blob: 9199fc3d6c25609017fe42429b390e0b8896b054 [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"
Alexis Huntc5575cc2011-02-26 19:13:13 +000024#include "clang/AST/ExprCXX.h"
Douglas Gregorb139cd52010-05-01 20:49:11 +000025#include "clang/AST/RecordLayout.h"
26#include "clang/AST/StmtVisitor.h"
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +000027#include "clang/AST/TypeLoc.h"
Douglas Gregordff6a8e2008-10-22 21:13:31 +000028#include "clang/AST/TypeOrdering.h"
John McCall8b0666c2010-08-20 18:27:03 +000029#include "clang/Sema/DeclSpec.h"
30#include "clang/Sema/ParsedTemplate.h"
Anders Carlssond624e162009-08-26 23:45:07 +000031#include "clang/Basic/PartialDiagnostic.h"
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +000032#include "clang/Lex/Preprocessor.h"
John McCalla1e130b2010-08-25 07:03:20 +000033#include "llvm/ADT/DenseSet.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000034#include "llvm/ADT/STLExtras.h"
Douglas Gregor29a92472008-10-22 17:49:05 +000035#include <map>
Douglas Gregor36d1b142009-10-06 17:59:45 +000036#include <set>
Chris Lattner199abbc2008-04-08 05:04:30 +000037
38using namespace clang;
39
Chris Lattner58258242008-04-10 02:22:51 +000040//===----------------------------------------------------------------------===//
41// CheckDefaultArgumentVisitor
42//===----------------------------------------------------------------------===//
43
Chris Lattnerb0d38442008-04-12 23:52:44 +000044namespace {
45 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
46 /// the default argument of a parameter to determine whether it
47 /// contains any ill-formed subexpressions. For example, this will
48 /// diagnose the use of local variables or parameters within the
49 /// default argument expression.
Benjamin Kramer337e3a52009-11-28 19:45:26 +000050 class CheckDefaultArgumentVisitor
Chris Lattner574dee62008-07-26 22:17:49 +000051 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattnerb0d38442008-04-12 23:52:44 +000052 Expr *DefaultArg;
53 Sema *S;
Chris Lattner58258242008-04-10 02:22:51 +000054
Chris Lattnerb0d38442008-04-12 23:52:44 +000055 public:
Mike Stump11289f42009-09-09 15:08:12 +000056 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattnerb0d38442008-04-12 23:52:44 +000057 : DefaultArg(defarg), S(s) {}
Chris Lattner58258242008-04-10 02:22:51 +000058
Chris Lattnerb0d38442008-04-12 23:52:44 +000059 bool VisitExpr(Expr *Node);
60 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor97a9c812008-11-04 14:32:21 +000061 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattnerb0d38442008-04-12 23:52:44 +000062 };
Chris Lattner58258242008-04-10 02:22:51 +000063
Chris Lattnerb0d38442008-04-12 23:52:44 +000064 /// VisitExpr - Visit all of the children of this expression.
65 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
66 bool IsInvalid = false;
John McCall8322c3a2011-02-13 04:07:26 +000067 for (Stmt::child_range I = Node->children(); I; ++I)
Chris Lattner574dee62008-07-26 22:17:49 +000068 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
Anders Carlssonfc1eef42011-01-22 17:51:53 +0000524 // C++ [class.derived]p2:
525 // If a class is marked with the class-virt-specifier final and it appears
526 // as a base-type-specifier in a base-clause (10 class.derived), the program
527 // is ill-formed.
Anders Carlsson1eb95962011-01-24 16:26:15 +0000528 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
Anders Carlssonfc1eef42011-01-22 17:51:53 +0000529 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
530 << CXXBaseDecl->getDeclName();
531 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
532 << CXXBaseDecl->getDeclName();
533 return 0;
534 }
535
John McCall3696dcb2010-08-17 07:23:57 +0000536 if (BaseDecl->isInvalidDecl())
537 Class->setInvalidDecl();
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000538
539 // Create the base specifier.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000540 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +0000541 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +0000542 Access, TInfo, EllipsisLoc);
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000543}
544
Douglas Gregor556877c2008-04-13 21:30:24 +0000545/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
546/// one entry in the base class list of a class specifier, for
Mike Stump11289f42009-09-09 15:08:12 +0000547/// example:
548/// class foo : public bar, virtual private baz {
Douglas Gregor556877c2008-04-13 21:30:24 +0000549/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallfaf5fb42010-08-26 23:41:50 +0000550BaseResult
John McCall48871652010-08-21 09:40:31 +0000551Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Douglas Gregor29a92472008-10-22 17:49:05 +0000552 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +0000553 ParsedType basetype, SourceLocation BaseLoc,
554 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000555 if (!classdecl)
556 return true;
557
Douglas Gregorc40290e2009-03-09 23:48:35 +0000558 AdjustDeclIfTemplate(classdecl);
John McCall48871652010-08-21 09:40:31 +0000559 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregorbeab56e2010-02-27 00:25:28 +0000560 if (!Class)
561 return true;
562
Nick Lewycky19b9f952010-07-26 16:56:01 +0000563 TypeSourceInfo *TInfo = 0;
564 GetTypeFromParser(basetype, &TInfo);
Douglas Gregor506bd562010-12-13 22:49:22 +0000565
Douglas Gregor752a5952011-01-03 22:36:02 +0000566 if (EllipsisLoc.isInvalid() &&
567 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregor506bd562010-12-13 22:49:22 +0000568 UPPC_BaseType))
569 return true;
Douglas Gregor752a5952011-01-03 22:36:02 +0000570
Douglas Gregor463421d2009-03-03 04:44:36 +0000571 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregor752a5952011-01-03 22:36:02 +0000572 Virtual, Access, TInfo,
573 EllipsisLoc))
Douglas Gregor463421d2009-03-03 04:44:36 +0000574 return BaseSpec;
Mike Stump11289f42009-09-09 15:08:12 +0000575
Douglas Gregor463421d2009-03-03 04:44:36 +0000576 return true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000577}
Douglas Gregor556877c2008-04-13 21:30:24 +0000578
Douglas Gregor463421d2009-03-03 04:44:36 +0000579/// \brief Performs the actual work of attaching the given base class
580/// specifiers to a C++ class.
581bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
582 unsigned NumBases) {
583 if (NumBases == 0)
584 return false;
Douglas Gregor29a92472008-10-22 17:49:05 +0000585
586 // Used to keep track of which base types we have already seen, so
587 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000588 // that the key is always the unqualified canonical type of the base
589 // class.
Douglas Gregor29a92472008-10-22 17:49:05 +0000590 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
591
592 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000593 unsigned NumGoodBases = 0;
Douglas Gregor463421d2009-03-03 04:44:36 +0000594 bool Invalid = false;
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000595 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump11289f42009-09-09 15:08:12 +0000596 QualType NewBaseType
Douglas Gregor463421d2009-03-03 04:44:36 +0000597 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000598 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Fariborz Jahanian2792f302010-05-20 23:34:56 +0000599 if (!Class->hasObjectMember()) {
600 if (const RecordType *FDTTy =
601 NewBaseType.getTypePtr()->getAs<RecordType>())
602 if (FDTTy->getDecl()->hasObjectMember())
603 Class->setHasObjectMember(true);
604 }
605
Douglas Gregor29a92472008-10-22 17:49:05 +0000606 if (KnownBaseTypes[NewBaseType]) {
607 // C++ [class.mi]p3:
608 // A class shall not be specified as a direct base class of a
609 // derived class more than once.
Douglas Gregor463421d2009-03-03 04:44:36 +0000610 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +0000611 diag::err_duplicate_base_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000612 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor463421d2009-03-03 04:44:36 +0000613 << Bases[idx]->getSourceRange();
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000614
615 // Delete the duplicate base class specifier; we're going to
616 // overwrite its pointer later.
Douglas Gregorb77af8f2009-07-22 20:55:49 +0000617 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +0000618
619 Invalid = true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000620 } else {
621 // Okay, add this new base class.
Douglas Gregor463421d2009-03-03 04:44:36 +0000622 KnownBaseTypes[NewBaseType] = Bases[idx];
623 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregor29a92472008-10-22 17:49:05 +0000624 }
625 }
626
627 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor4a62bdf2010-02-11 01:30:34 +0000628 Class->setBases(Bases, NumGoodBases);
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000629
630 // Delete the remaining (good) base class specifiers, since their
631 // data has been copied into the CXXRecordDecl.
632 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregorb77af8f2009-07-22 20:55:49 +0000633 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +0000634
635 return Invalid;
636}
637
638/// ActOnBaseSpecifiers - Attach the given base specifiers to the
639/// class, after checking whether there are any duplicate base
640/// classes.
John McCall48871652010-08-21 09:40:31 +0000641void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, BaseTy **Bases,
Douglas Gregor463421d2009-03-03 04:44:36 +0000642 unsigned NumBases) {
643 if (!ClassDecl || !Bases || !NumBases)
644 return;
645
646 AdjustDeclIfTemplate(ClassDecl);
John McCall48871652010-08-21 09:40:31 +0000647 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor463421d2009-03-03 04:44:36 +0000648 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregor556877c2008-04-13 21:30:24 +0000649}
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +0000650
John McCalle78aac42010-03-10 03:28:59 +0000651static CXXRecordDecl *GetClassForType(QualType T) {
652 if (const RecordType *RT = T->getAs<RecordType>())
653 return cast<CXXRecordDecl>(RT->getDecl());
654 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
655 return ICT->getDecl();
656 else
657 return 0;
658}
659
Douglas Gregor36d1b142009-10-06 17:59:45 +0000660/// \brief Determine whether the type \p Derived is a C++ class that is
661/// derived from the type \p Base.
662bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
663 if (!getLangOptions().CPlusPlus)
664 return false;
John McCalle78aac42010-03-10 03:28:59 +0000665
666 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
667 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000668 return false;
669
John McCalle78aac42010-03-10 03:28:59 +0000670 CXXRecordDecl *BaseRD = GetClassForType(Base);
671 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000672 return false;
673
John McCall67da35c2010-02-04 22:26:26 +0000674 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
675 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregor36d1b142009-10-06 17:59:45 +0000676}
677
678/// \brief Determine whether the type \p Derived is a C++ class that is
679/// derived from the type \p Base.
680bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
681 if (!getLangOptions().CPlusPlus)
682 return false;
683
John McCalle78aac42010-03-10 03:28:59 +0000684 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
685 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000686 return false;
687
John McCalle78aac42010-03-10 03:28:59 +0000688 CXXRecordDecl *BaseRD = GetClassForType(Base);
689 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000690 return false;
691
Douglas Gregor36d1b142009-10-06 17:59:45 +0000692 return DerivedRD->isDerivedFrom(BaseRD, Paths);
693}
694
Anders Carlssona70cff62010-04-24 19:06:50 +0000695void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallcf142162010-08-07 06:22:56 +0000696 CXXCastPath &BasePathArray) {
Anders Carlssona70cff62010-04-24 19:06:50 +0000697 assert(BasePathArray.empty() && "Base path array must be empty!");
698 assert(Paths.isRecordingPaths() && "Must record paths!");
699
700 const CXXBasePath &Path = Paths.front();
701
702 // We first go backward and check if we have a virtual base.
703 // FIXME: It would be better if CXXBasePath had the base specifier for
704 // the nearest virtual base.
705 unsigned Start = 0;
706 for (unsigned I = Path.size(); I != 0; --I) {
707 if (Path[I - 1].Base->isVirtual()) {
708 Start = I - 1;
709 break;
710 }
711 }
712
713 // Now add all bases.
714 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallcf142162010-08-07 06:22:56 +0000715 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlssona70cff62010-04-24 19:06:50 +0000716}
717
Douglas Gregor88d292c2010-05-13 16:44:06 +0000718/// \brief Determine whether the given base path includes a virtual
719/// base class.
John McCallcf142162010-08-07 06:22:56 +0000720bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
721 for (CXXCastPath::const_iterator B = BasePath.begin(),
722 BEnd = BasePath.end();
Douglas Gregor88d292c2010-05-13 16:44:06 +0000723 B != BEnd; ++B)
724 if ((*B)->isVirtual())
725 return true;
726
727 return false;
728}
729
Douglas Gregor36d1b142009-10-06 17:59:45 +0000730/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
731/// conversion (where Derived and Base are class types) is
732/// well-formed, meaning that the conversion is unambiguous (and
733/// that all of the base classes are accessible). Returns true
734/// and emits a diagnostic if the code is ill-formed, returns false
735/// otherwise. Loc is the location where this routine should point to
736/// if there is an error, and Range is the source range to highlight
737/// if there is an error.
738bool
739Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall1064d7e2010-03-16 05:22:47 +0000740 unsigned InaccessibleBaseID,
Douglas Gregor36d1b142009-10-06 17:59:45 +0000741 unsigned AmbigiousBaseConvID,
742 SourceLocation Loc, SourceRange Range,
Anders Carlsson7afe4242010-04-24 17:11:09 +0000743 DeclarationName Name,
John McCallcf142162010-08-07 06:22:56 +0000744 CXXCastPath *BasePath) {
Douglas Gregor36d1b142009-10-06 17:59:45 +0000745 // First, determine whether the path from Derived to Base is
746 // ambiguous. This is slightly more expensive than checking whether
747 // the Derived to Base conversion exists, because here we need to
748 // explore multiple paths to determine if there is an ambiguity.
749 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
750 /*DetectVirtual=*/false);
751 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
752 assert(DerivationOkay &&
753 "Can only be used with a derived-to-base conversion");
754 (void)DerivationOkay;
755
756 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlssona70cff62010-04-24 19:06:50 +0000757 if (InaccessibleBaseID) {
758 // Check that the base class can be accessed.
759 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
760 InaccessibleBaseID)) {
761 case AR_inaccessible:
762 return true;
763 case AR_accessible:
764 case AR_dependent:
765 case AR_delayed:
766 break;
Anders Carlsson7afe4242010-04-24 17:11:09 +0000767 }
John McCall5b0829a2010-02-10 09:31:12 +0000768 }
Anders Carlssona70cff62010-04-24 19:06:50 +0000769
770 // Build a base path if necessary.
771 if (BasePath)
772 BuildBasePathArray(Paths, *BasePath);
773 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +0000774 }
775
776 // We know that the derived-to-base conversion is ambiguous, and
777 // we're going to produce a diagnostic. Perform the derived-to-base
778 // search just one more time to compute all of the possible paths so
779 // that we can print them out. This is more expensive than any of
780 // the previous derived-to-base checks we've done, but at this point
781 // performance isn't as much of an issue.
782 Paths.clear();
783 Paths.setRecordingPaths(true);
784 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
785 assert(StillOkay && "Can only be used with a derived-to-base conversion");
786 (void)StillOkay;
787
788 // Build up a textual representation of the ambiguous paths, e.g.,
789 // D -> B -> A, that will be used to illustrate the ambiguous
790 // conversions in the diagnostic. We only print one of the paths
791 // to each base class subobject.
792 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
793
794 Diag(Loc, AmbigiousBaseConvID)
795 << Derived << Base << PathDisplayStr << Range << Name;
796 return true;
797}
798
799bool
800Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redl7c353682009-11-14 21:15:49 +0000801 SourceLocation Loc, SourceRange Range,
John McCallcf142162010-08-07 06:22:56 +0000802 CXXCastPath *BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +0000803 bool IgnoreAccess) {
Douglas Gregor36d1b142009-10-06 17:59:45 +0000804 return CheckDerivedToBaseConversion(Derived, Base,
John McCall1064d7e2010-03-16 05:22:47 +0000805 IgnoreAccess ? 0
806 : diag::err_upcast_to_inaccessible_base,
Douglas Gregor36d1b142009-10-06 17:59:45 +0000807 diag::err_ambiguous_derived_to_base_conv,
Anders Carlsson7afe4242010-04-24 17:11:09 +0000808 Loc, Range, DeclarationName(),
809 BasePath);
Douglas Gregor36d1b142009-10-06 17:59:45 +0000810}
811
812
813/// @brief Builds a string representing ambiguous paths from a
814/// specific derived class to different subobjects of the same base
815/// class.
816///
817/// This function builds a string that can be used in error messages
818/// to show the different paths that one can take through the
819/// inheritance hierarchy to go from the derived class to different
820/// subobjects of a base class. The result looks something like this:
821/// @code
822/// struct D -> struct B -> struct A
823/// struct D -> struct C -> struct A
824/// @endcode
825std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
826 std::string PathDisplayStr;
827 std::set<unsigned> DisplayedPaths;
828 for (CXXBasePaths::paths_iterator Path = Paths.begin();
829 Path != Paths.end(); ++Path) {
830 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
831 // We haven't displayed a path to this particular base
832 // class subobject yet.
833 PathDisplayStr += "\n ";
834 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
835 for (CXXBasePath::const_iterator Element = Path->begin();
836 Element != Path->end(); ++Element)
837 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
838 }
839 }
840
841 return PathDisplayStr;
842}
843
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000844//===----------------------------------------------------------------------===//
845// C++ class member Handling
846//===----------------------------------------------------------------------===//
847
Abramo Bagnarad7340582010-06-05 05:09:32 +0000848/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
John McCall48871652010-08-21 09:40:31 +0000849Decl *Sema::ActOnAccessSpecifier(AccessSpecifier Access,
850 SourceLocation ASLoc,
851 SourceLocation ColonLoc) {
Abramo Bagnarad7340582010-06-05 05:09:32 +0000852 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCall48871652010-08-21 09:40:31 +0000853 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnarad7340582010-06-05 05:09:32 +0000854 ASLoc, ColonLoc);
855 CurContext->addHiddenDecl(ASDecl);
John McCall48871652010-08-21 09:40:31 +0000856 return ASDecl;
Abramo Bagnarad7340582010-06-05 05:09:32 +0000857}
858
Anders Carlssonfd835532011-01-20 05:57:14 +0000859/// CheckOverrideControl - Check C++0x override control semantics.
Anders Carlssonc87f8612011-01-20 06:29:02 +0000860void Sema::CheckOverrideControl(const Decl *D) {
Anders Carlssonfd835532011-01-20 05:57:14 +0000861 const CXXMethodDecl *MD = llvm::dyn_cast<CXXMethodDecl>(D);
862 if (!MD || !MD->isVirtual())
863 return;
864
Anders Carlssonfa8e5d32011-01-20 06:33:26 +0000865 if (MD->isDependentContext())
866 return;
867
Anders Carlssonfd835532011-01-20 05:57:14 +0000868 // C++0x [class.virtual]p3:
869 // If a virtual function is marked with the virt-specifier override and does
870 // not override a member function of a base class,
871 // the program is ill-formed.
872 bool HasOverriddenMethods =
873 MD->begin_overridden_methods() != MD->end_overridden_methods();
Anders Carlsson1eb95962011-01-24 16:26:15 +0000874 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) {
Anders Carlssonc87f8612011-01-20 06:29:02 +0000875 Diag(MD->getLocation(),
Anders Carlssonfd835532011-01-20 05:57:14 +0000876 diag::err_function_marked_override_not_overriding)
877 << MD->getDeclName();
878 return;
879 }
Anders Carlsson7d59a682011-01-22 22:23:37 +0000880
881 // C++0x [class.derived]p8:
882 // In a class definition marked with the class-virt-specifier explicit,
883 // if a virtual member function that is neither implicitly-declared nor a
884 // destructor overrides a member function of a base class and it is not
885 // marked with the virt-specifier override, the program is ill-formed.
Anders Carlsson1eb95962011-01-24 16:26:15 +0000886 if (MD->getParent()->hasAttr<ExplicitAttr>() && !isa<CXXDestructorDecl>(MD) &&
887 HasOverriddenMethods && !MD->hasAttr<OverrideAttr>()) {
Anders Carlsson7d59a682011-01-22 22:23:37 +0000888 llvm::SmallVector<const CXXMethodDecl*, 4>
889 OverriddenMethods(MD->begin_overridden_methods(),
890 MD->end_overridden_methods());
891
892 Diag(MD->getLocation(), diag::err_function_overriding_without_override)
893 << MD->getDeclName()
894 << (unsigned)OverriddenMethods.size();
895
896 for (unsigned I = 0; I != OverriddenMethods.size(); ++I)
897 Diag(OverriddenMethods[I]->getLocation(),
898 diag::note_overridden_virtual_function);
899 }
Anders Carlssonfd835532011-01-20 05:57:14 +0000900}
901
Anders Carlsson3f610c72011-01-20 16:25:36 +0000902/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
903/// function overrides a virtual member function marked 'final', according to
904/// C++0x [class.virtual]p3.
905bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
906 const CXXMethodDecl *Old) {
Anders Carlsson1eb95962011-01-24 16:26:15 +0000907 if (!Old->hasAttr<FinalAttr>())
Anders Carlsson19588aa2011-01-23 21:07:30 +0000908 return false;
909
910 Diag(New->getLocation(), diag::err_final_function_overridden)
911 << New->getDeclName();
912 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
913 return true;
Anders Carlsson3f610c72011-01-20 16:25:36 +0000914}
915
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000916/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
917/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
918/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnereb4373d2009-04-12 22:37:57 +0000919/// any.
John McCall48871652010-08-21 09:40:31 +0000920Decl *
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000921Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +0000922 MultiTemplateParamsArg TemplateParameterLists,
Anders Carlssondb36b802011-01-20 03:57:25 +0000923 ExprTy *BW, const VirtSpecifiers &VS,
924 ExprTy *InitExpr, bool IsDefinition,
Sebastian Redld6f78502009-11-24 23:38:44 +0000925 bool Deleted) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000926 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000927 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
928 DeclarationName Name = NameInfo.getName();
929 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor23ab7452010-11-09 03:31:16 +0000930
931 // For anonymous bitfields, the location should point to the type.
932 if (Loc.isInvalid())
933 Loc = D.getSourceRange().getBegin();
934
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000935 Expr *BitWidth = static_cast<Expr*>(BW);
936 Expr *Init = static_cast<Expr*>(InitExpr);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000937
John McCallb1cd7da2010-06-04 08:34:12 +0000938 assert(isa<CXXRecordDecl>(CurContext));
John McCall07e91c02009-08-06 02:15:43 +0000939 assert(!DS.isFriendSpecified());
940
John McCallb1cd7da2010-06-04 08:34:12 +0000941 bool isFunc = false;
942 if (D.isFunctionDeclarator())
943 isFunc = true;
944 else if (D.getNumTypeObjects() == 0 &&
945 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename) {
John McCallba7bf592010-08-24 05:47:05 +0000946 QualType TDType = GetTypeFromParser(DS.getRepAsType());
John McCallb1cd7da2010-06-04 08:34:12 +0000947 isFunc = TDType->isFunctionType();
948 }
949
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000950 // C++ 9.2p6: A member shall not be declared to have automatic storage
951 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000952 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
953 // data members and cannot be applied to names declared const or static,
954 // and cannot be applied to reference members.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000955 switch (DS.getStorageClassSpec()) {
956 case DeclSpec::SCS_unspecified:
957 case DeclSpec::SCS_typedef:
958 case DeclSpec::SCS_static:
959 // FALL THROUGH.
960 break;
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000961 case DeclSpec::SCS_mutable:
962 if (isFunc) {
963 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattner3b054132008-11-19 05:08:23 +0000964 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000965 else
Chris Lattner3b054132008-11-19 05:08:23 +0000966 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +0000967
Sebastian Redl8071edb2008-11-17 23:24:37 +0000968 // FIXME: It would be nicer if the keyword was ignored only for this
969 // declarator. Otherwise we could get follow-up errors.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000970 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000971 }
972 break;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000973 default:
974 if (DS.getStorageClassSpecLoc().isValid())
975 Diag(DS.getStorageClassSpecLoc(),
976 diag::err_storageclass_invalid_for_member);
977 else
978 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
979 D.getMutableDeclSpec().ClearStorageClassSpecs();
980 }
981
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000982 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
983 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +0000984 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000985
986 Decl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +0000987 if (isInstField) {
Douglas Gregora007d362010-10-13 22:19:53 +0000988 CXXScopeSpec &SS = D.getCXXScopeSpec();
989
990
991 if (SS.isSet() && !SS.isInvalid()) {
992 // The user provided a superfluous scope specifier inside a class
993 // definition:
994 //
995 // class X {
996 // int X::member;
997 // };
998 DeclContext *DC = 0;
999 if ((DC = computeDeclContext(SS, false)) && DC->Equals(CurContext))
1000 Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification)
1001 << Name << FixItHint::CreateRemoval(SS.getRange());
1002 else
1003 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1004 << Name << SS.getRange();
1005
1006 SS.clear();
1007 }
1008
Douglas Gregor3447e762009-08-20 22:52:58 +00001009 // FIXME: Check for template parameters!
Douglas Gregorc4356532010-12-16 00:46:58 +00001010 // FIXME: Check that the name is an identifier!
Douglas Gregor4261e4c2009-03-11 20:50:30 +00001011 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
1012 AS);
Chris Lattner97e277e2009-03-05 23:03:49 +00001013 assert(Member && "HandleField never returns null");
Chris Lattner73bf7b42009-03-05 22:45:59 +00001014 } else {
John McCall48871652010-08-21 09:40:31 +00001015 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition);
Chris Lattner97e277e2009-03-05 23:03:49 +00001016 if (!Member) {
John McCall48871652010-08-21 09:40:31 +00001017 return 0;
Chris Lattner97e277e2009-03-05 23:03:49 +00001018 }
Chris Lattnerd26760a2009-03-05 23:01:03 +00001019
1020 // Non-instance-fields can't have a bitfield.
1021 if (BitWidth) {
1022 if (Member->isInvalidDecl()) {
1023 // don't emit another diagnostic.
Douglas Gregor212cab32009-03-11 20:22:50 +00001024 } else if (isa<VarDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00001025 // C++ 9.6p3: A bit-field shall not be a static member.
1026 // "static member 'A' cannot be a bit-field"
1027 Diag(Loc, diag::err_static_not_bitfield)
1028 << Name << BitWidth->getSourceRange();
1029 } else if (isa<TypedefDecl>(Member)) {
1030 // "typedef member 'x' cannot be a bit-field"
1031 Diag(Loc, diag::err_typedef_not_bitfield)
1032 << Name << BitWidth->getSourceRange();
1033 } else {
1034 // A function typedef ("typedef int f(); f a;").
1035 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1036 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +00001037 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +00001038 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +00001039 }
Mike Stump11289f42009-09-09 15:08:12 +00001040
Chris Lattnerd26760a2009-03-05 23:01:03 +00001041 BitWidth = 0;
1042 Member->setInvalidDecl();
1043 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +00001044
1045 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +00001046
Douglas Gregor3447e762009-08-20 22:52:58 +00001047 // If we have declared a member function template, set the access of the
1048 // templated declaration as well.
1049 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1050 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +00001051 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001052
Anders Carlsson13a69102011-01-20 04:34:22 +00001053 if (VS.isOverrideSpecified()) {
1054 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1055 if (!MD || !MD->isVirtual()) {
1056 Diag(Member->getLocStart(),
1057 diag::override_keyword_only_allowed_on_virtual_member_functions)
1058 << "override" << FixItHint::CreateRemoval(VS.getOverrideLoc());
Anders Carlssonfd835532011-01-20 05:57:14 +00001059 } else
Anders Carlsson1eb95962011-01-24 16:26:15 +00001060 MD->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
Anders Carlsson13a69102011-01-20 04:34:22 +00001061 }
1062 if (VS.isFinalSpecified()) {
1063 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1064 if (!MD || !MD->isVirtual()) {
1065 Diag(Member->getLocStart(),
1066 diag::override_keyword_only_allowed_on_virtual_member_functions)
1067 << "final" << FixItHint::CreateRemoval(VS.getFinalLoc());
Anders Carlssonfd835532011-01-20 05:57:14 +00001068 } else
Anders Carlsson1eb95962011-01-24 16:26:15 +00001069 MD->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlsson13a69102011-01-20 04:34:22 +00001070 }
Anders Carlssonfd835532011-01-20 05:57:14 +00001071
Anders Carlssonc87f8612011-01-20 06:29:02 +00001072 CheckOverrideControl(Member);
Anders Carlssonfd835532011-01-20 05:57:14 +00001073
Douglas Gregor92751d42008-11-17 22:58:34 +00001074 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001075
Douglas Gregor0c880302009-03-11 23:00:04 +00001076 if (Init)
Richard Smith30482bc2011-02-20 03:19:35 +00001077 AddInitializerToDecl(Member, Init, false,
1078 DS.getTypeSpecType() == DeclSpec::TST_auto);
Sebastian Redl42e92c42009-04-12 17:16:29 +00001079 if (Deleted) // FIXME: Source location is not very good.
John McCall48871652010-08-21 09:40:31 +00001080 SetDeclDeleted(Member, D.getSourceRange().getBegin());
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001081
Richard Smithb2bc2e62011-02-21 20:05:19 +00001082 FinalizeDeclaration(Member);
1083
John McCall25849ca2011-02-15 07:12:36 +00001084 if (isInstField)
Douglas Gregor91f84212008-12-11 16:49:14 +00001085 FieldCollector->Add(cast<FieldDecl>(Member));
John McCall48871652010-08-21 09:40:31 +00001086 return Member;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001087}
1088
Douglas Gregor15e77a22009-12-31 09:10:24 +00001089/// \brief Find the direct and/or virtual base specifiers that
1090/// correspond to the given base type, for use in base initialization
1091/// within a constructor.
1092static bool FindBaseInitializer(Sema &SemaRef,
1093 CXXRecordDecl *ClassDecl,
1094 QualType BaseType,
1095 const CXXBaseSpecifier *&DirectBaseSpec,
1096 const CXXBaseSpecifier *&VirtualBaseSpec) {
1097 // First, check for a direct base class.
1098 DirectBaseSpec = 0;
1099 for (CXXRecordDecl::base_class_const_iterator Base
1100 = ClassDecl->bases_begin();
1101 Base != ClassDecl->bases_end(); ++Base) {
1102 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1103 // We found a direct base of this type. That's what we're
1104 // initializing.
1105 DirectBaseSpec = &*Base;
1106 break;
1107 }
1108 }
1109
1110 // Check for a virtual base class.
1111 // FIXME: We might be able to short-circuit this if we know in advance that
1112 // there are no virtual bases.
1113 VirtualBaseSpec = 0;
1114 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1115 // We haven't found a base yet; search the class hierarchy for a
1116 // virtual base class.
1117 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1118 /*DetectVirtual=*/false);
1119 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1120 BaseType, Paths)) {
1121 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1122 Path != Paths.end(); ++Path) {
1123 if (Path->back().Base->isVirtual()) {
1124 VirtualBaseSpec = Path->back().Base;
1125 break;
1126 }
1127 }
1128 }
1129 }
1130
1131 return DirectBaseSpec || VirtualBaseSpec;
1132}
1133
Douglas Gregore8381c02008-11-05 04:29:56 +00001134/// ActOnMemInitializer - Handle a C++ member initializer.
John McCallfaf5fb42010-08-26 23:41:50 +00001135MemInitResult
John McCall48871652010-08-21 09:40:31 +00001136Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +00001137 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001138 CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +00001139 IdentifierInfo *MemberOrBase,
John McCallba7bf592010-08-24 05:47:05 +00001140 ParsedType TemplateTypeTy,
Douglas Gregore8381c02008-11-05 04:29:56 +00001141 SourceLocation IdLoc,
1142 SourceLocation LParenLoc,
1143 ExprTy **Args, unsigned NumArgs,
Douglas Gregor44e7df62011-01-04 00:32:56 +00001144 SourceLocation RParenLoc,
1145 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001146 if (!ConstructorD)
1147 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001148
Douglas Gregorc8c277a2009-08-24 11:57:43 +00001149 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +00001150
1151 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00001152 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregore8381c02008-11-05 04:29:56 +00001153 if (!Constructor) {
1154 // The user wrote a constructor initializer on a function that is
1155 // not a C++ constructor. Ignore the error for now, because we may
1156 // have more member initializers coming; we'll diagnose it just
1157 // once in ActOnMemInitializers.
1158 return true;
1159 }
1160
1161 CXXRecordDecl *ClassDecl = Constructor->getParent();
1162
1163 // C++ [class.base.init]p2:
1164 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky9331ed82010-11-20 01:29:55 +00001165 // constructor's class and, if not found in that scope, are looked
1166 // up in the scope containing the constructor's definition.
1167 // [Note: if the constructor's class contains a member with the
1168 // same name as a direct or virtual base class of the class, a
1169 // mem-initializer-id naming the member or base class and composed
1170 // of a single identifier refers to the class member. A
Douglas Gregore8381c02008-11-05 04:29:56 +00001171 // mem-initializer-id for the hidden base class may be specified
1172 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00001173 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001174 // Look for a member, first.
1175 FieldDecl *Member = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001176 DeclContext::lookup_result Result
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001177 = ClassDecl->lookup(MemberOrBase);
Francois Pichet783dd6e2010-11-21 06:08:52 +00001178 if (Result.first != Result.second) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001179 Member = dyn_cast<FieldDecl>(*Result.first);
Francois Pichet783dd6e2010-11-21 06:08:52 +00001180
Douglas Gregor44e7df62011-01-04 00:32:56 +00001181 if (Member) {
1182 if (EllipsisLoc.isValid())
1183 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1184 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1185
Francois Pichetd583da02010-12-04 09:14:42 +00001186 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001187 LParenLoc, RParenLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00001188 }
1189
Francois Pichetd583da02010-12-04 09:14:42 +00001190 // Handle anonymous union case.
1191 if (IndirectFieldDecl* IndirectField
Douglas Gregor44e7df62011-01-04 00:32:56 +00001192 = dyn_cast<IndirectFieldDecl>(*Result.first)) {
1193 if (EllipsisLoc.isValid())
1194 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1195 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1196
Francois Pichetd583da02010-12-04 09:14:42 +00001197 return BuildMemberInitializer(IndirectField, (Expr**)Args,
1198 NumArgs, IdLoc,
1199 LParenLoc, RParenLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00001200 }
Francois Pichetd583da02010-12-04 09:14:42 +00001201 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001202 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001203 // It didn't name a member, so see if it names a class.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001204 QualType BaseType;
John McCallbcd03502009-12-07 02:54:59 +00001205 TypeSourceInfo *TInfo = 0;
John McCallb5a0d312009-12-21 10:41:20 +00001206
1207 if (TemplateTypeTy) {
John McCallbcd03502009-12-07 02:54:59 +00001208 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
John McCallb5a0d312009-12-21 10:41:20 +00001209 } else {
1210 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1211 LookupParsedName(R, S, &SS);
1212
1213 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1214 if (!TyD) {
1215 if (R.isAmbiguous()) return true;
1216
John McCallda6841b2010-04-09 19:01:14 +00001217 // We don't want access-control diagnostics here.
1218 R.suppressDiagnostics();
1219
Douglas Gregora3b624a2010-01-19 06:46:48 +00001220 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1221 bool NotUnknownSpecialization = false;
1222 DeclContext *DC = computeDeclContext(SS, false);
1223 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1224 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1225
1226 if (!NotUnknownSpecialization) {
1227 // When the scope specifier can refer to a member of an unknown
1228 // specialization, we take it as a type name.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00001229 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
1230 SS.getWithLocInContext(Context),
1231 *MemberOrBase, IdLoc);
Douglas Gregor281c4862010-03-07 23:26:22 +00001232 if (BaseType.isNull())
1233 return true;
1234
Douglas Gregora3b624a2010-01-19 06:46:48 +00001235 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00001236 R.setLookupName(MemberOrBase);
Douglas Gregora3b624a2010-01-19 06:46:48 +00001237 }
1238 }
1239
Douglas Gregor15e77a22009-12-31 09:10:24 +00001240 // If no results were found, try to correct typos.
Douglas Gregora3b624a2010-01-19 06:46:48 +00001241 if (R.empty() && BaseType.isNull() &&
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001242 CorrectTypo(R, S, &SS, ClassDecl, 0, CTC_NoKeywords) &&
1243 R.isSingleResult()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001244 if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00001245 if (Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl)) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001246 // We have found a non-static data member with a similar
1247 // name to what was typed; complain and initialize that
1248 // member.
1249 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1250 << MemberOrBase << true << R.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +00001251 << FixItHint::CreateReplacement(R.getNameLoc(),
1252 R.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00001253 Diag(Member->getLocation(), diag::note_previous_decl)
1254 << Member->getDeclName();
Douglas Gregor15e77a22009-12-31 09:10:24 +00001255
1256 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1257 LParenLoc, RParenLoc);
1258 }
1259 } else if (TypeDecl *Type = R.getAsSingle<TypeDecl>()) {
1260 const CXXBaseSpecifier *DirectBaseSpec;
1261 const CXXBaseSpecifier *VirtualBaseSpec;
1262 if (FindBaseInitializer(*this, ClassDecl,
1263 Context.getTypeDeclType(Type),
1264 DirectBaseSpec, VirtualBaseSpec)) {
1265 // We have found a direct or virtual base class with a
1266 // similar name to what was typed; complain and initialize
1267 // that base class.
1268 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1269 << MemberOrBase << false << R.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +00001270 << FixItHint::CreateReplacement(R.getNameLoc(),
1271 R.getLookupName().getAsString());
Douglas Gregor43a08572010-01-07 00:26:25 +00001272
1273 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1274 : VirtualBaseSpec;
1275 Diag(BaseSpec->getSourceRange().getBegin(),
1276 diag::note_base_class_specified_here)
1277 << BaseSpec->getType()
1278 << BaseSpec->getSourceRange();
1279
Douglas Gregor15e77a22009-12-31 09:10:24 +00001280 TyD = Type;
1281 }
1282 }
1283 }
1284
Douglas Gregora3b624a2010-01-19 06:46:48 +00001285 if (!TyD && BaseType.isNull()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001286 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1287 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1288 return true;
1289 }
John McCallb5a0d312009-12-21 10:41:20 +00001290 }
1291
Douglas Gregora3b624a2010-01-19 06:46:48 +00001292 if (BaseType.isNull()) {
1293 BaseType = Context.getTypeDeclType(TyD);
1294 if (SS.isSet()) {
1295 NestedNameSpecifier *Qualifier =
1296 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCallb5a0d312009-12-21 10:41:20 +00001297
Douglas Gregora3b624a2010-01-19 06:46:48 +00001298 // FIXME: preserve source range information
Abramo Bagnara6150c882010-05-11 21:36:43 +00001299 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregora3b624a2010-01-19 06:46:48 +00001300 }
John McCallb5a0d312009-12-21 10:41:20 +00001301 }
1302 }
Mike Stump11289f42009-09-09 15:08:12 +00001303
John McCallbcd03502009-12-07 02:54:59 +00001304 if (!TInfo)
1305 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001306
John McCallbcd03502009-12-07 02:54:59 +00001307 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
Douglas Gregor44e7df62011-01-04 00:32:56 +00001308 LParenLoc, RParenLoc, ClassDecl, EllipsisLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00001309}
1310
John McCalle22a04a2009-11-04 23:02:40 +00001311/// Checks an initializer expression for use of uninitialized fields, such as
1312/// containing the field that is being initialized. Returns true if there is an
1313/// uninitialized field was used an updates the SourceLocation parameter; false
1314/// otherwise.
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001315static bool InitExprContainsUninitializedFields(const Stmt *S,
Francois Pichetd583da02010-12-04 09:14:42 +00001316 const ValueDecl *LhsField,
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001317 SourceLocation *L) {
Francois Pichetd583da02010-12-04 09:14:42 +00001318 assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField));
1319
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001320 if (isa<CallExpr>(S)) {
1321 // Do not descend into function calls or constructors, as the use
1322 // of an uninitialized field may be valid. One would have to inspect
1323 // the contents of the function/ctor to determine if it is safe or not.
1324 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1325 // may be safe, depending on what the function/ctor does.
1326 return false;
1327 }
1328 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
1329 const NamedDecl *RhsField = ME->getMemberDecl();
Anders Carlsson0f7e94f2010-10-06 02:43:25 +00001330
1331 if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) {
1332 // The member expression points to a static data member.
1333 assert(VD->isStaticDataMember() &&
1334 "Member points to non-static data member!");
Nick Lewycky300524242010-10-06 18:37:39 +00001335 (void)VD;
Anders Carlsson0f7e94f2010-10-06 02:43:25 +00001336 return false;
1337 }
1338
1339 if (isa<EnumConstantDecl>(RhsField)) {
1340 // The member expression points to an enum.
1341 return false;
1342 }
1343
John McCalle22a04a2009-11-04 23:02:40 +00001344 if (RhsField == LhsField) {
1345 // Initializing a field with itself. Throw a warning.
1346 // But wait; there are exceptions!
1347 // Exception #1: The field may not belong to this record.
1348 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001349 const Expr *base = ME->getBase();
John McCalle22a04a2009-11-04 23:02:40 +00001350 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1351 // Even though the field matches, it does not belong to this record.
1352 return false;
1353 }
1354 // None of the exceptions triggered; return true to indicate an
1355 // uninitialized field was used.
1356 *L = ME->getMemberLoc();
1357 return true;
1358 }
Argyrios Kyrtzidis03f0e2b2010-09-21 10:47:20 +00001359 } else if (isa<SizeOfAlignOfExpr>(S)) {
1360 // sizeof/alignof doesn't reference contents, do not warn.
1361 return false;
1362 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) {
1363 // address-of doesn't reference contents (the pointer may be dereferenced
1364 // in the same expression but it would be rare; and weird).
1365 if (UOE->getOpcode() == UO_AddrOf)
1366 return false;
John McCalle22a04a2009-11-04 23:02:40 +00001367 }
John McCall8322c3a2011-02-13 04:07:26 +00001368 for (Stmt::const_child_range it = S->children(); it; ++it) {
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001369 if (!*it) {
1370 // An expression such as 'member(arg ?: "")' may trigger this.
John McCalle22a04a2009-11-04 23:02:40 +00001371 continue;
1372 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001373 if (InitExprContainsUninitializedFields(*it, LhsField, L))
1374 return true;
John McCalle22a04a2009-11-04 23:02:40 +00001375 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001376 return false;
John McCalle22a04a2009-11-04 23:02:40 +00001377}
1378
John McCallfaf5fb42010-08-26 23:41:50 +00001379MemInitResult
Chandler Carruthd44c3102010-12-06 09:23:57 +00001380Sema::BuildMemberInitializer(ValueDecl *Member, Expr **Args,
Eli Friedman8e1433b2009-07-29 19:44:27 +00001381 unsigned NumArgs, SourceLocation IdLoc,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001382 SourceLocation LParenLoc,
Eli Friedman8e1433b2009-07-29 19:44:27 +00001383 SourceLocation RParenLoc) {
Chandler Carruthd44c3102010-12-06 09:23:57 +00001384 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
1385 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
1386 assert((DirectMember || IndirectMember) &&
Francois Pichetd583da02010-12-04 09:14:42 +00001387 "Member must be a FieldDecl or IndirectFieldDecl");
1388
Douglas Gregor266bb5f2010-11-05 22:21:31 +00001389 if (Member->isInvalidDecl())
1390 return true;
Chandler Carruthd44c3102010-12-06 09:23:57 +00001391
John McCalle22a04a2009-11-04 23:02:40 +00001392 // Diagnose value-uses of fields to initialize themselves, e.g.
1393 // foo(foo)
1394 // where foo is not also a parameter to the constructor.
John McCallc90f6d72009-11-04 23:13:52 +00001395 // TODO: implement -Wuninitialized and fold this into that framework.
John McCalle22a04a2009-11-04 23:02:40 +00001396 for (unsigned i = 0; i < NumArgs; ++i) {
1397 SourceLocation L;
1398 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1399 // FIXME: Return true in the case when other fields are used before being
1400 // uninitialized. For example, let this field be the i'th field. When
1401 // initializing the i'th field, throw a warning if any of the >= i'th
1402 // fields are used, as they are not yet initialized.
1403 // Right now we are only handling the case where the i'th field uses
1404 // itself in its initializer.
1405 Diag(L, diag::warn_field_is_uninit);
1406 }
1407 }
1408
Eli Friedman8e1433b2009-07-29 19:44:27 +00001409 bool HasDependentArg = false;
1410 for (unsigned i = 0; i < NumArgs; i++)
1411 HasDependentArg |= Args[i]->isTypeDependent();
1412
Chandler Carruthd44c3102010-12-06 09:23:57 +00001413 Expr *Init;
Eli Friedman9255adf2010-07-24 21:19:15 +00001414 if (Member->getType()->isDependentType() || HasDependentArg) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001415 // Can't check initialization for a member of dependent type or when
1416 // any of the arguments are type-dependent expressions.
Chandler Carruthd44c3102010-12-06 09:23:57 +00001417 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1418 RParenLoc);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001419
1420 // Erase any temporaries within this evaluation context; we're not
1421 // going to track them in the AST, since we'll be rebuilding the
1422 // ASTs during template instantiation.
1423 ExprTemporaries.erase(
1424 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1425 ExprTemporaries.end());
Chandler Carruthd44c3102010-12-06 09:23:57 +00001426 } else {
1427 // Initialize the member.
1428 InitializedEntity MemberEntity =
1429 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
1430 : InitializedEntity::InitializeMember(IndirectMember, 0);
1431 InitializationKind Kind =
1432 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc);
John McCallacf0ee52010-10-08 02:01:28 +00001433
Chandler Carruthd44c3102010-12-06 09:23:57 +00001434 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
1435
1436 ExprResult MemberInit =
1437 InitSeq.Perform(*this, MemberEntity, Kind,
1438 MultiExprArg(*this, Args, NumArgs), 0);
1439 if (MemberInit.isInvalid())
1440 return true;
1441
1442 CheckImplicitConversions(MemberInit.get(), LParenLoc);
1443
1444 // C++0x [class.base.init]p7:
1445 // The initialization of each base and member constitutes a
1446 // full-expression.
Douglas Gregora40433a2010-12-07 00:41:46 +00001447 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Chandler Carruthd44c3102010-12-06 09:23:57 +00001448 if (MemberInit.isInvalid())
1449 return true;
1450
1451 // If we are in a dependent context, template instantiation will
1452 // perform this type-checking again. Just save the arguments that we
1453 // received in a ParenListExpr.
1454 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1455 // of the information that we have about the member
1456 // initializer. However, deconstructing the ASTs is a dicey process,
1457 // and this approach is far more likely to get the corner cases right.
1458 if (CurContext->isDependentContext())
1459 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1460 RParenLoc);
1461 else
1462 Init = MemberInit.get();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001463 }
1464
Chandler Carruthd44c3102010-12-06 09:23:57 +00001465 if (DirectMember) {
Alexis Hunt1d792652011-01-08 20:30:50 +00001466 return new (Context) CXXCtorInitializer(Context, DirectMember,
Chandler Carruthd44c3102010-12-06 09:23:57 +00001467 IdLoc, LParenLoc, Init,
1468 RParenLoc);
1469 } else {
Alexis Hunt1d792652011-01-08 20:30:50 +00001470 return new (Context) CXXCtorInitializer(Context, IndirectMember,
Chandler Carruthd44c3102010-12-06 09:23:57 +00001471 IdLoc, LParenLoc, Init,
1472 RParenLoc);
1473 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00001474}
1475
John McCallfaf5fb42010-08-26 23:41:50 +00001476MemInitResult
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001477Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo,
1478 Expr **Args, unsigned NumArgs,
Alexis Huntc5575cc2011-02-26 19:13:13 +00001479 SourceLocation NameLoc,
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001480 SourceLocation LParenLoc,
1481 SourceLocation RParenLoc,
Alexis Huntc5575cc2011-02-26 19:13:13 +00001482 CXXRecordDecl *ClassDecl) {
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001483 SourceLocation Loc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
1484 if (!LangOpts.CPlusPlus0x)
1485 return Diag(Loc, diag::err_delegation_0x_only)
1486 << TInfo->getTypeLoc().getLocalSourceRange();
1487
Alexis Huntc5575cc2011-02-26 19:13:13 +00001488 // Initialize the object.
1489 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
1490 QualType(ClassDecl->getTypeForDecl(), 0));
1491 InitializationKind Kind =
1492 InitializationKind::CreateDirect(NameLoc, LParenLoc, RParenLoc);
1493
1494 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs);
1495
1496 ExprResult DelegationInit =
1497 InitSeq.Perform(*this, DelegationEntity, Kind,
1498 MultiExprArg(*this, Args, NumArgs), 0);
1499 if (DelegationInit.isInvalid())
1500 return true;
1501
1502 CXXConstructExpr *ConExpr = cast<CXXConstructExpr>(DelegationInit.get());
1503 CXXConstructorDecl *Constructor = ConExpr->getConstructor();
1504 assert(Constructor && "Delegating constructor with no target?");
1505
1506 CheckImplicitConversions(DelegationInit.get(), LParenLoc);
1507
1508 // C++0x [class.base.init]p7:
1509 // The initialization of each base and member constitutes a
1510 // full-expression.
1511 DelegationInit = MaybeCreateExprWithCleanups(DelegationInit);
1512 if (DelegationInit.isInvalid())
1513 return true;
1514
1515 // If we are in a dependent context, template instantiation will
1516 // perform this type-checking again. Just save the arguments that we
1517 // received in a ParenListExpr.
1518 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1519 // of the information that we have about the base
1520 // initializer. However, deconstructing the ASTs is a dicey process,
1521 // and this approach is far more likely to get the corner cases right.
1522 if (CurContext->isDependentContext()) {
1523 ExprResult Init
1524 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args,
1525 NumArgs, RParenLoc));
1526 return new (Context) CXXCtorInitializer(Context, Loc, LParenLoc,
1527 Constructor, Init.takeAs<Expr>(),
1528 RParenLoc);
1529 }
1530
1531 return new (Context) CXXCtorInitializer(Context, Loc, LParenLoc, Constructor,
1532 DelegationInit.takeAs<Expr>(),
1533 RParenLoc);
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001534}
1535
1536MemInitResult
John McCallbcd03502009-12-07 02:54:59 +00001537Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001538 Expr **Args, unsigned NumArgs,
1539 SourceLocation LParenLoc, SourceLocation RParenLoc,
Douglas Gregor44e7df62011-01-04 00:32:56 +00001540 CXXRecordDecl *ClassDecl,
1541 SourceLocation EllipsisLoc) {
Eli Friedman8e1433b2009-07-29 19:44:27 +00001542 bool HasDependentArg = false;
1543 for (unsigned i = 0; i < NumArgs; i++)
1544 HasDependentArg |= Args[i]->isTypeDependent();
1545
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001546 SourceLocation BaseLoc
1547 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
1548
1549 if (!BaseType->isDependentType() && !BaseType->isRecordType())
1550 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1551 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
1552
1553 // C++ [class.base.init]p2:
1554 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky9331ed82010-11-20 01:29:55 +00001555 // member of the constructor's class or a direct or virtual base
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001556 // of that class, the mem-initializer is ill-formed. A
1557 // mem-initializer-list can initialize a base class using any
1558 // name that denotes that base class type.
1559 bool Dependent = BaseType->isDependentType() || HasDependentArg;
1560
Douglas Gregor44e7df62011-01-04 00:32:56 +00001561 if (EllipsisLoc.isValid()) {
1562 // This is a pack expansion.
1563 if (!BaseType->containsUnexpandedParameterPack()) {
1564 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1565 << SourceRange(BaseLoc, RParenLoc);
1566
1567 EllipsisLoc = SourceLocation();
1568 }
1569 } else {
1570 // Check for any unexpanded parameter packs.
1571 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
1572 return true;
1573
1574 for (unsigned I = 0; I != NumArgs; ++I)
1575 if (DiagnoseUnexpandedParameterPack(Args[I]))
1576 return true;
1577 }
1578
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001579 // Check for direct and virtual base classes.
1580 const CXXBaseSpecifier *DirectBaseSpec = 0;
1581 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1582 if (!Dependent) {
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001583 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
1584 BaseType))
Alexis Huntc5575cc2011-02-26 19:13:13 +00001585 return BuildDelegatingInitializer(BaseTInfo, Args, NumArgs, BaseLoc,
1586 LParenLoc, RParenLoc, ClassDecl);
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001587
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001588 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1589 VirtualBaseSpec);
1590
1591 // C++ [base.class.init]p2:
1592 // Unless the mem-initializer-id names a nonstatic data member of the
1593 // constructor's class or a direct or virtual base of that class, the
1594 // mem-initializer is ill-formed.
1595 if (!DirectBaseSpec && !VirtualBaseSpec) {
1596 // If the class has any dependent bases, then it's possible that
1597 // one of those types will resolve to the same type as
1598 // BaseType. Therefore, just treat this as a dependent base
1599 // class initialization. FIXME: Should we try to check the
1600 // initialization anyway? It seems odd.
1601 if (ClassDecl->hasAnyDependentBases())
1602 Dependent = true;
1603 else
1604 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1605 << BaseType << Context.getTypeDeclType(ClassDecl)
1606 << BaseTInfo->getTypeLoc().getLocalSourceRange();
1607 }
1608 }
1609
1610 if (Dependent) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001611 // Can't check initialization for a base of dependent type or when
1612 // any of the arguments are type-dependent expressions.
John McCalldadc5752010-08-24 06:29:42 +00001613 ExprResult BaseInit
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001614 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1615 RParenLoc));
Eli Friedman8e1433b2009-07-29 19:44:27 +00001616
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001617 // Erase any temporaries within this evaluation context; we're not
1618 // going to track them in the AST, since we'll be rebuilding the
1619 // ASTs during template instantiation.
1620 ExprTemporaries.erase(
1621 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1622 ExprTemporaries.end());
Mike Stump11289f42009-09-09 15:08:12 +00001623
Alexis Hunt1d792652011-01-08 20:30:50 +00001624 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001625 /*IsVirtual=*/false,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001626 LParenLoc,
1627 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001628 RParenLoc,
1629 EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001630 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001631
1632 // C++ [base.class.init]p2:
1633 // If a mem-initializer-id is ambiguous because it designates both
1634 // a direct non-virtual base class and an inherited virtual base
1635 // class, the mem-initializer is ill-formed.
1636 if (DirectBaseSpec && VirtualBaseSpec)
1637 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00001638 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001639
1640 CXXBaseSpecifier *BaseSpec
1641 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
1642 if (!BaseSpec)
1643 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1644
1645 // Initialize the base.
1646 InitializedEntity BaseEntity =
Anders Carlsson43c64af2010-04-21 19:52:01 +00001647 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001648 InitializationKind Kind =
1649 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc);
1650
1651 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
1652
John McCalldadc5752010-08-24 06:29:42 +00001653 ExprResult BaseInit =
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001654 InitSeq.Perform(*this, BaseEntity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00001655 MultiExprArg(*this, Args, NumArgs), 0);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001656 if (BaseInit.isInvalid())
1657 return true;
John McCallacf0ee52010-10-08 02:01:28 +00001658
1659 CheckImplicitConversions(BaseInit.get(), LParenLoc);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001660
1661 // C++0x [class.base.init]p7:
1662 // The initialization of each base and member constitutes a
1663 // full-expression.
Douglas Gregora40433a2010-12-07 00:41:46 +00001664 BaseInit = MaybeCreateExprWithCleanups(BaseInit);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001665 if (BaseInit.isInvalid())
1666 return true;
1667
1668 // If we are in a dependent context, template instantiation will
1669 // perform this type-checking again. Just save the arguments that we
1670 // received in a ParenListExpr.
1671 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1672 // of the information that we have about the base
1673 // initializer. However, deconstructing the ASTs is a dicey process,
1674 // and this approach is far more likely to get the corner cases right.
1675 if (CurContext->isDependentContext()) {
John McCalldadc5752010-08-24 06:29:42 +00001676 ExprResult Init
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001677 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1678 RParenLoc));
Alexis Hunt1d792652011-01-08 20:30:50 +00001679 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001680 BaseSpec->isVirtual(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001681 LParenLoc,
1682 Init.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001683 RParenLoc,
1684 EllipsisLoc);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001685 }
1686
Alexis Hunt1d792652011-01-08 20:30:50 +00001687 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001688 BaseSpec->isVirtual(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001689 LParenLoc,
1690 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001691 RParenLoc,
1692 EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001693}
1694
Anders Carlsson1b00e242010-04-23 03:10:23 +00001695/// ImplicitInitializerKind - How an implicit base or member initializer should
1696/// initialize its base or member.
1697enum ImplicitInitializerKind {
1698 IIK_Default,
1699 IIK_Copy,
1700 IIK_Move
1701};
1702
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001703static bool
Anders Carlsson3c1db572010-04-23 02:15:47 +00001704BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001705 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson43c64af2010-04-21 19:52:01 +00001706 CXXBaseSpecifier *BaseSpec,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001707 bool IsInheritedVirtualBase,
Alexis Hunt1d792652011-01-08 20:30:50 +00001708 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001709 InitializedEntity InitEntity
Anders Carlsson43c64af2010-04-21 19:52:01 +00001710 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
1711 IsInheritedVirtualBase);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001712
John McCalldadc5752010-08-24 06:29:42 +00001713 ExprResult BaseInit;
Anders Carlsson1b00e242010-04-23 03:10:23 +00001714
1715 switch (ImplicitInitKind) {
1716 case IIK_Default: {
1717 InitializationKind InitKind
1718 = InitializationKind::CreateDefault(Constructor->getLocation());
1719 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
1720 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00001721 MultiExprArg(SemaRef, 0, 0));
Anders Carlsson1b00e242010-04-23 03:10:23 +00001722 break;
1723 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001724
Anders Carlsson1b00e242010-04-23 03:10:23 +00001725 case IIK_Copy: {
1726 ParmVarDecl *Param = Constructor->getParamDecl(0);
1727 QualType ParamType = Param->getType().getNonReferenceType();
1728
1729 Expr *CopyCtorArg =
Douglas Gregorea972d32011-02-28 21:54:11 +00001730 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param,
John McCall7decc9e2010-11-18 06:31:45 +00001731 Constructor->getLocation(), ParamType,
1732 VK_LValue, 0);
Anders Carlsson1b00e242010-04-23 03:10:23 +00001733
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00001734 // Cast to the base class to avoid ambiguities.
Anders Carlsson79111502010-05-01 16:39:01 +00001735 QualType ArgTy =
1736 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
1737 ParamType.getQualifiers());
John McCallcf142162010-08-07 06:22:56 +00001738
1739 CXXCastPath BasePath;
1740 BasePath.push_back(BaseSpec);
Sebastian Redlc57d34b2010-07-20 04:20:21 +00001741 SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
John McCalle3027922010-08-25 11:45:40 +00001742 CK_UncheckedDerivedToBase,
John McCall2536c6d2010-08-25 10:28:54 +00001743 VK_LValue, &BasePath);
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00001744
Anders Carlsson1b00e242010-04-23 03:10:23 +00001745 InitializationKind InitKind
1746 = InitializationKind::CreateDirect(Constructor->getLocation(),
1747 SourceLocation(), SourceLocation());
1748 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
1749 &CopyCtorArg, 1);
1750 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00001751 MultiExprArg(&CopyCtorArg, 1));
Anders Carlsson1b00e242010-04-23 03:10:23 +00001752 break;
1753 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001754
Anders Carlsson1b00e242010-04-23 03:10:23 +00001755 case IIK_Move:
1756 assert(false && "Unhandled initializer kind!");
1757 }
John McCallb268a282010-08-23 23:25:46 +00001758
Douglas Gregora40433a2010-12-07 00:41:46 +00001759 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001760 if (BaseInit.isInvalid())
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001761 return true;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001762
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001763 CXXBaseInit =
Alexis Hunt1d792652011-01-08 20:30:50 +00001764 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001765 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
1766 SourceLocation()),
1767 BaseSpec->isVirtual(),
1768 SourceLocation(),
1769 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001770 SourceLocation(),
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001771 SourceLocation());
1772
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001773 return false;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001774}
1775
Anders Carlsson3c1db572010-04-23 02:15:47 +00001776static bool
1777BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001778 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson3c1db572010-04-23 02:15:47 +00001779 FieldDecl *Field,
Alexis Hunt1d792652011-01-08 20:30:50 +00001780 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00001781 if (Field->isInvalidDecl())
1782 return true;
1783
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001784 SourceLocation Loc = Constructor->getLocation();
1785
Anders Carlsson423f5d82010-04-23 16:04:08 +00001786 if (ImplicitInitKind == IIK_Copy) {
1787 ParmVarDecl *Param = Constructor->getParamDecl(0);
1788 QualType ParamType = Param->getType().getNonReferenceType();
1789
1790 Expr *MemberExprBase =
Douglas Gregorea972d32011-02-28 21:54:11 +00001791 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param,
John McCall7decc9e2010-11-18 06:31:45 +00001792 Loc, ParamType, VK_LValue, 0);
Douglas Gregor94f9a482010-05-05 05:51:00 +00001793
1794 // Build a reference to this field within the parameter.
1795 CXXScopeSpec SS;
1796 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
1797 Sema::LookupMemberName);
1798 MemberLookup.addDecl(Field, AS_public);
1799 MemberLookup.resolveKind();
John McCalldadc5752010-08-24 06:29:42 +00001800 ExprResult CopyCtorArg
John McCallb268a282010-08-23 23:25:46 +00001801 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregor94f9a482010-05-05 05:51:00 +00001802 ParamType, Loc,
1803 /*IsArrow=*/false,
1804 SS,
1805 /*FirstQualifierInScope=*/0,
1806 MemberLookup,
1807 /*TemplateArgs=*/0);
1808 if (CopyCtorArg.isInvalid())
Anders Carlsson423f5d82010-04-23 16:04:08 +00001809 return true;
1810
Douglas Gregor94f9a482010-05-05 05:51:00 +00001811 // When the field we are copying is an array, create index variables for
1812 // each dimension of the array. We use these index variables to subscript
1813 // the source array, and other clients (e.g., CodeGen) will perform the
1814 // necessary iteration with these index variables.
1815 llvm::SmallVector<VarDecl *, 4> IndexVariables;
1816 QualType BaseType = Field->getType();
1817 QualType SizeType = SemaRef.Context.getSizeType();
1818 while (const ConstantArrayType *Array
1819 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
1820 // Create the iteration variable for this array index.
1821 IdentifierInfo *IterationVarName = 0;
1822 {
1823 llvm::SmallString<8> Str;
1824 llvm::raw_svector_ostream OS(Str);
1825 OS << "__i" << IndexVariables.size();
1826 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
1827 }
1828 VarDecl *IterationVar
Abramo Bagnaradff19302011-03-08 08:55:46 +00001829 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregor94f9a482010-05-05 05:51:00 +00001830 IterationVarName, SizeType,
1831 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCall8e7d6562010-08-26 03:08:43 +00001832 SC_None, SC_None);
Douglas Gregor94f9a482010-05-05 05:51:00 +00001833 IndexVariables.push_back(IterationVar);
1834
1835 // Create a reference to the iteration variable.
John McCalldadc5752010-08-24 06:29:42 +00001836 ExprResult IterationVarRef
John McCall7decc9e2010-11-18 06:31:45 +00001837 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc);
Douglas Gregor94f9a482010-05-05 05:51:00 +00001838 assert(!IterationVarRef.isInvalid() &&
1839 "Reference to invented variable cannot fail!");
1840
1841 // Subscript the array with this iteration variable.
John McCallb268a282010-08-23 23:25:46 +00001842 CopyCtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CopyCtorArg.take(),
Douglas Gregor94f9a482010-05-05 05:51:00 +00001843 Loc,
John McCallb268a282010-08-23 23:25:46 +00001844 IterationVarRef.take(),
Douglas Gregor94f9a482010-05-05 05:51:00 +00001845 Loc);
1846 if (CopyCtorArg.isInvalid())
1847 return true;
1848
1849 BaseType = Array->getElementType();
1850 }
1851
1852 // Construct the entity that we will be initializing. For an array, this
1853 // will be first element in the array, which may require several levels
1854 // of array-subscript entities.
1855 llvm::SmallVector<InitializedEntity, 4> Entities;
1856 Entities.reserve(1 + IndexVariables.size());
1857 Entities.push_back(InitializedEntity::InitializeMember(Field));
1858 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
1859 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
1860 0,
1861 Entities.back()));
1862
1863 // Direct-initialize to use the copy constructor.
1864 InitializationKind InitKind =
1865 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
1866
1867 Expr *CopyCtorArgE = CopyCtorArg.takeAs<Expr>();
1868 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
1869 &CopyCtorArgE, 1);
1870
John McCalldadc5752010-08-24 06:29:42 +00001871 ExprResult MemberInit
Douglas Gregor94f9a482010-05-05 05:51:00 +00001872 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00001873 MultiExprArg(&CopyCtorArgE, 1));
Douglas Gregora40433a2010-12-07 00:41:46 +00001874 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregor94f9a482010-05-05 05:51:00 +00001875 if (MemberInit.isInvalid())
1876 return true;
1877
1878 CXXMemberInit
Alexis Hunt1d792652011-01-08 20:30:50 +00001879 = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc, Loc,
Douglas Gregor94f9a482010-05-05 05:51:00 +00001880 MemberInit.takeAs<Expr>(), Loc,
1881 IndexVariables.data(),
1882 IndexVariables.size());
Anders Carlsson1b00e242010-04-23 03:10:23 +00001883 return false;
1884 }
1885
Anders Carlsson423f5d82010-04-23 16:04:08 +00001886 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
1887
Anders Carlsson3c1db572010-04-23 02:15:47 +00001888 QualType FieldBaseElementType =
1889 SemaRef.Context.getBaseElementType(Field->getType());
1890
Anders Carlsson3c1db572010-04-23 02:15:47 +00001891 if (FieldBaseElementType->isRecordType()) {
1892 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
Anders Carlsson423f5d82010-04-23 16:04:08 +00001893 InitializationKind InitKind =
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001894 InitializationKind::CreateDefault(Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00001895
1896 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCalldadc5752010-08-24 06:29:42 +00001897 ExprResult MemberInit =
John McCallfaf5fb42010-08-26 23:41:50 +00001898 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCallb268a282010-08-23 23:25:46 +00001899
Douglas Gregora40433a2010-12-07 00:41:46 +00001900 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlsson3c1db572010-04-23 02:15:47 +00001901 if (MemberInit.isInvalid())
1902 return true;
1903
1904 CXXMemberInit =
Alexis Hunt1d792652011-01-08 20:30:50 +00001905 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001906 Field, Loc, Loc,
John McCallb268a282010-08-23 23:25:46 +00001907 MemberInit.get(),
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001908 Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00001909 return false;
1910 }
Anders Carlssondca6be02010-04-23 03:07:47 +00001911
1912 if (FieldBaseElementType->isReferenceType()) {
1913 SemaRef.Diag(Constructor->getLocation(),
1914 diag::err_uninitialized_member_in_ctor)
1915 << (int)Constructor->isImplicit()
1916 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1917 << 0 << Field->getDeclName();
1918 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1919 return true;
1920 }
1921
1922 if (FieldBaseElementType.isConstQualified()) {
1923 SemaRef.Diag(Constructor->getLocation(),
1924 diag::err_uninitialized_member_in_ctor)
1925 << (int)Constructor->isImplicit()
1926 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1927 << 1 << Field->getDeclName();
1928 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1929 return true;
1930 }
Anders Carlsson3c1db572010-04-23 02:15:47 +00001931
1932 // Nothing to initialize.
1933 CXXMemberInit = 0;
1934 return false;
1935}
John McCallbc83b3f2010-05-20 23:23:51 +00001936
1937namespace {
1938struct BaseAndFieldInfo {
1939 Sema &S;
1940 CXXConstructorDecl *Ctor;
1941 bool AnyErrorsInInits;
1942 ImplicitInitializerKind IIK;
Alexis Hunt1d792652011-01-08 20:30:50 +00001943 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
1944 llvm::SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallbc83b3f2010-05-20 23:23:51 +00001945
1946 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
1947 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
1948 // FIXME: Handle implicit move constructors.
1949 if (Ctor->isImplicit() && Ctor->isCopyConstructor())
1950 IIK = IIK_Copy;
1951 else
1952 IIK = IIK_Default;
1953 }
1954};
1955}
1956
1957static bool CollectFieldInitializer(BaseAndFieldInfo &Info,
1958 FieldDecl *Top, FieldDecl *Field) {
1959
Chandler Carruth139e9622010-06-30 02:59:29 +00001960 // Overwhelmingly common case: we have a direct initializer for this field.
Alexis Hunt1d792652011-01-08 20:30:50 +00001961 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) {
Francois Pichetd583da02010-12-04 09:14:42 +00001962 Info.AllToInit.push_back(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00001963 return false;
1964 }
1965
1966 if (Info.IIK == IIK_Default && Field->isAnonymousStructOrUnion()) {
1967 const RecordType *FieldClassType = Field->getType()->getAs<RecordType>();
1968 assert(FieldClassType && "anonymous struct/union without record type");
John McCallbc83b3f2010-05-20 23:23:51 +00001969 CXXRecordDecl *FieldClassDecl
1970 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Chandler Carruth139e9622010-06-30 02:59:29 +00001971
1972 // Even though union members never have non-trivial default
1973 // constructions in C++03, we still build member initializers for aggregate
1974 // record types which can be union members, and C++0x allows non-trivial
1975 // default constructors for union members, so we ensure that only one
1976 // member is initialized for these.
1977 if (FieldClassDecl->isUnion()) {
1978 // First check for an explicit initializer for one field.
1979 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
1980 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00001981 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(*FA)) {
Francois Pichetd583da02010-12-04 09:14:42 +00001982 Info.AllToInit.push_back(Init);
Chandler Carruth139e9622010-06-30 02:59:29 +00001983
1984 // Once we've initialized a field of an anonymous union, the union
1985 // field in the class is also initialized, so exit immediately.
1986 return false;
Argyrios Kyrtzidisa3ae3eb2010-08-16 17:27:13 +00001987 } else if ((*FA)->isAnonymousStructOrUnion()) {
1988 if (CollectFieldInitializer(Info, Top, *FA))
1989 return true;
Chandler Carruth139e9622010-06-30 02:59:29 +00001990 }
1991 }
1992
1993 // Fallthrough and construct a default initializer for the union as
1994 // a whole, which can call its default constructor if such a thing exists
1995 // (C++0x perhaps). FIXME: It's not clear that this is the correct
1996 // behavior going forward with C++0x, when anonymous unions there are
1997 // finalized, we should revisit this.
1998 } else {
1999 // For structs, we simply descend through to initialize all members where
2000 // necessary.
2001 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
2002 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
2003 if (CollectFieldInitializer(Info, Top, *FA))
2004 return true;
2005 }
2006 }
John McCallbc83b3f2010-05-20 23:23:51 +00002007 }
2008
2009 // Don't try to build an implicit initializer if there were semantic
2010 // errors in any of the initializers (and therefore we might be
2011 // missing some that the user actually wrote).
2012 if (Info.AnyErrorsInInits)
2013 return false;
2014
Alexis Hunt1d792652011-01-08 20:30:50 +00002015 CXXCtorInitializer *Init = 0;
John McCallbc83b3f2010-05-20 23:23:51 +00002016 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, Init))
2017 return true;
John McCallbc83b3f2010-05-20 23:23:51 +00002018
Francois Pichetd583da02010-12-04 09:14:42 +00002019 if (Init)
2020 Info.AllToInit.push_back(Init);
2021
John McCallbc83b3f2010-05-20 23:23:51 +00002022 return false;
2023}
Anders Carlsson3c1db572010-04-23 02:15:47 +00002024
Eli Friedman9cf6b592009-11-09 19:20:36 +00002025bool
Alexis Hunt1d792652011-01-08 20:30:50 +00002026Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
2027 CXXCtorInitializer **Initializers,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002028 unsigned NumInitializers,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002029 bool AnyErrors) {
John McCallbb7b6582010-04-10 07:37:23 +00002030 if (Constructor->getDeclContext()->isDependentContext()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00002031 // Just store the initializers as written, they will be checked during
2032 // instantiation.
2033 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002034 Constructor->setNumCtorInitializers(NumInitializers);
2035 CXXCtorInitializer **baseOrMemberInitializers =
2036 new (Context) CXXCtorInitializer*[NumInitializers];
Anders Carlssondb0a9652010-04-02 06:26:44 +00002037 memcpy(baseOrMemberInitializers, Initializers,
Alexis Hunt1d792652011-01-08 20:30:50 +00002038 NumInitializers * sizeof(CXXCtorInitializer*));
2039 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssondb0a9652010-04-02 06:26:44 +00002040 }
2041
2042 return false;
2043 }
2044
John McCallbc83b3f2010-05-20 23:23:51 +00002045 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlsson1b00e242010-04-23 03:10:23 +00002046
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002047 // We need to build the initializer AST according to order of construction
2048 // and not what user specified in the Initializers list.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002049 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregorc14922f2010-03-26 22:43:07 +00002050 if (!ClassDecl)
2051 return true;
2052
Eli Friedman9cf6b592009-11-09 19:20:36 +00002053 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00002054
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002055 for (unsigned i = 0; i < NumInitializers; i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002056 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssondb0a9652010-04-02 06:26:44 +00002057
2058 if (Member->isBaseInitializer())
John McCallbc83b3f2010-05-20 23:23:51 +00002059 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00002060 else
Francois Pichetd583da02010-12-04 09:14:42 +00002061 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00002062 }
2063
Anders Carlsson43c64af2010-04-21 19:52:01 +00002064 // Keep track of the direct virtual bases.
2065 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
2066 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
2067 E = ClassDecl->bases_end(); I != E; ++I) {
2068 if (I->isVirtual())
2069 DirectVBases.insert(I);
2070 }
2071
Anders Carlssondb0a9652010-04-02 06:26:44 +00002072 // Push virtual bases before others.
2073 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2074 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2075
Alexis Hunt1d792652011-01-08 20:30:50 +00002076 if (CXXCtorInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00002077 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
2078 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00002079 } else if (!AnyErrors) {
Anders Carlsson43c64af2010-04-21 19:52:01 +00002080 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Alexis Hunt1d792652011-01-08 20:30:50 +00002081 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00002082 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlsson1b00e242010-04-23 03:10:23 +00002083 VBase, IsInheritedVirtualBase,
2084 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00002085 HadError = true;
2086 continue;
2087 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002088
John McCallbc83b3f2010-05-20 23:23:51 +00002089 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002090 }
2091 }
Mike Stump11289f42009-09-09 15:08:12 +00002092
John McCallbc83b3f2010-05-20 23:23:51 +00002093 // Non-virtual bases.
Anders Carlssondb0a9652010-04-02 06:26:44 +00002094 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2095 E = ClassDecl->bases_end(); Base != E; ++Base) {
2096 // Virtuals are in the virtual base list and already constructed.
2097 if (Base->isVirtual())
2098 continue;
Mike Stump11289f42009-09-09 15:08:12 +00002099
Alexis Hunt1d792652011-01-08 20:30:50 +00002100 if (CXXCtorInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00002101 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
2102 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00002103 } else if (!AnyErrors) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002104 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00002105 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlsson1b00e242010-04-23 03:10:23 +00002106 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002107 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00002108 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002109 continue;
Anders Carlssondb0a9652010-04-02 06:26:44 +00002110 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00002111
John McCallbc83b3f2010-05-20 23:23:51 +00002112 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002113 }
2114 }
Mike Stump11289f42009-09-09 15:08:12 +00002115
John McCallbc83b3f2010-05-20 23:23:51 +00002116 // Fields.
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002117 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00002118 E = ClassDecl->field_end(); Field != E; ++Field) {
2119 if ((*Field)->getType()->isIncompleteArrayType()) {
2120 assert(ClassDecl->hasFlexibleArrayMember() &&
2121 "Incomplete array type is not valid");
2122 continue;
2123 }
John McCallbc83b3f2010-05-20 23:23:51 +00002124 if (CollectFieldInitializer(Info, *Field, *Field))
Anders Carlsson3c1db572010-04-23 02:15:47 +00002125 HadError = true;
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00002126 }
Mike Stump11289f42009-09-09 15:08:12 +00002127
John McCallbc83b3f2010-05-20 23:23:51 +00002128 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002129 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002130 Constructor->setNumCtorInitializers(NumInitializers);
2131 CXXCtorInitializer **baseOrMemberInitializers =
2132 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallbc83b3f2010-05-20 23:23:51 +00002133 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Alexis Hunt1d792652011-01-08 20:30:50 +00002134 NumInitializers * sizeof(CXXCtorInitializer*));
2135 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola13327bb2010-03-13 18:12:56 +00002136
John McCalla6309952010-03-16 21:39:52 +00002137 // Constructors implicitly reference the base and member
2138 // destructors.
2139 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
2140 Constructor->getParent());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002141 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00002142
2143 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002144}
2145
Eli Friedman952c15d2009-07-21 19:28:10 +00002146static void *GetKeyForTopLevelField(FieldDecl *Field) {
2147 // For anonymous unions, use the class declaration as the key.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002148 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman952c15d2009-07-21 19:28:10 +00002149 if (RT->getDecl()->isAnonymousStructOrUnion())
2150 return static_cast<void *>(RT->getDecl());
2151 }
2152 return static_cast<void *>(Field);
2153}
2154
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002155static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCall424cec92011-01-19 06:33:43 +00002156 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssonbcec05c2009-09-01 06:22:14 +00002157}
2158
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002159static void *GetKeyForMember(ASTContext &Context,
Alexis Hunt1d792652011-01-08 20:30:50 +00002160 CXXCtorInitializer *Member) {
Francois Pichetd583da02010-12-04 09:14:42 +00002161 if (!Member->isAnyMemberInitializer())
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002162 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlssona942dcd2010-03-30 15:39:27 +00002163
Eli Friedman952c15d2009-07-21 19:28:10 +00002164 // For fields injected into the class via declaration of an anonymous union,
2165 // use its anonymous union class declaration as the unique key.
Francois Pichetd583da02010-12-04 09:14:42 +00002166 FieldDecl *Field = Member->getAnyMember();
2167
John McCall23eebd92010-04-10 09:28:51 +00002168 // If the field is a member of an anonymous struct or union, our key
2169 // is the anonymous record decl that's a direct child of the class.
Anders Carlsson83ac3122010-03-30 16:19:37 +00002170 RecordDecl *RD = Field->getParent();
John McCall23eebd92010-04-10 09:28:51 +00002171 if (RD->isAnonymousStructOrUnion()) {
2172 while (true) {
2173 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
2174 if (Parent->isAnonymousStructOrUnion())
2175 RD = Parent;
2176 else
2177 break;
2178 }
2179
Anders Carlsson83ac3122010-03-30 16:19:37 +00002180 return static_cast<void *>(RD);
John McCall23eebd92010-04-10 09:28:51 +00002181 }
Mike Stump11289f42009-09-09 15:08:12 +00002182
Anders Carlssona942dcd2010-03-30 15:39:27 +00002183 return static_cast<void *>(Field);
Eli Friedman952c15d2009-07-21 19:28:10 +00002184}
2185
Anders Carlssone857b292010-04-02 03:37:03 +00002186static void
2187DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002188 const CXXConstructorDecl *Constructor,
Alexis Hunt1d792652011-01-08 20:30:50 +00002189 CXXCtorInitializer **Inits,
John McCallbb7b6582010-04-10 07:37:23 +00002190 unsigned NumInits) {
2191 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00002192 return;
Mike Stump11289f42009-09-09 15:08:12 +00002193
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002194 // Don't check initializers order unless the warning is enabled at the
2195 // location of at least one initializer.
2196 bool ShouldCheckOrder = false;
2197 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002198 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002199 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
2200 Init->getSourceLocation())
2201 != Diagnostic::Ignored) {
2202 ShouldCheckOrder = true;
2203 break;
2204 }
2205 }
2206 if (!ShouldCheckOrder)
Anders Carlssone0eebb32009-08-27 05:45:01 +00002207 return;
Anders Carlssone857b292010-04-02 03:37:03 +00002208
John McCallbb7b6582010-04-10 07:37:23 +00002209 // Build the list of bases and members in the order that they'll
2210 // actually be initialized. The explicit initializers should be in
2211 // this same order but may be missing things.
2212 llvm::SmallVector<const void*, 32> IdealInitKeys;
Mike Stump11289f42009-09-09 15:08:12 +00002213
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002214 const CXXRecordDecl *ClassDecl = Constructor->getParent();
2215
John McCallbb7b6582010-04-10 07:37:23 +00002216 // 1. Virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002217 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlssone0eebb32009-08-27 05:45:01 +00002218 ClassDecl->vbases_begin(),
2219 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCallbb7b6582010-04-10 07:37:23 +00002220 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump11289f42009-09-09 15:08:12 +00002221
John McCallbb7b6582010-04-10 07:37:23 +00002222 // 2. Non-virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002223 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlssone0eebb32009-08-27 05:45:01 +00002224 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlssone0eebb32009-08-27 05:45:01 +00002225 if (Base->isVirtual())
2226 continue;
John McCallbb7b6582010-04-10 07:37:23 +00002227 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00002228 }
Mike Stump11289f42009-09-09 15:08:12 +00002229
John McCallbb7b6582010-04-10 07:37:23 +00002230 // 3. Direct fields.
Anders Carlssone0eebb32009-08-27 05:45:01 +00002231 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2232 E = ClassDecl->field_end(); Field != E; ++Field)
John McCallbb7b6582010-04-10 07:37:23 +00002233 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Mike Stump11289f42009-09-09 15:08:12 +00002234
John McCallbb7b6582010-04-10 07:37:23 +00002235 unsigned NumIdealInits = IdealInitKeys.size();
2236 unsigned IdealIndex = 0;
Eli Friedman952c15d2009-07-21 19:28:10 +00002237
Alexis Hunt1d792652011-01-08 20:30:50 +00002238 CXXCtorInitializer *PrevInit = 0;
John McCallbb7b6582010-04-10 07:37:23 +00002239 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002240 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichetd583da02010-12-04 09:14:42 +00002241 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCallbb7b6582010-04-10 07:37:23 +00002242
2243 // Scan forward to try to find this initializer in the idealized
2244 // initializers list.
2245 for (; IdealIndex != NumIdealInits; ++IdealIndex)
2246 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00002247 break;
John McCallbb7b6582010-04-10 07:37:23 +00002248
2249 // If we didn't find this initializer, it must be because we
2250 // scanned past it on a previous iteration. That can only
2251 // happen if we're out of order; emit a warning.
Douglas Gregoraabdfcb2010-05-20 23:49:34 +00002252 if (IdealIndex == NumIdealInits && PrevInit) {
John McCallbb7b6582010-04-10 07:37:23 +00002253 Sema::SemaDiagnosticBuilder D =
2254 SemaRef.Diag(PrevInit->getSourceLocation(),
2255 diag::warn_initializer_out_of_order);
2256
Francois Pichetd583da02010-12-04 09:14:42 +00002257 if (PrevInit->isAnyMemberInitializer())
2258 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00002259 else
2260 D << 1 << PrevInit->getBaseClassInfo()->getType();
2261
Francois Pichetd583da02010-12-04 09:14:42 +00002262 if (Init->isAnyMemberInitializer())
2263 D << 0 << Init->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00002264 else
2265 D << 1 << Init->getBaseClassInfo()->getType();
2266
2267 // Move back to the initializer's location in the ideal list.
2268 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
2269 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00002270 break;
John McCallbb7b6582010-04-10 07:37:23 +00002271
2272 assert(IdealIndex != NumIdealInits &&
2273 "initializer not found in initializer list");
Fariborz Jahanian341583c2009-07-09 19:59:47 +00002274 }
John McCallbb7b6582010-04-10 07:37:23 +00002275
2276 PrevInit = Init;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00002277 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00002278}
2279
John McCall23eebd92010-04-10 09:28:51 +00002280namespace {
2281bool CheckRedundantInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00002282 CXXCtorInitializer *Init,
2283 CXXCtorInitializer *&PrevInit) {
John McCall23eebd92010-04-10 09:28:51 +00002284 if (!PrevInit) {
2285 PrevInit = Init;
2286 return false;
2287 }
2288
2289 if (FieldDecl *Field = Init->getMember())
2290 S.Diag(Init->getSourceLocation(),
2291 diag::err_multiple_mem_initialization)
2292 << Field->getDeclName()
2293 << Init->getSourceRange();
2294 else {
John McCall424cec92011-01-19 06:33:43 +00002295 const Type *BaseClass = Init->getBaseClass();
John McCall23eebd92010-04-10 09:28:51 +00002296 assert(BaseClass && "neither field nor base");
2297 S.Diag(Init->getSourceLocation(),
2298 diag::err_multiple_base_initialization)
2299 << QualType(BaseClass, 0)
2300 << Init->getSourceRange();
2301 }
2302 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
2303 << 0 << PrevInit->getSourceRange();
2304
2305 return true;
2306}
2307
Alexis Hunt1d792652011-01-08 20:30:50 +00002308typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall23eebd92010-04-10 09:28:51 +00002309typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
2310
2311bool CheckRedundantUnionInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00002312 CXXCtorInitializer *Init,
John McCall23eebd92010-04-10 09:28:51 +00002313 RedundantUnionMap &Unions) {
Francois Pichetd583da02010-12-04 09:14:42 +00002314 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00002315 RecordDecl *Parent = Field->getParent();
2316 if (!Parent->isAnonymousStructOrUnion())
2317 return false;
2318
2319 NamedDecl *Child = Field;
2320 do {
2321 if (Parent->isUnion()) {
2322 UnionEntry &En = Unions[Parent];
2323 if (En.first && En.first != Child) {
2324 S.Diag(Init->getSourceLocation(),
2325 diag::err_multiple_mem_union_initialization)
2326 << Field->getDeclName()
2327 << Init->getSourceRange();
2328 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
2329 << 0 << En.second->getSourceRange();
2330 return true;
2331 } else if (!En.first) {
2332 En.first = Child;
2333 En.second = Init;
2334 }
2335 }
2336
2337 Child = Parent;
2338 Parent = cast<RecordDecl>(Parent->getDeclContext());
2339 } while (Parent->isAnonymousStructOrUnion());
2340
2341 return false;
2342}
2343}
2344
Anders Carlssone857b292010-04-02 03:37:03 +00002345/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCall48871652010-08-21 09:40:31 +00002346void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlssone857b292010-04-02 03:37:03 +00002347 SourceLocation ColonLoc,
2348 MemInitTy **meminits, unsigned NumMemInits,
2349 bool AnyErrors) {
2350 if (!ConstructorDecl)
2351 return;
2352
2353 AdjustDeclIfTemplate(ConstructorDecl);
2354
2355 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002356 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlssone857b292010-04-02 03:37:03 +00002357
2358 if (!Constructor) {
2359 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
2360 return;
2361 }
2362
Alexis Hunt1d792652011-01-08 20:30:50 +00002363 CXXCtorInitializer **MemInits =
2364 reinterpret_cast<CXXCtorInitializer **>(meminits);
John McCall23eebd92010-04-10 09:28:51 +00002365
2366 // Mapping for the duplicate initializers check.
2367 // For member initializers, this is keyed with a FieldDecl*.
2368 // For base initializers, this is keyed with a Type*.
Alexis Hunt1d792652011-01-08 20:30:50 +00002369 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall23eebd92010-04-10 09:28:51 +00002370
2371 // Mapping for the inconsistent anonymous-union initializers check.
2372 RedundantUnionMap MemberUnions;
2373
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002374 bool HadError = false;
2375 for (unsigned i = 0; i < NumMemInits; i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002376 CXXCtorInitializer *Init = MemInits[i];
Anders Carlssone857b292010-04-02 03:37:03 +00002377
Abramo Bagnara341d7832010-05-26 18:09:23 +00002378 // Set the source order index.
2379 Init->setSourceOrder(i);
2380
Francois Pichetd583da02010-12-04 09:14:42 +00002381 if (Init->isAnyMemberInitializer()) {
2382 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00002383 if (CheckRedundantInit(*this, Init, Members[Field]) ||
2384 CheckRedundantUnionInit(*this, Init, MemberUnions))
2385 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00002386 } else if (Init->isBaseInitializer()) {
John McCall23eebd92010-04-10 09:28:51 +00002387 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
2388 if (CheckRedundantInit(*this, Init, Members[Key]))
2389 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00002390 } else {
2391 assert(Init->isDelegatingInitializer());
2392 // This must be the only initializer
2393 if (i != 0 || NumMemInits > 1) {
2394 Diag(MemInits[0]->getSourceLocation(),
2395 diag::err_delegating_initializer_alone)
2396 << MemInits[0]->getSourceRange();
2397 HadError = true;
2398 }
Anders Carlssone857b292010-04-02 03:37:03 +00002399 }
Anders Carlssone857b292010-04-02 03:37:03 +00002400 }
2401
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002402 if (HadError)
2403 return;
2404
Anders Carlssone857b292010-04-02 03:37:03 +00002405 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlsson4c8cb012010-04-02 03:43:34 +00002406
Alexis Hunt1d792652011-01-08 20:30:50 +00002407 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlssone857b292010-04-02 03:37:03 +00002408}
2409
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002410void
John McCalla6309952010-03-16 21:39:52 +00002411Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
2412 CXXRecordDecl *ClassDecl) {
2413 // Ignore dependent contexts.
2414 if (ClassDecl->isDependentContext())
Anders Carlssondee9a302009-11-17 04:44:12 +00002415 return;
John McCall1064d7e2010-03-16 05:22:47 +00002416
2417 // FIXME: all the access-control diagnostics are positioned on the
2418 // field/base declaration. That's probably good; that said, the
2419 // user might reasonably want to know why the destructor is being
2420 // emitted, and we currently don't say.
Anders Carlssondee9a302009-11-17 04:44:12 +00002421
Anders Carlssondee9a302009-11-17 04:44:12 +00002422 // Non-static data members.
2423 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
2424 E = ClassDecl->field_end(); I != E; ++I) {
2425 FieldDecl *Field = *I;
Fariborz Jahanian16f94c62010-05-17 18:15:18 +00002426 if (Field->isInvalidDecl())
2427 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00002428 QualType FieldType = Context.getBaseElementType(Field->getType());
2429
2430 const RecordType* RT = FieldType->getAs<RecordType>();
2431 if (!RT)
2432 continue;
2433
2434 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
2435 if (FieldClassDecl->hasTrivialDestructor())
2436 continue;
2437
Douglas Gregore71edda2010-07-01 22:47:18 +00002438 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
John McCall1064d7e2010-03-16 05:22:47 +00002439 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002440 PDiag(diag::err_access_dtor_field)
John McCall1064d7e2010-03-16 05:22:47 +00002441 << Field->getDeclName()
2442 << FieldType);
2443
John McCalla6309952010-03-16 21:39:52 +00002444 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00002445 }
2446
John McCall1064d7e2010-03-16 05:22:47 +00002447 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
2448
Anders Carlssondee9a302009-11-17 04:44:12 +00002449 // Bases.
2450 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2451 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall1064d7e2010-03-16 05:22:47 +00002452 // Bases are always records in a well-formed non-dependent class.
2453 const RecordType *RT = Base->getType()->getAs<RecordType>();
2454
2455 // Remember direct virtual bases.
Anders Carlssondee9a302009-11-17 04:44:12 +00002456 if (Base->isVirtual())
John McCall1064d7e2010-03-16 05:22:47 +00002457 DirectVirtualBases.insert(RT);
Anders Carlssondee9a302009-11-17 04:44:12 +00002458
2459 // Ignore trivial destructors.
John McCall1064d7e2010-03-16 05:22:47 +00002460 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlssondee9a302009-11-17 04:44:12 +00002461 if (BaseClassDecl->hasTrivialDestructor())
2462 continue;
John McCall1064d7e2010-03-16 05:22:47 +00002463
Douglas Gregore71edda2010-07-01 22:47:18 +00002464 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
John McCall1064d7e2010-03-16 05:22:47 +00002465
2466 // FIXME: caret should be on the start of the class name
2467 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002468 PDiag(diag::err_access_dtor_base)
John McCall1064d7e2010-03-16 05:22:47 +00002469 << Base->getType()
2470 << Base->getSourceRange());
Anders Carlssondee9a302009-11-17 04:44:12 +00002471
John McCalla6309952010-03-16 21:39:52 +00002472 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00002473 }
2474
2475 // Virtual bases.
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002476 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2477 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall1064d7e2010-03-16 05:22:47 +00002478
2479 // Bases are always records in a well-formed non-dependent class.
2480 const RecordType *RT = VBase->getType()->getAs<RecordType>();
2481
2482 // Ignore direct virtual bases.
2483 if (DirectVirtualBases.count(RT))
2484 continue;
2485
Anders Carlssondee9a302009-11-17 04:44:12 +00002486 // Ignore trivial destructors.
John McCall1064d7e2010-03-16 05:22:47 +00002487 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002488 if (BaseClassDecl->hasTrivialDestructor())
2489 continue;
John McCall1064d7e2010-03-16 05:22:47 +00002490
Douglas Gregore71edda2010-07-01 22:47:18 +00002491 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
John McCall1064d7e2010-03-16 05:22:47 +00002492 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002493 PDiag(diag::err_access_dtor_vbase)
John McCall1064d7e2010-03-16 05:22:47 +00002494 << VBase->getType());
2495
John McCalla6309952010-03-16 21:39:52 +00002496 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002497 }
2498}
2499
John McCall48871652010-08-21 09:40:31 +00002500void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00002501 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00002502 return;
Mike Stump11289f42009-09-09 15:08:12 +00002503
Mike Stump11289f42009-09-09 15:08:12 +00002504 if (CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002505 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Alexis Hunt1d792652011-01-08 20:30:50 +00002506 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahanian49c81792009-07-14 18:24:21 +00002507}
2508
Mike Stump11289f42009-09-09 15:08:12 +00002509bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00002510 unsigned DiagID, AbstractDiagSelID SelID) {
Anders Carlssoneabf7702009-08-27 00:13:57 +00002511 if (SelID == -1)
John McCall02db245d2010-08-18 09:41:07 +00002512 return RequireNonAbstractType(Loc, T, PDiag(DiagID));
Anders Carlssoneabf7702009-08-27 00:13:57 +00002513 else
John McCall02db245d2010-08-18 09:41:07 +00002514 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
Mike Stump11289f42009-09-09 15:08:12 +00002515}
2516
Anders Carlssoneabf7702009-08-27 00:13:57 +00002517bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00002518 const PartialDiagnostic &PD) {
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002519 if (!getLangOptions().CPlusPlus)
2520 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002521
Anders Carlssoneb0c5322009-03-23 19:10:31 +00002522 if (const ArrayType *AT = Context.getAsArrayType(T))
John McCall02db245d2010-08-18 09:41:07 +00002523 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Mike Stump11289f42009-09-09 15:08:12 +00002524
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002525 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002526 // Find the innermost pointer type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002527 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002528 PT = T;
Mike Stump11289f42009-09-09 15:08:12 +00002529
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002530 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
John McCall02db245d2010-08-18 09:41:07 +00002531 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002532 }
Mike Stump11289f42009-09-09 15:08:12 +00002533
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002534 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002535 if (!RT)
2536 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002537
John McCall67da35c2010-02-04 22:26:26 +00002538 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002539
John McCall02db245d2010-08-18 09:41:07 +00002540 // We can't answer whether something is abstract until it has a
2541 // definition. If it's currently being defined, we'll walk back
2542 // over all the declarations when we have a full definition.
2543 const CXXRecordDecl *Def = RD->getDefinition();
2544 if (!Def || Def->isBeingDefined())
John McCall67da35c2010-02-04 22:26:26 +00002545 return false;
2546
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002547 if (!RD->isAbstract())
2548 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002549
Anders Carlssoneabf7702009-08-27 00:13:57 +00002550 Diag(Loc, PD) << RD->getDeclName();
John McCall02db245d2010-08-18 09:41:07 +00002551 DiagnoseAbstractType(RD);
Mike Stump11289f42009-09-09 15:08:12 +00002552
John McCall02db245d2010-08-18 09:41:07 +00002553 return true;
2554}
2555
2556void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
2557 // Check if we've already emitted the list of pure virtual functions
2558 // for this class.
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002559 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall02db245d2010-08-18 09:41:07 +00002560 return;
Mike Stump11289f42009-09-09 15:08:12 +00002561
Douglas Gregor4165bd62010-03-23 23:47:56 +00002562 CXXFinalOverriderMap FinalOverriders;
2563 RD->getFinalOverriders(FinalOverriders);
Mike Stump11289f42009-09-09 15:08:12 +00002564
Anders Carlssona2f74f32010-06-03 01:00:02 +00002565 // Keep a set of seen pure methods so we won't diagnose the same method
2566 // more than once.
2567 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
2568
Douglas Gregor4165bd62010-03-23 23:47:56 +00002569 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2570 MEnd = FinalOverriders.end();
2571 M != MEnd;
2572 ++M) {
2573 for (OverridingMethods::iterator SO = M->second.begin(),
2574 SOEnd = M->second.end();
2575 SO != SOEnd; ++SO) {
2576 // C++ [class.abstract]p4:
2577 // A class is abstract if it contains or inherits at least one
2578 // pure virtual function for which the final overrider is pure
2579 // virtual.
Mike Stump11289f42009-09-09 15:08:12 +00002580
Douglas Gregor4165bd62010-03-23 23:47:56 +00002581 //
2582 if (SO->second.size() != 1)
2583 continue;
2584
2585 if (!SO->second.front().Method->isPure())
2586 continue;
2587
Anders Carlssona2f74f32010-06-03 01:00:02 +00002588 if (!SeenPureMethods.insert(SO->second.front().Method))
2589 continue;
2590
Douglas Gregor4165bd62010-03-23 23:47:56 +00002591 Diag(SO->second.front().Method->getLocation(),
2592 diag::note_pure_virtual_function)
Chandler Carruth98e3c562011-02-18 23:59:51 +00002593 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor4165bd62010-03-23 23:47:56 +00002594 }
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002595 }
2596
2597 if (!PureVirtualClassDiagSet)
2598 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2599 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002600}
2601
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002602namespace {
John McCall02db245d2010-08-18 09:41:07 +00002603struct AbstractUsageInfo {
2604 Sema &S;
2605 CXXRecordDecl *Record;
2606 CanQualType AbstractType;
2607 bool Invalid;
Mike Stump11289f42009-09-09 15:08:12 +00002608
John McCall02db245d2010-08-18 09:41:07 +00002609 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
2610 : S(S), Record(Record),
2611 AbstractType(S.Context.getCanonicalType(
2612 S.Context.getTypeDeclType(Record))),
2613 Invalid(false) {}
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002614
John McCall02db245d2010-08-18 09:41:07 +00002615 void DiagnoseAbstractType() {
2616 if (Invalid) return;
2617 S.DiagnoseAbstractType(Record);
2618 Invalid = true;
2619 }
Anders Carlssonb57738b2009-03-24 17:23:42 +00002620
John McCall02db245d2010-08-18 09:41:07 +00002621 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
2622};
2623
2624struct CheckAbstractUsage {
2625 AbstractUsageInfo &Info;
2626 const NamedDecl *Ctx;
2627
2628 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
2629 : Info(Info), Ctx(Ctx) {}
2630
2631 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2632 switch (TL.getTypeLocClass()) {
2633#define ABSTRACT_TYPELOC(CLASS, PARENT)
2634#define TYPELOC(CLASS, PARENT) \
2635 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
2636#include "clang/AST/TypeLocNodes.def"
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002637 }
John McCall02db245d2010-08-18 09:41:07 +00002638 }
Mike Stump11289f42009-09-09 15:08:12 +00002639
John McCall02db245d2010-08-18 09:41:07 +00002640 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2641 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
2642 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor385d3fd2011-02-22 23:21:06 +00002643 if (!TL.getArg(I))
2644 continue;
2645
John McCall02db245d2010-08-18 09:41:07 +00002646 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
2647 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssonb57738b2009-03-24 17:23:42 +00002648 }
John McCall02db245d2010-08-18 09:41:07 +00002649 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002650
John McCall02db245d2010-08-18 09:41:07 +00002651 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2652 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
2653 }
Mike Stump11289f42009-09-09 15:08:12 +00002654
John McCall02db245d2010-08-18 09:41:07 +00002655 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2656 // Visit the type parameters from a permissive context.
2657 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2658 TemplateArgumentLoc TAL = TL.getArgLoc(I);
2659 if (TAL.getArgument().getKind() == TemplateArgument::Type)
2660 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
2661 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
2662 // TODO: other template argument types?
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002663 }
John McCall02db245d2010-08-18 09:41:07 +00002664 }
Mike Stump11289f42009-09-09 15:08:12 +00002665
John McCall02db245d2010-08-18 09:41:07 +00002666 // Visit pointee types from a permissive context.
2667#define CheckPolymorphic(Type) \
2668 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
2669 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
2670 }
2671 CheckPolymorphic(PointerTypeLoc)
2672 CheckPolymorphic(ReferenceTypeLoc)
2673 CheckPolymorphic(MemberPointerTypeLoc)
2674 CheckPolymorphic(BlockPointerTypeLoc)
Mike Stump11289f42009-09-09 15:08:12 +00002675
John McCall02db245d2010-08-18 09:41:07 +00002676 /// Handle all the types we haven't given a more specific
2677 /// implementation for above.
2678 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2679 // Every other kind of type that we haven't called out already
2680 // that has an inner type is either (1) sugar or (2) contains that
2681 // inner type in some way as a subobject.
2682 if (TypeLoc Next = TL.getNextTypeLoc())
2683 return Visit(Next, Sel);
2684
2685 // If there's no inner type and we're in a permissive context,
2686 // don't diagnose.
2687 if (Sel == Sema::AbstractNone) return;
2688
2689 // Check whether the type matches the abstract type.
2690 QualType T = TL.getType();
2691 if (T->isArrayType()) {
2692 Sel = Sema::AbstractArrayType;
2693 T = Info.S.Context.getBaseElementType(T);
Anders Carlssonb57738b2009-03-24 17:23:42 +00002694 }
John McCall02db245d2010-08-18 09:41:07 +00002695 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
2696 if (CT != Info.AbstractType) return;
2697
2698 // It matched; do some magic.
2699 if (Sel == Sema::AbstractArrayType) {
2700 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
2701 << T << TL.getSourceRange();
2702 } else {
2703 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
2704 << Sel << T << TL.getSourceRange();
2705 }
2706 Info.DiagnoseAbstractType();
2707 }
2708};
2709
2710void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
2711 Sema::AbstractDiagSelID Sel) {
2712 CheckAbstractUsage(*this, D).Visit(TL, Sel);
2713}
2714
2715}
2716
2717/// Check for invalid uses of an abstract type in a method declaration.
2718static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2719 CXXMethodDecl *MD) {
2720 // No need to do the check on definitions, which require that
2721 // the return/param types be complete.
2722 if (MD->isThisDeclarationADefinition())
2723 return;
2724
2725 // For safety's sake, just ignore it if we don't have type source
2726 // information. This should never happen for non-implicit methods,
2727 // but...
2728 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
2729 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
2730}
2731
2732/// Check for invalid uses of an abstract type within a class definition.
2733static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2734 CXXRecordDecl *RD) {
2735 for (CXXRecordDecl::decl_iterator
2736 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
2737 Decl *D = *I;
2738 if (D->isImplicit()) continue;
2739
2740 // Methods and method templates.
2741 if (isa<CXXMethodDecl>(D)) {
2742 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
2743 } else if (isa<FunctionTemplateDecl>(D)) {
2744 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
2745 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
2746
2747 // Fields and static variables.
2748 } else if (isa<FieldDecl>(D)) {
2749 FieldDecl *FD = cast<FieldDecl>(D);
2750 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
2751 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
2752 } else if (isa<VarDecl>(D)) {
2753 VarDecl *VD = cast<VarDecl>(D);
2754 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
2755 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
2756
2757 // Nested classes and class templates.
2758 } else if (isa<CXXRecordDecl>(D)) {
2759 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
2760 } else if (isa<ClassTemplateDecl>(D)) {
2761 CheckAbstractClassUsage(Info,
2762 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
2763 }
2764 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002765}
2766
Douglas Gregorc99f1552009-12-03 18:33:45 +00002767/// \brief Perform semantic checks on a class definition that has been
2768/// completing, introducing implicitly-declared members, checking for
2769/// abstract types, etc.
Douglas Gregor0be31a22010-07-02 17:43:08 +00002770void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +00002771 if (!Record)
Douglas Gregorc99f1552009-12-03 18:33:45 +00002772 return;
2773
John McCall02db245d2010-08-18 09:41:07 +00002774 if (Record->isAbstract() && !Record->isInvalidDecl()) {
2775 AbstractUsageInfo Info(*this, Record);
2776 CheckAbstractClassUsage(Info, Record);
2777 }
Douglas Gregor454a5b62010-04-15 00:00:53 +00002778
2779 // If this is not an aggregate type and has no user-declared constructor,
2780 // complain about any non-static data members of reference or const scalar
2781 // type, since they will never get initializers.
2782 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
2783 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
2784 bool Complained = false;
2785 for (RecordDecl::field_iterator F = Record->field_begin(),
2786 FEnd = Record->field_end();
2787 F != FEnd; ++F) {
2788 if (F->getType()->isReferenceType() ||
Benjamin Kramer659d7fc2010-04-16 17:43:15 +00002789 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00002790 if (!Complained) {
2791 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
2792 << Record->getTagKind() << Record;
2793 Complained = true;
2794 }
2795
2796 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
2797 << F->getType()->isReferenceType()
2798 << F->getDeclName();
2799 }
2800 }
2801 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00002802
Anders Carlssone771e762011-01-25 18:08:22 +00002803 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor88d292c2010-05-13 16:44:06 +00002804 DynamicClasses.push_back(Record);
Douglas Gregor36c22a22010-10-15 13:21:21 +00002805
2806 if (Record->getIdentifier()) {
2807 // C++ [class.mem]p13:
2808 // If T is the name of a class, then each of the following shall have a
2809 // name different from T:
2810 // - every member of every anonymous union that is a member of class T.
2811 //
2812 // C++ [class.mem]p14:
2813 // In addition, if class T has a user-declared constructor (12.1), every
2814 // non-static data member of class T shall have a name different from T.
2815 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
Francois Pichet783dd6e2010-11-21 06:08:52 +00002816 R.first != R.second; ++R.first) {
2817 NamedDecl *D = *R.first;
2818 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
2819 isa<IndirectFieldDecl>(D)) {
2820 Diag(D->getLocation(), diag::err_member_name_of_class)
2821 << D->getDeclName();
Douglas Gregor36c22a22010-10-15 13:21:21 +00002822 break;
2823 }
Francois Pichet783dd6e2010-11-21 06:08:52 +00002824 }
Douglas Gregor36c22a22010-10-15 13:21:21 +00002825 }
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00002826
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00002827 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregor0cf82f62011-02-19 19:14:36 +00002828 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00002829 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00002830 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00002831 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
2832 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
2833 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00002834
2835 // See if a method overloads virtual methods in a base
2836 /// class without overriding any.
2837 if (!Record->isDependentType()) {
2838 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
2839 MEnd = Record->method_end();
2840 M != MEnd; ++M) {
Argyrios Kyrtzidis7a1778e2011-03-03 22:58:57 +00002841 if (!(*M)->isStatic())
2842 DiagnoseHiddenVirtualMethods(Record, *M);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00002843 }
2844 }
Sebastian Redl08905022011-02-05 19:23:19 +00002845
2846 // Declare inherited constructors. We do this eagerly here because:
2847 // - The standard requires an eager diagnostic for conflicting inherited
2848 // constructors from different classes.
2849 // - The lazy declaration of the other implicit constructors is so as to not
2850 // waste space and performance on classes that are not meant to be
2851 // instantiated (e.g. meta-functions). This doesn't apply to classes that
2852 // have inherited constructors.
2853 DeclareInheritedConstructors(Record);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00002854}
2855
2856/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramer024e6192011-03-04 13:12:48 +00002857namespace {
2858 struct FindHiddenVirtualMethodData {
2859 Sema *S;
2860 CXXMethodDecl *Method;
2861 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
2862 llvm::SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
2863 };
2864}
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00002865
2866/// \brief Member lookup function that determines whether a given C++
2867/// method overloads virtual methods in a base class without overriding any,
2868/// to be used with CXXRecordDecl::lookupInBases().
2869static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
2870 CXXBasePath &Path,
2871 void *UserData) {
2872 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
2873
2874 FindHiddenVirtualMethodData &Data
2875 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
2876
2877 DeclarationName Name = Data.Method->getDeclName();
2878 assert(Name.getNameKind() == DeclarationName::Identifier);
2879
2880 bool foundSameNameMethod = false;
2881 llvm::SmallVector<CXXMethodDecl *, 8> overloadedMethods;
2882 for (Path.Decls = BaseRecord->lookup(Name);
2883 Path.Decls.first != Path.Decls.second;
2884 ++Path.Decls.first) {
2885 NamedDecl *D = *Path.Decls.first;
2886 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00002887 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00002888 foundSameNameMethod = true;
2889 // Interested only in hidden virtual methods.
2890 if (!MD->isVirtual())
2891 continue;
2892 // If the method we are checking overrides a method from its base
2893 // don't warn about the other overloaded methods.
2894 if (!Data.S->IsOverload(Data.Method, MD, false))
2895 return true;
2896 // Collect the overload only if its hidden.
2897 if (!Data.OverridenAndUsingBaseMethods.count(MD))
2898 overloadedMethods.push_back(MD);
2899 }
2900 }
2901
2902 if (foundSameNameMethod)
2903 Data.OverloadedMethods.append(overloadedMethods.begin(),
2904 overloadedMethods.end());
2905 return foundSameNameMethod;
2906}
2907
2908/// \brief See if a method overloads virtual methods in a base class without
2909/// overriding any.
2910void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
2911 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
2912 MD->getLocation()) == Diagnostic::Ignored)
2913 return;
2914 if (MD->getDeclName().getNameKind() != DeclarationName::Identifier)
2915 return;
2916
2917 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
2918 /*bool RecordPaths=*/false,
2919 /*bool DetectVirtual=*/false);
2920 FindHiddenVirtualMethodData Data;
2921 Data.Method = MD;
2922 Data.S = this;
2923
2924 // Keep the base methods that were overriden or introduced in the subclass
2925 // by 'using' in a set. A base method not in this set is hidden.
2926 for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
2927 res.first != res.second; ++res.first) {
2928 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first))
2929 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
2930 E = MD->end_overridden_methods();
2931 I != E; ++I)
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00002932 Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl());
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00002933 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
2934 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl()))
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00002935 Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl());
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00002936 }
2937
2938 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
2939 !Data.OverloadedMethods.empty()) {
2940 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
2941 << MD << (Data.OverloadedMethods.size() > 1);
2942
2943 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
2944 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
2945 Diag(overloadedMD->getLocation(),
2946 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
2947 }
2948 }
Douglas Gregorc99f1552009-12-03 18:33:45 +00002949}
2950
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002951void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCall48871652010-08-21 09:40:31 +00002952 Decl *TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002953 SourceLocation LBrac,
Douglas Gregorc48a10d2010-03-29 14:42:08 +00002954 SourceLocation RBrac,
2955 AttributeList *AttrList) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002956 if (!TagDecl)
2957 return;
Mike Stump11289f42009-09-09 15:08:12 +00002958
Douglas Gregorc9f9b862009-05-11 19:58:34 +00002959 AdjustDeclIfTemplate(TagDecl);
Douglas Gregorc99f1552009-12-03 18:33:45 +00002960
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002961 ActOnFields(S, RLoc, TagDecl,
John McCall48871652010-08-21 09:40:31 +00002962 // strict aliasing violation!
2963 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
Douglas Gregorc48a10d2010-03-29 14:42:08 +00002964 FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList);
Douglas Gregor463421d2009-03-03 04:44:36 +00002965
Douglas Gregor0be31a22010-07-02 17:43:08 +00002966 CheckCompletedCXXClass(
John McCall48871652010-08-21 09:40:31 +00002967 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002968}
2969
Douglas Gregor95755162010-07-01 05:10:53 +00002970namespace {
2971 /// \brief Helper class that collects exception specifications for
2972 /// implicitly-declared special member functions.
2973 class ImplicitExceptionSpecification {
2974 ASTContext &Context;
2975 bool AllowsAllExceptions;
2976 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
2977 llvm::SmallVector<QualType, 4> Exceptions;
2978
2979 public:
2980 explicit ImplicitExceptionSpecification(ASTContext &Context)
2981 : Context(Context), AllowsAllExceptions(false) { }
2982
2983 /// \brief Whether the special member function should have any
2984 /// exception specification at all.
2985 bool hasExceptionSpecification() const {
2986 return !AllowsAllExceptions;
2987 }
2988
2989 /// \brief Whether the special member function should have a
2990 /// throw(...) exception specification (a Microsoft extension).
2991 bool hasAnyExceptionSpecification() const {
2992 return false;
2993 }
2994
2995 /// \brief The number of exceptions in the exception specification.
2996 unsigned size() const { return Exceptions.size(); }
2997
2998 /// \brief The set of exceptions in the exception specification.
2999 const QualType *data() const { return Exceptions.data(); }
3000
3001 /// \brief Note that
3002 void CalledDecl(CXXMethodDecl *Method) {
3003 // If we already know that we allow all exceptions, do nothing.
Douglas Gregor3311ed42010-07-01 15:29:53 +00003004 if (AllowsAllExceptions || !Method)
Douglas Gregor95755162010-07-01 05:10:53 +00003005 return;
3006
3007 const FunctionProtoType *Proto
3008 = Method->getType()->getAs<FunctionProtoType>();
3009
3010 // If this function can throw any exceptions, make a note of that.
3011 if (!Proto->hasExceptionSpec() || Proto->hasAnyExceptionSpec()) {
3012 AllowsAllExceptions = true;
3013 ExceptionsSeen.clear();
3014 Exceptions.clear();
3015 return;
3016 }
3017
3018 // Record the exceptions in this function's exception specification.
3019 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
3020 EEnd = Proto->exception_end();
3021 E != EEnd; ++E)
3022 if (ExceptionsSeen.insert(Context.getCanonicalType(*E)))
3023 Exceptions.push_back(*E);
3024 }
3025 };
3026}
3027
3028
Douglas Gregor05379422008-11-03 17:51:48 +00003029/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
3030/// special functions, such as the default constructor, copy
3031/// constructor, or destructor, to the given C++ class (C++
3032/// [special]p1). This routine can only be executed just before the
3033/// definition of the class is complete.
Douglas Gregor0be31a22010-07-02 17:43:08 +00003034void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00003035 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00003036 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00003037
Douglas Gregor54be3392010-07-01 17:57:27 +00003038 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregora6d69502010-07-02 23:41:54 +00003039 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00003040
Douglas Gregor330b9cf2010-07-02 21:50:04 +00003041 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
3042 ++ASTContext::NumImplicitCopyAssignmentOperators;
3043
3044 // If we have a dynamic class, then the copy assignment operator may be
3045 // virtual, so we have to declare it immediately. This ensures that, e.g.,
3046 // it shows up in the right place in the vtable and that we diagnose
3047 // problems with the implicit exception specification.
3048 if (ClassDecl->isDynamicClass())
3049 DeclareImplicitCopyAssignment(ClassDecl);
3050 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00003051
Douglas Gregor7454c562010-07-02 20:37:36 +00003052 if (!ClassDecl->hasUserDeclaredDestructor()) {
3053 ++ASTContext::NumImplicitDestructors;
3054
3055 // If we have a dynamic class, then the destructor may be virtual, so we
3056 // have to declare the destructor immediately. This ensures that, e.g., it
3057 // shows up in the right place in the vtable and that we diagnose problems
3058 // with the implicit exception specification.
3059 if (ClassDecl->isDynamicClass())
3060 DeclareImplicitDestructor(ClassDecl);
3061 }
Douglas Gregor05379422008-11-03 17:51:48 +00003062}
3063
John McCall48871652010-08-21 09:40:31 +00003064void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregore61ef622009-09-10 00:12:48 +00003065 if (!D)
3066 return;
3067
3068 TemplateParameterList *Params = 0;
3069 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
3070 Params = Template->getTemplateParameters();
3071 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
3072 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
3073 Params = PartialSpec->getTemplateParameters();
3074 else
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003075 return;
3076
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003077 for (TemplateParameterList::iterator Param = Params->begin(),
3078 ParamEnd = Params->end();
3079 Param != ParamEnd; ++Param) {
3080 NamedDecl *Named = cast<NamedDecl>(*Param);
3081 if (Named->getDeclName()) {
John McCall48871652010-08-21 09:40:31 +00003082 S->AddDecl(Named);
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003083 IdResolver.AddDecl(Named);
3084 }
3085 }
3086}
3087
John McCall48871652010-08-21 09:40:31 +00003088void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00003089 if (!RecordD) return;
3090 AdjustDeclIfTemplate(RecordD);
John McCall48871652010-08-21 09:40:31 +00003091 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall6df5fef2009-12-19 10:49:29 +00003092 PushDeclContext(S, Record);
3093}
3094
John McCall48871652010-08-21 09:40:31 +00003095void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00003096 if (!RecordD) return;
3097 PopDeclContext();
3098}
3099
Douglas Gregor4d87df52008-12-16 21:30:33 +00003100/// ActOnStartDelayedCXXMethodDeclaration - We have completed
3101/// parsing a top-level (non-nested) C++ class, and we are now
3102/// parsing those parts of the given Method declaration that could
3103/// not be parsed earlier (C++ [class.mem]p2), such as default
3104/// arguments. This action should enter the scope of the given
3105/// Method declaration as if we had just parsed the qualified method
3106/// name. However, it should not bring the parameters into scope;
3107/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCall48871652010-08-21 09:40:31 +00003108void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00003109}
3110
3111/// ActOnDelayedCXXMethodParameter - We've already started a delayed
3112/// C++ method declaration. We're (re-)introducing the given
3113/// function parameter into scope for use in parsing later parts of
3114/// the method declaration. For example, we could see an
3115/// ActOnParamDefaultArgument event for this parameter.
John McCall48871652010-08-21 09:40:31 +00003116void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00003117 if (!ParamD)
3118 return;
Mike Stump11289f42009-09-09 15:08:12 +00003119
John McCall48871652010-08-21 09:40:31 +00003120 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor58354032008-12-24 00:01:03 +00003121
3122 // If this parameter has an unparsed default argument, clear it out
3123 // to make way for the parsed default argument.
3124 if (Param->hasUnparsedDefaultArg())
3125 Param->setDefaultArg(0);
3126
John McCall48871652010-08-21 09:40:31 +00003127 S->AddDecl(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +00003128 if (Param->getDeclName())
3129 IdResolver.AddDecl(Param);
3130}
3131
3132/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
3133/// processing the delayed method declaration for Method. The method
3134/// declaration is now considered finished. There may be a separate
3135/// ActOnStartOfFunctionDef action later (not necessarily
3136/// immediately!) for this method, if it was also defined inside the
3137/// class body.
John McCall48871652010-08-21 09:40:31 +00003138void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00003139 if (!MethodD)
3140 return;
Mike Stump11289f42009-09-09 15:08:12 +00003141
Douglas Gregorc8c277a2009-08-24 11:57:43 +00003142 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00003143
John McCall48871652010-08-21 09:40:31 +00003144 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor4d87df52008-12-16 21:30:33 +00003145
3146 // Now that we have our default arguments, check the constructor
3147 // again. It could produce additional diagnostics or affect whether
3148 // the class has implicitly-declared destructors, among other
3149 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003150 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
3151 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00003152
3153 // Check the default arguments, which we may have added.
3154 if (!Method->isInvalidDecl())
3155 CheckCXXDefaultArguments(Method);
3156}
3157
Douglas Gregor831c93f2008-11-05 20:51:48 +00003158/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00003159/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00003160/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00003161/// emit diagnostics and set the invalid bit to true. In any case, the type
3162/// will be updated to reflect a well-formed type for the constructor and
3163/// returned.
3164QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00003165 StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003166 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00003167
3168 // C++ [class.ctor]p3:
3169 // A constructor shall not be virtual (10.3) or static (9.4). A
3170 // constructor can be invoked for a const, volatile or const
3171 // volatile object. A constructor shall not be declared const,
3172 // volatile, or const volatile (9.3.2).
3173 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00003174 if (!D.isInvalidType())
3175 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
3176 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
3177 << SourceRange(D.getIdentifierLoc());
3178 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00003179 }
John McCall8e7d6562010-08-26 03:08:43 +00003180 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00003181 if (!D.isInvalidType())
3182 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
3183 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
3184 << SourceRange(D.getIdentifierLoc());
3185 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00003186 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00003187 }
Mike Stump11289f42009-09-09 15:08:12 +00003188
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003189 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00003190 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00003191 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00003192 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
3193 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00003194 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00003195 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
3196 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00003197 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00003198 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
3199 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalldb40c7f2010-12-14 08:05:40 +00003200 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00003201 }
Mike Stump11289f42009-09-09 15:08:12 +00003202
Douglas Gregordb9d6642011-01-26 05:01:58 +00003203 // C++0x [class.ctor]p4:
3204 // A constructor shall not be declared with a ref-qualifier.
3205 if (FTI.hasRefQualifier()) {
3206 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
3207 << FTI.RefQualifierIsLValueRef
3208 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
3209 D.setInvalidType();
3210 }
3211
Douglas Gregor831c93f2008-11-05 20:51:48 +00003212 // Rebuild the function type "R" without any type qualifiers (in
3213 // case any of the errors above fired) and with "void" as the
Douglas Gregor95755162010-07-01 05:10:53 +00003214 // return type, since constructors don't have return types.
John McCall9dd450b2009-09-21 23:43:11 +00003215 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00003216 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
3217 return R;
3218
3219 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3220 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00003221 EPI.RefQualifier = RQ_None;
3222
Chris Lattner38378bf2009-04-25 08:28:21 +00003223 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00003224 Proto->getNumArgs(), EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00003225}
3226
Douglas Gregor4d87df52008-12-16 21:30:33 +00003227/// CheckConstructor - Checks a fully-formed constructor for
3228/// well-formedness, issuing any diagnostics required. Returns true if
3229/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003230void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00003231 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00003232 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
3233 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003234 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00003235
3236 // C++ [class.copy]p3:
3237 // A declaration of a constructor for a class X is ill-formed if
3238 // its first parameter is of type (optionally cv-qualified) X and
3239 // either there are no other parameters or else all other
3240 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00003241 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00003242 ((Constructor->getNumParams() == 1) ||
3243 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00003244 Constructor->getParamDecl(1)->hasDefaultArg())) &&
3245 Constructor->getTemplateSpecializationKind()
3246 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00003247 QualType ParamType = Constructor->getParamDecl(0)->getType();
3248 QualType ClassTy = Context.getTagDeclType(ClassDecl);
3249 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00003250 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregorfd42e952010-05-27 21:28:21 +00003251 const char *ConstRef
3252 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
3253 : " const &";
Douglas Gregor170512f2009-04-01 23:51:29 +00003254 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregorfd42e952010-05-27 21:28:21 +00003255 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregorffe14e32009-11-14 01:20:54 +00003256
3257 // FIXME: Rather that making the constructor invalid, we should endeavor
3258 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003259 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00003260 }
3261 }
Douglas Gregor4d87df52008-12-16 21:30:33 +00003262}
3263
John McCalldeb646e2010-08-04 01:04:25 +00003264/// CheckDestructor - Checks a fully-formed destructor definition for
3265/// well-formedness, issuing any diagnostics required. Returns true
3266/// on error.
Anders Carlssonf98849e2009-12-02 17:15:43 +00003267bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00003268 CXXRecordDecl *RD = Destructor->getParent();
3269
3270 if (Destructor->isVirtual()) {
3271 SourceLocation Loc;
3272
3273 if (!Destructor->isImplicit())
3274 Loc = Destructor->getLocation();
3275 else
3276 Loc = RD->getLocation();
3277
3278 // If we have a virtual destructor, look up the deallocation function
3279 FunctionDecl *OperatorDelete = 0;
3280 DeclarationName Name =
3281 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlssonf98849e2009-12-02 17:15:43 +00003282 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson26a807d2009-11-30 21:24:50 +00003283 return true;
John McCall1e5d75d2010-07-03 18:33:00 +00003284
3285 MarkDeclarationReferenced(Loc, OperatorDelete);
Anders Carlsson26a807d2009-11-30 21:24:50 +00003286
3287 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson2a50e952009-11-15 22:49:34 +00003288 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00003289
3290 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00003291}
3292
Mike Stump11289f42009-09-09 15:08:12 +00003293static inline bool
Anders Carlsson5e965472009-04-30 23:18:11 +00003294FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
3295 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
3296 FTI.ArgInfo[0].Param &&
John McCall48871652010-08-21 09:40:31 +00003297 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson5e965472009-04-30 23:18:11 +00003298}
3299
Douglas Gregor831c93f2008-11-05 20:51:48 +00003300/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
3301/// the well-formednes of the destructor declarator @p D with type @p
3302/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00003303/// emit diagnostics and set the declarator to invalid. Even if this happens,
3304/// will be updated to reflect a well-formed type for the destructor and
3305/// returned.
Douglas Gregor95755162010-07-01 05:10:53 +00003306QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00003307 StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003308 // C++ [class.dtor]p1:
3309 // [...] A typedef-name that names a class is a class-name
3310 // (7.1.3); however, a typedef-name that names a class shall not
3311 // be used as the identifier in the declarator for a destructor
3312 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00003313 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Douglas Gregor95755162010-07-01 05:10:53 +00003314 if (isa<TypedefType>(DeclaratorType))
Chris Lattner38378bf2009-04-25 08:28:21 +00003315 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor9817f4a2009-02-09 15:09:02 +00003316 << DeclaratorType;
Douglas Gregor831c93f2008-11-05 20:51:48 +00003317
3318 // C++ [class.dtor]p2:
3319 // A destructor is used to destroy objects of its class type. A
3320 // destructor takes no parameters, and no return type can be
3321 // specified for it (not even void). The address of a destructor
3322 // shall not be taken. A destructor shall not be static. A
3323 // destructor can be invoked for a const, volatile or const
3324 // volatile object. A destructor shall not be declared const,
3325 // volatile or const volatile (9.3.2).
John McCall8e7d6562010-08-26 03:08:43 +00003326 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00003327 if (!D.isInvalidType())
3328 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
3329 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregor95755162010-07-01 05:10:53 +00003330 << SourceRange(D.getIdentifierLoc())
3331 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
3332
John McCall8e7d6562010-08-26 03:08:43 +00003333 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00003334 }
Chris Lattner38378bf2009-04-25 08:28:21 +00003335 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003336 // Destructors don't have return types, but the parser will
3337 // happily parse something like:
3338 //
3339 // class X {
3340 // float ~X();
3341 // };
3342 //
3343 // The return type will be eliminated later.
Chris Lattner3b054132008-11-19 05:08:23 +00003344 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
3345 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3346 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00003347 }
Mike Stump11289f42009-09-09 15:08:12 +00003348
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003349 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00003350 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00003351 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00003352 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3353 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00003354 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00003355 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3356 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00003357 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00003358 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3359 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00003360 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00003361 }
3362
Douglas Gregordb9d6642011-01-26 05:01:58 +00003363 // C++0x [class.dtor]p2:
3364 // A destructor shall not be declared with a ref-qualifier.
3365 if (FTI.hasRefQualifier()) {
3366 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
3367 << FTI.RefQualifierIsLValueRef
3368 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
3369 D.setInvalidType();
3370 }
3371
Douglas Gregor831c93f2008-11-05 20:51:48 +00003372 // Make sure we don't have any parameters.
Anders Carlsson5e965472009-04-30 23:18:11 +00003373 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003374 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
3375
3376 // Delete the parameters.
Chris Lattner38378bf2009-04-25 08:28:21 +00003377 FTI.freeArgs();
3378 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00003379 }
3380
Mike Stump11289f42009-09-09 15:08:12 +00003381 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00003382 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003383 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00003384 D.setInvalidType();
3385 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00003386
3387 // Rebuild the function type "R" without any type qualifiers or
3388 // parameters (in case any of the errors above fired) and with
3389 // "void" as the return type, since destructors don't have return
Douglas Gregor95755162010-07-01 05:10:53 +00003390 // types.
John McCalldb40c7f2010-12-14 08:05:40 +00003391 if (!D.isInvalidType())
3392 return R;
3393
Douglas Gregor95755162010-07-01 05:10:53 +00003394 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00003395 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3396 EPI.Variadic = false;
3397 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00003398 EPI.RefQualifier = RQ_None;
John McCalldb40c7f2010-12-14 08:05:40 +00003399 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00003400}
3401
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003402/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
3403/// well-formednes of the conversion function declarator @p D with
3404/// type @p R. If there are any errors in the declarator, this routine
3405/// will emit diagnostics and return true. Otherwise, it will return
3406/// false. Either way, the type @p R will be updated to reflect a
3407/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003408void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCall8e7d6562010-08-26 03:08:43 +00003409 StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003410 // C++ [class.conv.fct]p1:
3411 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00003412 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00003413 // parameter returning conversion-type-id."
John McCall8e7d6562010-08-26 03:08:43 +00003414 if (SC == SC_Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003415 if (!D.isInvalidType())
3416 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
3417 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
3418 << SourceRange(D.getIdentifierLoc());
3419 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00003420 SC = SC_None;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003421 }
John McCall212fa2e2010-04-13 00:04:31 +00003422
3423 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
3424
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003425 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003426 // Conversion functions don't have return types, but the parser will
3427 // happily parse something like:
3428 //
3429 // class X {
3430 // float operator bool();
3431 // };
3432 //
3433 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00003434 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
3435 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3436 << SourceRange(D.getIdentifierLoc());
John McCall212fa2e2010-04-13 00:04:31 +00003437 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003438 }
3439
John McCall212fa2e2010-04-13 00:04:31 +00003440 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
3441
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003442 // Make sure we don't have any parameters.
John McCall212fa2e2010-04-13 00:04:31 +00003443 if (Proto->getNumArgs() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003444 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
3445
3446 // Delete the parameters.
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003447 D.getFunctionTypeInfo().freeArgs();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003448 D.setInvalidType();
John McCall212fa2e2010-04-13 00:04:31 +00003449 } else if (Proto->isVariadic()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003450 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003451 D.setInvalidType();
3452 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003453
John McCall212fa2e2010-04-13 00:04:31 +00003454 // Diagnose "&operator bool()" and other such nonsense. This
3455 // is actually a gcc extension which we don't support.
3456 if (Proto->getResultType() != ConvType) {
3457 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
3458 << Proto->getResultType();
3459 D.setInvalidType();
3460 ConvType = Proto->getResultType();
3461 }
3462
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003463 // C++ [class.conv.fct]p4:
3464 // The conversion-type-id shall not represent a function type nor
3465 // an array type.
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003466 if (ConvType->isArrayType()) {
3467 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
3468 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003469 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003470 } else if (ConvType->isFunctionType()) {
3471 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
3472 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003473 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003474 }
3475
3476 // Rebuild the function type "R" without any parameters (in case any
3477 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00003478 // return type.
John McCalldb40c7f2010-12-14 08:05:40 +00003479 if (D.isInvalidType())
3480 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003481
Douglas Gregor5fb53972009-01-14 15:45:31 +00003482 // C++0x explicit conversion operators.
3483 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump11289f42009-09-09 15:08:12 +00003484 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor5fb53972009-01-14 15:45:31 +00003485 diag::warn_explicit_conversion_functions)
3486 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003487}
3488
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003489/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
3490/// the declaration of the given C++ conversion function. This routine
3491/// is responsible for recording the conversion function in the C++
3492/// class, if possible.
John McCall48871652010-08-21 09:40:31 +00003493Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003494 assert(Conversion && "Expected to receive a conversion function declaration");
3495
Douglas Gregor4287b372008-12-12 08:25:50 +00003496 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003497
3498 // Make sure we aren't redeclaring the conversion function.
3499 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003500
3501 // C++ [class.conv.fct]p1:
3502 // [...] A conversion function is never used to convert a
3503 // (possibly cv-qualified) object to the (possibly cv-qualified)
3504 // same object type (or a reference to it), to a (possibly
3505 // cv-qualified) base class of that type (or a reference to it),
3506 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00003507 // FIXME: Suppress this warning if the conversion function ends up being a
3508 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00003509 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003510 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003511 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003512 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregor6309e3d2010-09-12 07:22:28 +00003513 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
3514 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregore47191c2010-09-13 16:44:26 +00003515 /* Suppress diagnostics for instantiations. */;
Douglas Gregor6309e3d2010-09-12 07:22:28 +00003516 else if (ConvType->isRecordType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003517 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
3518 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003519 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003520 << ClassType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003521 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003522 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003523 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003524 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003525 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003526 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003527 }
3528
Douglas Gregor457104e2010-09-29 04:25:11 +00003529 if (FunctionTemplateDecl *ConversionTemplate
3530 = Conversion->getDescribedFunctionTemplate())
3531 return ConversionTemplate;
3532
John McCall48871652010-08-21 09:40:31 +00003533 return Conversion;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003534}
3535
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003536//===----------------------------------------------------------------------===//
3537// Namespace Handling
3538//===----------------------------------------------------------------------===//
3539
John McCallb1be5232010-08-26 09:15:37 +00003540
3541
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003542/// ActOnStartNamespaceDef - This is called at the start of a namespace
3543/// definition.
John McCall48871652010-08-21 09:40:31 +00003544Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redl67667942010-08-27 23:12:46 +00003545 SourceLocation InlineLoc,
John McCallb1be5232010-08-26 09:15:37 +00003546 SourceLocation IdentLoc,
3547 IdentifierInfo *II,
3548 SourceLocation LBrace,
3549 AttributeList *AttrList) {
Douglas Gregor086cae62010-08-19 20:55:47 +00003550 // anonymous namespace starts at its left brace
3551 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext,
3552 (II ? IdentLoc : LBrace) , II);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003553 Namespc->setLBracLoc(LBrace);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00003554 Namespc->setInline(InlineLoc.isValid());
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003555
3556 Scope *DeclRegionScope = NamespcScope->getParent();
3557
Anders Carlssona7bcade2010-02-07 01:09:23 +00003558 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
3559
John McCall2faf32c2010-12-10 02:59:44 +00003560 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
3561 PushNamespaceVisibilityAttr(Attr);
Eli Friedman570024a2010-08-05 06:57:20 +00003562
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003563 if (II) {
3564 // C++ [namespace.def]p2:
Douglas Gregor412c3622010-10-22 15:24:46 +00003565 // The identifier in an original-namespace-definition shall not
3566 // have been previously defined in the declarative region in
3567 // which the original-namespace-definition appears. The
3568 // identifier in an original-namespace-definition is the name of
3569 // the namespace. Subsequently in that declarative region, it is
3570 // treated as an original-namespace-name.
3571 //
3572 // Since namespace names are unique in their scope, and we don't
3573 // look through using directives, just
3574 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
3575 NamedDecl *PrevDecl = R.first == R.second? 0 : *R.first;
Mike Stump11289f42009-09-09 15:08:12 +00003576
Douglas Gregor91f84212008-12-11 16:49:14 +00003577 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
3578 // This is an extended namespace definition.
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00003579 if (Namespc->isInline() != OrigNS->isInline()) {
3580 // inline-ness must match
3581 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
3582 << Namespc->isInline();
3583 Diag(OrigNS->getLocation(), diag::note_previous_definition);
3584 Namespc->setInvalidDecl();
3585 // Recover by ignoring the new namespace's inline status.
3586 Namespc->setInline(OrigNS->isInline());
3587 }
3588
Douglas Gregor91f84212008-12-11 16:49:14 +00003589 // Attach this namespace decl to the chain of extended namespace
3590 // definitions.
3591 OrigNS->setNextNamespace(Namespc);
3592 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003593
Mike Stump11289f42009-09-09 15:08:12 +00003594 // Remove the previous declaration from the scope.
John McCall48871652010-08-21 09:40:31 +00003595 if (DeclRegionScope->isDeclScope(OrigNS)) {
Douglas Gregor7a4fad12008-12-11 20:41:00 +00003596 IdResolver.RemoveDecl(OrigNS);
John McCall48871652010-08-21 09:40:31 +00003597 DeclRegionScope->RemoveDecl(OrigNS);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003598 }
Douglas Gregor91f84212008-12-11 16:49:14 +00003599 } else if (PrevDecl) {
3600 // This is an invalid name redefinition.
3601 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
3602 << Namespc->getDeclName();
3603 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3604 Namespc->setInvalidDecl();
3605 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor87f54062009-09-15 22:30:29 +00003606 } else if (II->isStr("std") &&
Sebastian Redl50c68252010-08-31 00:36:30 +00003607 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00003608 // This is the first "real" definition of the namespace "std", so update
3609 // our cache of the "std" namespace to point at this definition.
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003610 if (NamespaceDecl *StdNS = getStdNamespace()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00003611 // We had already defined a dummy namespace "std". Link this new
3612 // namespace definition to the dummy namespace "std".
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003613 StdNS->setNextNamespace(Namespc);
3614 StdNS->setLocation(IdentLoc);
3615 Namespc->setOriginalNamespace(StdNS->getOriginalNamespace());
Douglas Gregor87f54062009-09-15 22:30:29 +00003616 }
3617
3618 // Make our StdNamespace cache point at the first real definition of the
3619 // "std" namespace.
3620 StdNamespace = Namespc;
Mike Stump11289f42009-09-09 15:08:12 +00003621 }
Douglas Gregor91f84212008-12-11 16:49:14 +00003622
3623 PushOnScopeChains(Namespc, DeclRegionScope);
3624 } else {
John McCall4fa53422009-10-01 00:25:31 +00003625 // Anonymous namespaces.
John McCall0db42252009-12-16 02:06:49 +00003626 assert(Namespc->isAnonymousNamespace());
John McCall0db42252009-12-16 02:06:49 +00003627
3628 // Link the anonymous namespace into its parent.
3629 NamespaceDecl *PrevDecl;
Sebastian Redl50c68252010-08-31 00:36:30 +00003630 DeclContext *Parent = CurContext->getRedeclContext();
John McCall0db42252009-12-16 02:06:49 +00003631 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
3632 PrevDecl = TU->getAnonymousNamespace();
3633 TU->setAnonymousNamespace(Namespc);
3634 } else {
3635 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
3636 PrevDecl = ND->getAnonymousNamespace();
3637 ND->setAnonymousNamespace(Namespc);
3638 }
3639
3640 // Link the anonymous namespace with its previous declaration.
3641 if (PrevDecl) {
3642 assert(PrevDecl->isAnonymousNamespace());
3643 assert(!PrevDecl->getNextNamespace());
3644 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
3645 PrevDecl->setNextNamespace(Namespc);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00003646
3647 if (Namespc->isInline() != PrevDecl->isInline()) {
3648 // inline-ness must match
3649 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
3650 << Namespc->isInline();
3651 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3652 Namespc->setInvalidDecl();
3653 // Recover by ignoring the new namespace's inline status.
3654 Namespc->setInline(PrevDecl->isInline());
3655 }
John McCall0db42252009-12-16 02:06:49 +00003656 }
John McCall4fa53422009-10-01 00:25:31 +00003657
Douglas Gregorf9f54ea2010-03-24 00:46:35 +00003658 CurContext->addDecl(Namespc);
3659
John McCall4fa53422009-10-01 00:25:31 +00003660 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
3661 // behaves as if it were replaced by
3662 // namespace unique { /* empty body */ }
3663 // using namespace unique;
3664 // namespace unique { namespace-body }
3665 // where all occurrences of 'unique' in a translation unit are
3666 // replaced by the same identifier and this identifier differs
3667 // from all other identifiers in the entire program.
3668
3669 // We just create the namespace with an empty name and then add an
3670 // implicit using declaration, just like the standard suggests.
3671 //
3672 // CodeGen enforces the "universally unique" aspect by giving all
3673 // declarations semantically contained within an anonymous
3674 // namespace internal linkage.
3675
John McCall0db42252009-12-16 02:06:49 +00003676 if (!PrevDecl) {
3677 UsingDirectiveDecl* UD
3678 = UsingDirectiveDecl::Create(Context, CurContext,
3679 /* 'using' */ LBrace,
3680 /* 'namespace' */ SourceLocation(),
Douglas Gregor12441b32011-02-25 16:33:46 +00003681 /* qualifier */ NestedNameSpecifierLoc(),
John McCall0db42252009-12-16 02:06:49 +00003682 /* identifier */ SourceLocation(),
3683 Namespc,
3684 /* Ancestor */ CurContext);
3685 UD->setImplicit();
3686 CurContext->addDecl(UD);
3687 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003688 }
3689
3690 // Although we could have an invalid decl (i.e. the namespace name is a
3691 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00003692 // FIXME: We should be able to push Namespc here, so that the each DeclContext
3693 // for the namespace has the declarations that showed up in that particular
3694 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00003695 PushDeclContext(NamespcScope, Namespc);
John McCall48871652010-08-21 09:40:31 +00003696 return Namespc;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003697}
3698
Sebastian Redla6602e92009-11-23 15:34:23 +00003699/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
3700/// is a namespace alias, returns the namespace it points to.
3701static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
3702 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
3703 return AD->getNamespace();
3704 return dyn_cast_or_null<NamespaceDecl>(D);
3705}
3706
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003707/// ActOnFinishNamespaceDef - This callback is called after a namespace is
3708/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCall48871652010-08-21 09:40:31 +00003709void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003710 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
3711 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
3712 Namespc->setRBracLoc(RBrace);
3713 PopDeclContext();
Eli Friedman570024a2010-08-05 06:57:20 +00003714 if (Namespc->hasAttr<VisibilityAttr>())
3715 PopPragmaVisibility();
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003716}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003717
John McCall28a0cf72010-08-25 07:42:41 +00003718CXXRecordDecl *Sema::getStdBadAlloc() const {
3719 return cast_or_null<CXXRecordDecl>(
3720 StdBadAlloc.get(Context.getExternalSource()));
3721}
3722
3723NamespaceDecl *Sema::getStdNamespace() const {
3724 return cast_or_null<NamespaceDecl>(
3725 StdNamespace.get(Context.getExternalSource()));
3726}
3727
Douglas Gregorcdf87022010-06-29 17:53:46 +00003728/// \brief Retrieve the special "std" namespace, which may require us to
3729/// implicitly define the namespace.
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00003730NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregorcdf87022010-06-29 17:53:46 +00003731 if (!StdNamespace) {
3732 // The "std" namespace has not yet been defined, so build one implicitly.
3733 StdNamespace = NamespaceDecl::Create(Context,
3734 Context.getTranslationUnitDecl(),
3735 SourceLocation(),
3736 &PP.getIdentifierTable().get("std"));
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003737 getStdNamespace()->setImplicit(true);
Douglas Gregorcdf87022010-06-29 17:53:46 +00003738 }
3739
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003740 return getStdNamespace();
Douglas Gregorcdf87022010-06-29 17:53:46 +00003741}
3742
John McCall48871652010-08-21 09:40:31 +00003743Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattner83f095c2009-03-28 19:18:32 +00003744 SourceLocation UsingLoc,
3745 SourceLocation NamespcLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003746 CXXScopeSpec &SS,
Chris Lattner83f095c2009-03-28 19:18:32 +00003747 SourceLocation IdentLoc,
3748 IdentifierInfo *NamespcName,
3749 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00003750 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3751 assert(NamespcName && "Invalid NamespcName.");
3752 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall9b72f892010-11-10 02:40:36 +00003753
3754 // This can only happen along a recovery path.
3755 while (S->getFlags() & Scope::TemplateParamScope)
3756 S = S->getParent();
Douglas Gregor889ceb72009-02-03 19:21:40 +00003757 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00003758
Douglas Gregor889ceb72009-02-03 19:21:40 +00003759 UsingDirectiveDecl *UDir = 0;
Douglas Gregorcdf87022010-06-29 17:53:46 +00003760 NestedNameSpecifier *Qualifier = 0;
3761 if (SS.isSet())
3762 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3763
Douglas Gregor34074322009-01-14 22:20:51 +00003764 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00003765 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
3766 LookupParsedName(R, S, &SS);
3767 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00003768 return 0;
John McCall27b18f82009-11-17 02:14:36 +00003769
Douglas Gregorcdf87022010-06-29 17:53:46 +00003770 if (R.empty()) {
3771 // Allow "using namespace std;" or "using namespace ::std;" even if
3772 // "std" hasn't been defined yet, for GCC compatibility.
3773 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
3774 NamespcName->isStr("std")) {
3775 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00003776 R.addDecl(getOrCreateStdNamespace());
Douglas Gregorcdf87022010-06-29 17:53:46 +00003777 R.resolveKind();
3778 }
3779 // Otherwise, attempt typo correction.
3780 else if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
3781 CTC_NoKeywords, 0)) {
3782 if (R.getAsSingle<NamespaceDecl>() ||
3783 R.getAsSingle<NamespaceAliasDecl>()) {
3784 if (DeclContext *DC = computeDeclContext(SS, false))
3785 Diag(IdentLoc, diag::err_using_directive_member_suggest)
3786 << NamespcName << DC << Corrected << SS.getRange()
3787 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3788 else
3789 Diag(IdentLoc, diag::err_using_directive_suggest)
3790 << NamespcName << Corrected
3791 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3792 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
3793 << Corrected;
3794
3795 NamespcName = Corrected.getAsIdentifierInfo();
Douglas Gregorc048c522010-06-29 19:27:42 +00003796 } else {
3797 R.clear();
3798 R.setLookupName(NamespcName);
Douglas Gregorcdf87022010-06-29 17:53:46 +00003799 }
3800 }
3801 }
3802
John McCall9f3059a2009-10-09 21:13:30 +00003803 if (!R.empty()) {
Sebastian Redla6602e92009-11-23 15:34:23 +00003804 NamedDecl *Named = R.getFoundDecl();
3805 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
3806 && "expected namespace decl");
Douglas Gregor889ceb72009-02-03 19:21:40 +00003807 // C++ [namespace.udir]p1:
3808 // A using-directive specifies that the names in the nominated
3809 // namespace can be used in the scope in which the
3810 // using-directive appears after the using-directive. During
3811 // unqualified name lookup (3.4.1), the names appear as if they
3812 // were declared in the nearest enclosing namespace which
3813 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00003814 // namespace. [Note: in this context, "contains" means "contains
3815 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00003816
3817 // Find enclosing context containing both using-directive and
3818 // nominated namespace.
Sebastian Redla6602e92009-11-23 15:34:23 +00003819 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003820 DeclContext *CommonAncestor = cast<DeclContext>(NS);
3821 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
3822 CommonAncestor = CommonAncestor->getParent();
3823
Sebastian Redla6602e92009-11-23 15:34:23 +00003824 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor12441b32011-02-25 16:33:46 +00003825 SS.getWithLocInContext(Context),
Sebastian Redla6602e92009-11-23 15:34:23 +00003826 IdentLoc, Named, CommonAncestor);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003827 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00003828 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00003829 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00003830 }
3831
Douglas Gregor889ceb72009-02-03 19:21:40 +00003832 // FIXME: We ignore attributes for now.
John McCall48871652010-08-21 09:40:31 +00003833 return UDir;
Douglas Gregor889ceb72009-02-03 19:21:40 +00003834}
3835
3836void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
3837 // If scope has associated entity, then using directive is at namespace
3838 // or translation unit scope. We add UsingDirectiveDecls, into
3839 // it's lookup structure.
3840 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003841 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003842 else
3843 // Otherwise it is block-sope. using-directives will affect lookup
3844 // only to the end of scope.
John McCall48871652010-08-21 09:40:31 +00003845 S->PushUsingDirective(UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00003846}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003847
Douglas Gregorfec52632009-06-20 00:51:54 +00003848
John McCall48871652010-08-21 09:40:31 +00003849Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall9b72f892010-11-10 02:40:36 +00003850 AccessSpecifier AS,
3851 bool HasUsingKeyword,
3852 SourceLocation UsingLoc,
3853 CXXScopeSpec &SS,
3854 UnqualifiedId &Name,
3855 AttributeList *AttrList,
3856 bool IsTypeName,
3857 SourceLocation TypenameLoc) {
Douglas Gregorfec52632009-06-20 00:51:54 +00003858 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00003859
Douglas Gregor220f4272009-11-04 16:30:06 +00003860 switch (Name.getKind()) {
3861 case UnqualifiedId::IK_Identifier:
3862 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00003863 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00003864 case UnqualifiedId::IK_ConversionFunctionId:
3865 break;
3866
3867 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003868 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall3969e302009-12-08 07:46:18 +00003869 // C++0x inherited constructors.
3870 if (getLangOptions().CPlusPlus0x) break;
3871
Douglas Gregor220f4272009-11-04 16:30:06 +00003872 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
3873 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00003874 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00003875
3876 case UnqualifiedId::IK_DestructorName:
3877 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
3878 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00003879 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00003880
3881 case UnqualifiedId::IK_TemplateId:
3882 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
3883 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCall48871652010-08-21 09:40:31 +00003884 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00003885 }
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003886
3887 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
3888 DeclarationName TargetName = TargetNameInfo.getName();
John McCall3969e302009-12-08 07:46:18 +00003889 if (!TargetName)
John McCall48871652010-08-21 09:40:31 +00003890 return 0;
John McCall3969e302009-12-08 07:46:18 +00003891
John McCalla0097262009-12-11 02:10:03 +00003892 // Warn about using declarations.
3893 // TODO: store that the declaration was written without 'using' and
3894 // talk about access decls instead of using decls in the
3895 // diagnostics.
3896 if (!HasUsingKeyword) {
3897 UsingLoc = Name.getSourceRange().getBegin();
3898
3899 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregora771f462010-03-31 17:46:05 +00003900 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCalla0097262009-12-11 02:10:03 +00003901 }
3902
Douglas Gregorc4356532010-12-16 00:46:58 +00003903 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
3904 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
3905 return 0;
3906
John McCall3f746822009-11-17 05:59:44 +00003907 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003908 TargetNameInfo, AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00003909 /* IsInstantiation */ false,
3910 IsTypeName, TypenameLoc);
John McCallb96ec562009-12-04 22:46:56 +00003911 if (UD)
3912 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00003913
John McCall48871652010-08-21 09:40:31 +00003914 return UD;
Anders Carlsson696a3f12009-08-28 05:40:36 +00003915}
3916
Douglas Gregor1d9ef842010-07-07 23:08:52 +00003917/// \brief Determine whether a using declaration considers the given
3918/// declarations as "equivalent", e.g., if they are redeclarations of
3919/// the same entity or are both typedefs of the same type.
3920static bool
3921IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
3922 bool &SuppressRedeclaration) {
3923 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
3924 SuppressRedeclaration = false;
3925 return true;
3926 }
3927
3928 if (TypedefDecl *TD1 = dyn_cast<TypedefDecl>(D1))
3929 if (TypedefDecl *TD2 = dyn_cast<TypedefDecl>(D2)) {
3930 SuppressRedeclaration = true;
3931 return Context.hasSameType(TD1->getUnderlyingType(),
3932 TD2->getUnderlyingType());
3933 }
3934
3935 return false;
3936}
3937
3938
John McCall84d87672009-12-10 09:41:52 +00003939/// Determines whether to create a using shadow decl for a particular
3940/// decl, given the set of decls existing prior to this using lookup.
3941bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
3942 const LookupResult &Previous) {
3943 // Diagnose finding a decl which is not from a base class of the
3944 // current class. We do this now because there are cases where this
3945 // function will silently decide not to build a shadow decl, which
3946 // will pre-empt further diagnostics.
3947 //
3948 // We don't need to do this in C++0x because we do the check once on
3949 // the qualifier.
3950 //
3951 // FIXME: diagnose the following if we care enough:
3952 // struct A { int foo; };
3953 // struct B : A { using A::foo; };
3954 // template <class T> struct C : A {};
3955 // template <class T> struct D : C<T> { using B::foo; } // <---
3956 // This is invalid (during instantiation) in C++03 because B::foo
3957 // resolves to the using decl in B, which is not a base class of D<T>.
3958 // We can't diagnose it immediately because C<T> is an unknown
3959 // specialization. The UsingShadowDecl in D<T> then points directly
3960 // to A::foo, which will look well-formed when we instantiate.
3961 // The right solution is to not collapse the shadow-decl chain.
3962 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
3963 DeclContext *OrigDC = Orig->getDeclContext();
3964
3965 // Handle enums and anonymous structs.
3966 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
3967 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
3968 while (OrigRec->isAnonymousStructOrUnion())
3969 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
3970
3971 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
3972 if (OrigDC == CurContext) {
3973 Diag(Using->getLocation(),
3974 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00003975 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00003976 Diag(Orig->getLocation(), diag::note_using_decl_target);
3977 return true;
3978 }
3979
Douglas Gregora9d87bc2011-02-25 00:36:19 +00003980 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall84d87672009-12-10 09:41:52 +00003981 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00003982 << Using->getQualifier()
John McCall84d87672009-12-10 09:41:52 +00003983 << cast<CXXRecordDecl>(CurContext)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00003984 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00003985 Diag(Orig->getLocation(), diag::note_using_decl_target);
3986 return true;
3987 }
3988 }
3989
3990 if (Previous.empty()) return false;
3991
3992 NamedDecl *Target = Orig;
3993 if (isa<UsingShadowDecl>(Target))
3994 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3995
John McCalla17e83e2009-12-11 02:33:26 +00003996 // If the target happens to be one of the previous declarations, we
3997 // don't have a conflict.
3998 //
3999 // FIXME: but we might be increasing its access, in which case we
4000 // should redeclare it.
4001 NamedDecl *NonTag = 0, *Tag = 0;
4002 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4003 I != E; ++I) {
4004 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor1d9ef842010-07-07 23:08:52 +00004005 bool Result;
4006 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
4007 return Result;
John McCalla17e83e2009-12-11 02:33:26 +00004008
4009 (isa<TagDecl>(D) ? Tag : NonTag) = D;
4010 }
4011
John McCall84d87672009-12-10 09:41:52 +00004012 if (Target->isFunctionOrFunctionTemplate()) {
4013 FunctionDecl *FD;
4014 if (isa<FunctionTemplateDecl>(Target))
4015 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
4016 else
4017 FD = cast<FunctionDecl>(Target);
4018
4019 NamedDecl *OldDecl = 0;
John McCalle9cccd82010-06-16 08:42:20 +00004020 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall84d87672009-12-10 09:41:52 +00004021 case Ovl_Overload:
4022 return false;
4023
4024 case Ovl_NonFunction:
John McCalle29c5cd2009-12-10 19:51:03 +00004025 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00004026 break;
4027
4028 // We found a decl with the exact signature.
4029 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00004030 // If we're in a record, we want to hide the target, so we
4031 // return true (without a diagnostic) to tell the caller not to
4032 // build a shadow decl.
4033 if (CurContext->isRecord())
4034 return true;
4035
4036 // If we're not in a record, this is an error.
John McCalle29c5cd2009-12-10 19:51:03 +00004037 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00004038 break;
4039 }
4040
4041 Diag(Target->getLocation(), diag::note_using_decl_target);
4042 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
4043 return true;
4044 }
4045
4046 // Target is not a function.
4047
John McCall84d87672009-12-10 09:41:52 +00004048 if (isa<TagDecl>(Target)) {
4049 // No conflict between a tag and a non-tag.
4050 if (!Tag) return false;
4051
John McCalle29c5cd2009-12-10 19:51:03 +00004052 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00004053 Diag(Target->getLocation(), diag::note_using_decl_target);
4054 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
4055 return true;
4056 }
4057
4058 // No conflict between a tag and a non-tag.
4059 if (!NonTag) return false;
4060
John McCalle29c5cd2009-12-10 19:51:03 +00004061 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00004062 Diag(Target->getLocation(), diag::note_using_decl_target);
4063 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
4064 return true;
4065}
4066
John McCall3f746822009-11-17 05:59:44 +00004067/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall3969e302009-12-08 07:46:18 +00004068UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall3969e302009-12-08 07:46:18 +00004069 UsingDecl *UD,
4070 NamedDecl *Orig) {
John McCall3f746822009-11-17 05:59:44 +00004071
4072 // If we resolved to another shadow declaration, just coalesce them.
John McCall3969e302009-12-08 07:46:18 +00004073 NamedDecl *Target = Orig;
4074 if (isa<UsingShadowDecl>(Target)) {
4075 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
4076 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall3f746822009-11-17 05:59:44 +00004077 }
4078
4079 UsingShadowDecl *Shadow
John McCall3969e302009-12-08 07:46:18 +00004080 = UsingShadowDecl::Create(Context, CurContext,
4081 UD->getLocation(), UD, Target);
John McCall3f746822009-11-17 05:59:44 +00004082 UD->addShadowDecl(Shadow);
Douglas Gregor457104e2010-09-29 04:25:11 +00004083
4084 Shadow->setAccess(UD->getAccess());
4085 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
4086 Shadow->setInvalidDecl();
4087
John McCall3f746822009-11-17 05:59:44 +00004088 if (S)
John McCall3969e302009-12-08 07:46:18 +00004089 PushOnScopeChains(Shadow, S);
John McCall3f746822009-11-17 05:59:44 +00004090 else
John McCall3969e302009-12-08 07:46:18 +00004091 CurContext->addDecl(Shadow);
John McCall3f746822009-11-17 05:59:44 +00004092
John McCall3969e302009-12-08 07:46:18 +00004093
John McCall84d87672009-12-10 09:41:52 +00004094 return Shadow;
4095}
John McCall3969e302009-12-08 07:46:18 +00004096
John McCall84d87672009-12-10 09:41:52 +00004097/// Hides a using shadow declaration. This is required by the current
4098/// using-decl implementation when a resolvable using declaration in a
4099/// class is followed by a declaration which would hide or override
4100/// one or more of the using decl's targets; for example:
4101///
4102/// struct Base { void foo(int); };
4103/// struct Derived : Base {
4104/// using Base::foo;
4105/// void foo(int);
4106/// };
4107///
4108/// The governing language is C++03 [namespace.udecl]p12:
4109///
4110/// When a using-declaration brings names from a base class into a
4111/// derived class scope, member functions in the derived class
4112/// override and/or hide member functions with the same name and
4113/// parameter types in a base class (rather than conflicting).
4114///
4115/// There are two ways to implement this:
4116/// (1) optimistically create shadow decls when they're not hidden
4117/// by existing declarations, or
4118/// (2) don't create any shadow decls (or at least don't make them
4119/// visible) until we've fully parsed/instantiated the class.
4120/// The problem with (1) is that we might have to retroactively remove
4121/// a shadow decl, which requires several O(n) operations because the
4122/// decl structures are (very reasonably) not designed for removal.
4123/// (2) avoids this but is very fiddly and phase-dependent.
4124void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCallda4458e2010-03-31 01:36:47 +00004125 if (Shadow->getDeclName().getNameKind() ==
4126 DeclarationName::CXXConversionFunctionName)
4127 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
4128
John McCall84d87672009-12-10 09:41:52 +00004129 // Remove it from the DeclContext...
4130 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00004131
John McCall84d87672009-12-10 09:41:52 +00004132 // ...and the scope, if applicable...
4133 if (S) {
John McCall48871652010-08-21 09:40:31 +00004134 S->RemoveDecl(Shadow);
John McCall84d87672009-12-10 09:41:52 +00004135 IdResolver.RemoveDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00004136 }
4137
John McCall84d87672009-12-10 09:41:52 +00004138 // ...and the using decl.
4139 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
4140
4141 // TODO: complain somehow if Shadow was used. It shouldn't
John McCallda4458e2010-03-31 01:36:47 +00004142 // be possible for this to happen, because...?
John McCall3f746822009-11-17 05:59:44 +00004143}
4144
John McCalle61f2ba2009-11-18 02:36:19 +00004145/// Builds a using declaration.
4146///
4147/// \param IsInstantiation - Whether this call arises from an
4148/// instantiation of an unresolved using declaration. We treat
4149/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00004150NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
4151 SourceLocation UsingLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00004152 CXXScopeSpec &SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00004153 const DeclarationNameInfo &NameInfo,
Anders Carlsson696a3f12009-08-28 05:40:36 +00004154 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00004155 bool IsInstantiation,
4156 bool IsTypeName,
4157 SourceLocation TypenameLoc) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00004158 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnara8de74e92010-08-12 11:46:03 +00004159 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlsson696a3f12009-08-28 05:40:36 +00004160 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00004161
Anders Carlssonf038fc22009-08-28 05:49:21 +00004162 // FIXME: We ignore attributes for now.
Mike Stump11289f42009-09-09 15:08:12 +00004163
Anders Carlsson59140b32009-08-28 03:16:11 +00004164 if (SS.isEmpty()) {
4165 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlsson696a3f12009-08-28 05:40:36 +00004166 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00004167 }
Mike Stump11289f42009-09-09 15:08:12 +00004168
John McCall84d87672009-12-10 09:41:52 +00004169 // Do the redeclaration lookup in the current scope.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00004170 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall84d87672009-12-10 09:41:52 +00004171 ForRedeclaration);
4172 Previous.setHideTags(false);
4173 if (S) {
4174 LookupName(Previous, S);
4175
4176 // It is really dumb that we have to do this.
4177 LookupResult::Filter F = Previous.makeFilter();
4178 while (F.hasNext()) {
4179 NamedDecl *D = F.next();
4180 if (!isDeclInScope(D, CurContext, S))
4181 F.erase();
4182 }
4183 F.done();
4184 } else {
4185 assert(IsInstantiation && "no scope in non-instantiation");
4186 assert(CurContext->isRecord() && "scope not record in instantiation");
4187 LookupQualifiedName(Previous, CurContext);
4188 }
4189
John McCall84d87672009-12-10 09:41:52 +00004190 // Check for invalid redeclarations.
4191 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
4192 return 0;
4193
4194 // Check for bad qualifiers.
John McCallb96ec562009-12-04 22:46:56 +00004195 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
4196 return 0;
4197
John McCall84c16cf2009-11-12 03:15:40 +00004198 DeclContext *LookupContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00004199 NamedDecl *D;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00004200 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall84c16cf2009-11-12 03:15:40 +00004201 if (!LookupContext) {
John McCalle61f2ba2009-11-18 02:36:19 +00004202 if (IsTypeName) {
John McCallb96ec562009-12-04 22:46:56 +00004203 // FIXME: not all declaration name kinds are legal here
4204 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
4205 UsingLoc, TypenameLoc,
Douglas Gregora9d87bc2011-02-25 00:36:19 +00004206 QualifierLoc,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00004207 IdentLoc, NameInfo.getName());
John McCallb96ec562009-12-04 22:46:56 +00004208 } else {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00004209 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
4210 QualifierLoc, NameInfo);
John McCalle61f2ba2009-11-18 02:36:19 +00004211 }
John McCallb96ec562009-12-04 22:46:56 +00004212 } else {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00004213 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
4214 NameInfo, IsTypeName);
Anders Carlssonf038fc22009-08-28 05:49:21 +00004215 }
John McCallb96ec562009-12-04 22:46:56 +00004216 D->setAccess(AS);
4217 CurContext->addDecl(D);
4218
4219 if (!LookupContext) return D;
4220 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump11289f42009-09-09 15:08:12 +00004221
John McCall0b66eb32010-05-01 00:40:08 +00004222 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall3969e302009-12-08 07:46:18 +00004223 UD->setInvalidDecl();
4224 return UD;
Anders Carlsson59140b32009-08-28 03:16:11 +00004225 }
4226
Sebastian Redl08905022011-02-05 19:23:19 +00004227 // Constructor inheriting using decls get special treatment.
4228 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
4229 if (CheckInheritedConstructorUsingDecl(UD))
4230 UD->setInvalidDecl();
4231 return UD;
4232 }
4233
4234 // Otherwise, look up the target name.
John McCall3969e302009-12-08 07:46:18 +00004235
Abramo Bagnara8de74e92010-08-12 11:46:03 +00004236 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle61f2ba2009-11-18 02:36:19 +00004237
John McCall3969e302009-12-08 07:46:18 +00004238 // Unlike most lookups, we don't always want to hide tag
4239 // declarations: tag names are visible through the using declaration
4240 // even if hidden by ordinary names, *except* in a dependent context
4241 // where it's important for the sanity of two-phase lookup.
John McCalle61f2ba2009-11-18 02:36:19 +00004242 if (!IsInstantiation)
4243 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00004244
John McCall27b18f82009-11-17 02:14:36 +00004245 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00004246
John McCall9f3059a2009-10-09 21:13:30 +00004247 if (R.empty()) {
Douglas Gregore40876a2009-10-13 21:16:44 +00004248 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnara8de74e92010-08-12 11:46:03 +00004249 << NameInfo.getName() << LookupContext << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00004250 UD->setInvalidDecl();
4251 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00004252 }
4253
John McCallb96ec562009-12-04 22:46:56 +00004254 if (R.isAmbiguous()) {
4255 UD->setInvalidDecl();
4256 return UD;
4257 }
Mike Stump11289f42009-09-09 15:08:12 +00004258
John McCalle61f2ba2009-11-18 02:36:19 +00004259 if (IsTypeName) {
4260 // If we asked for a typename and got a non-type decl, error out.
John McCallb96ec562009-12-04 22:46:56 +00004261 if (!R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00004262 Diag(IdentLoc, diag::err_using_typename_non_type);
4263 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
4264 Diag((*I)->getUnderlyingDecl()->getLocation(),
4265 diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00004266 UD->setInvalidDecl();
4267 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00004268 }
4269 } else {
4270 // If we asked for a non-typename and we got a type, error out,
4271 // but only if this is an instantiation of an unresolved using
4272 // decl. Otherwise just silently find the type name.
John McCallb96ec562009-12-04 22:46:56 +00004273 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00004274 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
4275 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00004276 UD->setInvalidDecl();
4277 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00004278 }
Anders Carlsson59140b32009-08-28 03:16:11 +00004279 }
4280
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00004281 // C++0x N2914 [namespace.udecl]p6:
4282 // A using-declaration shall not name a namespace.
John McCallb96ec562009-12-04 22:46:56 +00004283 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00004284 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
4285 << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00004286 UD->setInvalidDecl();
4287 return UD;
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00004288 }
Mike Stump11289f42009-09-09 15:08:12 +00004289
John McCall84d87672009-12-10 09:41:52 +00004290 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
4291 if (!CheckUsingShadowDecl(UD, *I, Previous))
4292 BuildUsingShadowDecl(S, UD, *I);
4293 }
John McCall3f746822009-11-17 05:59:44 +00004294
4295 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00004296}
4297
Sebastian Redl08905022011-02-05 19:23:19 +00004298/// Additional checks for a using declaration referring to a constructor name.
4299bool Sema::CheckInheritedConstructorUsingDecl(UsingDecl *UD) {
4300 if (UD->isTypeName()) {
4301 // FIXME: Cannot specify typename when specifying constructor
4302 return true;
4303 }
4304
Douglas Gregora9d87bc2011-02-25 00:36:19 +00004305 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redl08905022011-02-05 19:23:19 +00004306 assert(SourceType &&
4307 "Using decl naming constructor doesn't have type in scope spec.");
4308 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
4309
4310 // Check whether the named type is a direct base class.
4311 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
4312 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
4313 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
4314 BaseIt != BaseE; ++BaseIt) {
4315 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
4316 if (CanonicalSourceType == BaseType)
4317 break;
4318 }
4319
4320 if (BaseIt == BaseE) {
4321 // Did not find SourceType in the bases.
4322 Diag(UD->getUsingLocation(),
4323 diag::err_using_decl_constructor_not_in_direct_base)
4324 << UD->getNameInfo().getSourceRange()
4325 << QualType(SourceType, 0) << TargetClass;
4326 return true;
4327 }
4328
4329 BaseIt->setInheritConstructors();
4330
4331 return false;
4332}
4333
John McCall84d87672009-12-10 09:41:52 +00004334/// Checks that the given using declaration is not an invalid
4335/// redeclaration. Note that this is checking only for the using decl
4336/// itself, not for any ill-formedness among the UsingShadowDecls.
4337bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
4338 bool isTypeName,
4339 const CXXScopeSpec &SS,
4340 SourceLocation NameLoc,
4341 const LookupResult &Prev) {
4342 // C++03 [namespace.udecl]p8:
4343 // C++0x [namespace.udecl]p10:
4344 // A using-declaration is a declaration and can therefore be used
4345 // repeatedly where (and only where) multiple declarations are
4346 // allowed.
Douglas Gregor4b718ee2010-05-06 23:31:27 +00004347 //
John McCall032092f2010-11-29 18:01:58 +00004348 // That's in non-member contexts.
4349 if (!CurContext->getRedeclContext()->isRecord())
John McCall84d87672009-12-10 09:41:52 +00004350 return false;
4351
4352 NestedNameSpecifier *Qual
4353 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
4354
4355 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
4356 NamedDecl *D = *I;
4357
4358 bool DTypename;
4359 NestedNameSpecifier *DQual;
4360 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
4361 DTypename = UD->isTypeName();
Douglas Gregora9d87bc2011-02-25 00:36:19 +00004362 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00004363 } else if (UnresolvedUsingValueDecl *UD
4364 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
4365 DTypename = false;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00004366 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00004367 } else if (UnresolvedUsingTypenameDecl *UD
4368 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
4369 DTypename = true;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00004370 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00004371 } else continue;
4372
4373 // using decls differ if one says 'typename' and the other doesn't.
4374 // FIXME: non-dependent using decls?
4375 if (isTypeName != DTypename) continue;
4376
4377 // using decls differ if they name different scopes (but note that
4378 // template instantiation can cause this check to trigger when it
4379 // didn't before instantiation).
4380 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
4381 Context.getCanonicalNestedNameSpecifier(DQual))
4382 continue;
4383
4384 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCalle29c5cd2009-12-10 19:51:03 +00004385 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall84d87672009-12-10 09:41:52 +00004386 return true;
4387 }
4388
4389 return false;
4390}
4391
John McCall3969e302009-12-08 07:46:18 +00004392
John McCallb96ec562009-12-04 22:46:56 +00004393/// Checks that the given nested-name qualifier used in a using decl
4394/// in the current context is appropriately related to the current
4395/// scope. If an error is found, diagnoses it and returns true.
4396bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
4397 const CXXScopeSpec &SS,
4398 SourceLocation NameLoc) {
John McCall3969e302009-12-08 07:46:18 +00004399 DeclContext *NamedContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00004400
John McCall3969e302009-12-08 07:46:18 +00004401 if (!CurContext->isRecord()) {
4402 // C++03 [namespace.udecl]p3:
4403 // C++0x [namespace.udecl]p8:
4404 // A using-declaration for a class member shall be a member-declaration.
4405
4406 // If we weren't able to compute a valid scope, it must be a
4407 // dependent class scope.
4408 if (!NamedContext || NamedContext->isRecord()) {
4409 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
4410 << SS.getRange();
4411 return true;
4412 }
4413
4414 // Otherwise, everything is known to be fine.
4415 return false;
4416 }
4417
4418 // The current scope is a record.
4419
4420 // If the named context is dependent, we can't decide much.
4421 if (!NamedContext) {
4422 // FIXME: in C++0x, we can diagnose if we can prove that the
4423 // nested-name-specifier does not refer to a base class, which is
4424 // still possible in some cases.
4425
4426 // Otherwise we have to conservatively report that things might be
4427 // okay.
4428 return false;
4429 }
4430
4431 if (!NamedContext->isRecord()) {
4432 // Ideally this would point at the last name in the specifier,
4433 // but we don't have that level of source info.
4434 Diag(SS.getRange().getBegin(),
4435 diag::err_using_decl_nested_name_specifier_is_not_class)
4436 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
4437 return true;
4438 }
4439
Douglas Gregor7c842292010-12-21 07:41:49 +00004440 if (!NamedContext->isDependentContext() &&
4441 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
4442 return true;
4443
John McCall3969e302009-12-08 07:46:18 +00004444 if (getLangOptions().CPlusPlus0x) {
4445 // C++0x [namespace.udecl]p3:
4446 // In a using-declaration used as a member-declaration, the
4447 // nested-name-specifier shall name a base class of the class
4448 // being defined.
4449
4450 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
4451 cast<CXXRecordDecl>(NamedContext))) {
4452 if (CurContext == NamedContext) {
4453 Diag(NameLoc,
4454 diag::err_using_decl_nested_name_specifier_is_current_class)
4455 << SS.getRange();
4456 return true;
4457 }
4458
4459 Diag(SS.getRange().getBegin(),
4460 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4461 << (NestedNameSpecifier*) SS.getScopeRep()
4462 << cast<CXXRecordDecl>(CurContext)
4463 << SS.getRange();
4464 return true;
4465 }
4466
4467 return false;
4468 }
4469
4470 // C++03 [namespace.udecl]p4:
4471 // A using-declaration used as a member-declaration shall refer
4472 // to a member of a base class of the class being defined [etc.].
4473
4474 // Salient point: SS doesn't have to name a base class as long as
4475 // lookup only finds members from base classes. Therefore we can
4476 // diagnose here only if we can prove that that can't happen,
4477 // i.e. if the class hierarchies provably don't intersect.
4478
4479 // TODO: it would be nice if "definitely valid" results were cached
4480 // in the UsingDecl and UsingShadowDecl so that these checks didn't
4481 // need to be repeated.
4482
4483 struct UserData {
4484 llvm::DenseSet<const CXXRecordDecl*> Bases;
4485
4486 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
4487 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4488 Data->Bases.insert(Base);
4489 return true;
4490 }
4491
4492 bool hasDependentBases(const CXXRecordDecl *Class) {
4493 return !Class->forallBases(collect, this);
4494 }
4495
4496 /// Returns true if the base is dependent or is one of the
4497 /// accumulated base classes.
4498 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
4499 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4500 return !Data->Bases.count(Base);
4501 }
4502
4503 bool mightShareBases(const CXXRecordDecl *Class) {
4504 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
4505 }
4506 };
4507
4508 UserData Data;
4509
4510 // Returns false if we find a dependent base.
4511 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
4512 return false;
4513
4514 // Returns false if the class has a dependent base or if it or one
4515 // of its bases is present in the base set of the current context.
4516 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
4517 return false;
4518
4519 Diag(SS.getRange().getBegin(),
4520 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4521 << (NestedNameSpecifier*) SS.getScopeRep()
4522 << cast<CXXRecordDecl>(CurContext)
4523 << SS.getRange();
4524
4525 return true;
John McCallb96ec562009-12-04 22:46:56 +00004526}
4527
John McCall48871652010-08-21 09:40:31 +00004528Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson47952ae2009-03-28 22:53:22 +00004529 SourceLocation NamespaceLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00004530 SourceLocation AliasLoc,
4531 IdentifierInfo *Alias,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00004532 CXXScopeSpec &SS,
Anders Carlsson47952ae2009-03-28 22:53:22 +00004533 SourceLocation IdentLoc,
4534 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00004535
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004536 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00004537 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
4538 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004539
Anders Carlssondca83c42009-03-28 06:23:46 +00004540 // Check if we have a previous declaration with the same name.
Douglas Gregor5cf8d672010-05-03 15:37:31 +00004541 NamedDecl *PrevDecl
4542 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
4543 ForRedeclaration);
4544 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
4545 PrevDecl = 0;
4546
4547 if (PrevDecl) {
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004548 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump11289f42009-09-09 15:08:12 +00004549 // We already have an alias with the same name that points to the same
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004550 // namespace, so don't create a new one.
Douglas Gregor4667eff2010-03-26 22:59:39 +00004551 // FIXME: At some point, we'll want to create the (redundant)
4552 // declaration to maintain better source information.
John McCall9f3059a2009-10-09 21:13:30 +00004553 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregor4667eff2010-03-26 22:59:39 +00004554 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCall48871652010-08-21 09:40:31 +00004555 return 0;
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004556 }
Mike Stump11289f42009-09-09 15:08:12 +00004557
Anders Carlssondca83c42009-03-28 06:23:46 +00004558 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
4559 diag::err_redefinition_different_kind;
4560 Diag(AliasLoc, DiagID) << Alias;
4561 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCall48871652010-08-21 09:40:31 +00004562 return 0;
Anders Carlssondca83c42009-03-28 06:23:46 +00004563 }
4564
John McCall27b18f82009-11-17 02:14:36 +00004565 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00004566 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004567
John McCall9f3059a2009-10-09 21:13:30 +00004568 if (R.empty()) {
Douglas Gregor9629e9a2010-06-29 18:55:19 +00004569 if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
4570 CTC_NoKeywords, 0)) {
4571 if (R.getAsSingle<NamespaceDecl>() ||
4572 R.getAsSingle<NamespaceAliasDecl>()) {
4573 if (DeclContext *DC = computeDeclContext(SS, false))
4574 Diag(IdentLoc, diag::err_using_directive_member_suggest)
4575 << Ident << DC << Corrected << SS.getRange()
4576 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4577 else
4578 Diag(IdentLoc, diag::err_using_directive_suggest)
4579 << Ident << Corrected
4580 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4581
4582 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
4583 << Corrected;
4584
4585 Ident = Corrected.getAsIdentifierInfo();
Douglas Gregorc048c522010-06-29 19:27:42 +00004586 } else {
4587 R.clear();
4588 R.setLookupName(Ident);
Douglas Gregor9629e9a2010-06-29 18:55:19 +00004589 }
4590 }
4591
4592 if (R.empty()) {
4593 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00004594 return 0;
Douglas Gregor9629e9a2010-06-29 18:55:19 +00004595 }
Anders Carlssonac2c9652009-03-28 06:42:02 +00004596 }
Mike Stump11289f42009-09-09 15:08:12 +00004597
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00004598 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00004599 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregorc05ba2e2011-02-25 17:08:07 +00004600 Alias, SS.getWithLocInContext(Context),
John McCall9f3059a2009-10-09 21:13:30 +00004601 IdentLoc, R.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00004602
John McCalld8d0d432010-02-16 06:53:13 +00004603 PushOnScopeChains(AliasDecl, S);
John McCall48871652010-08-21 09:40:31 +00004604 return AliasDecl;
Anders Carlsson9205d552009-03-28 05:27:17 +00004605}
4606
Douglas Gregora57478e2010-05-01 15:04:51 +00004607namespace {
4608 /// \brief Scoped object used to handle the state changes required in Sema
4609 /// to implicitly define the body of a C++ member function;
4610 class ImplicitlyDefinedFunctionScope {
4611 Sema &S;
John McCallc1465822011-02-14 07:13:47 +00004612 Sema::ContextRAII SavedContext;
Douglas Gregora57478e2010-05-01 15:04:51 +00004613
4614 public:
4615 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
John McCallc1465822011-02-14 07:13:47 +00004616 : S(S), SavedContext(S, Method)
Douglas Gregora57478e2010-05-01 15:04:51 +00004617 {
Douglas Gregora57478e2010-05-01 15:04:51 +00004618 S.PushFunctionScope();
4619 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
4620 }
4621
4622 ~ImplicitlyDefinedFunctionScope() {
4623 S.PopExpressionEvaluationContext();
4624 S.PopFunctionOrBlockScope();
Douglas Gregora57478e2010-05-01 15:04:51 +00004625 }
4626 };
4627}
4628
Sebastian Redlc15c3262010-09-13 22:02:47 +00004629static CXXConstructorDecl *getDefaultConstructorUnsafe(Sema &Self,
4630 CXXRecordDecl *D) {
4631 ASTContext &Context = Self.Context;
4632 QualType ClassType = Context.getTypeDeclType(D);
4633 DeclarationName ConstructorName
4634 = Context.DeclarationNames.getCXXConstructorName(
4635 Context.getCanonicalType(ClassType.getUnqualifiedType()));
4636
4637 DeclContext::lookup_const_iterator Con, ConEnd;
4638 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
4639 Con != ConEnd; ++Con) {
4640 // FIXME: In C++0x, a constructor template can be a default constructor.
4641 if (isa<FunctionTemplateDecl>(*Con))
4642 continue;
4643
4644 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
4645 if (Constructor->isDefaultConstructor())
4646 return Constructor;
4647 }
4648 return 0;
4649}
4650
Douglas Gregor0be31a22010-07-02 17:43:08 +00004651CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
4652 CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004653 // C++ [class.ctor]p5:
4654 // A default constructor for a class X is a constructor of class X
4655 // that can be called without an argument. If there is no
4656 // user-declared constructor for class X, a default constructor is
4657 // implicitly declared. An implicitly-declared default constructor
4658 // is an inline public member of its class.
Douglas Gregor9672f922010-07-03 00:47:00 +00004659 assert(!ClassDecl->hasUserDeclaredConstructor() &&
4660 "Should not build implicit default constructor!");
4661
Douglas Gregor6d880b12010-07-01 22:31:05 +00004662 // C++ [except.spec]p14:
4663 // An implicitly declared special member function (Clause 12) shall have an
4664 // exception-specification. [...]
4665 ImplicitExceptionSpecification ExceptSpec(Context);
4666
4667 // Direct base-class destructors.
4668 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4669 BEnd = ClassDecl->bases_end();
4670 B != BEnd; ++B) {
4671 if (B->isVirtual()) // Handled below.
4672 continue;
4673
Douglas Gregor9672f922010-07-03 00:47:00 +00004674 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
4675 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4676 if (!BaseClassDecl->hasDeclaredDefaultConstructor())
4677 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
Sebastian Redlc15c3262010-09-13 22:02:47 +00004678 else if (CXXConstructorDecl *Constructor
4679 = getDefaultConstructorUnsafe(*this, BaseClassDecl))
Douglas Gregor6d880b12010-07-01 22:31:05 +00004680 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00004681 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00004682 }
4683
4684 // Virtual base-class destructors.
4685 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
4686 BEnd = ClassDecl->vbases_end();
4687 B != BEnd; ++B) {
Douglas Gregor9672f922010-07-03 00:47:00 +00004688 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
4689 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4690 if (!BaseClassDecl->hasDeclaredDefaultConstructor())
4691 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
4692 else if (CXXConstructorDecl *Constructor
Sebastian Redlc15c3262010-09-13 22:02:47 +00004693 = getDefaultConstructorUnsafe(*this, BaseClassDecl))
Douglas Gregor6d880b12010-07-01 22:31:05 +00004694 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00004695 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00004696 }
4697
4698 // Field destructors.
4699 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4700 FEnd = ClassDecl->field_end();
4701 F != FEnd; ++F) {
4702 if (const RecordType *RecordTy
Douglas Gregor9672f922010-07-03 00:47:00 +00004703 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
4704 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4705 if (!FieldClassDecl->hasDeclaredDefaultConstructor())
4706 ExceptSpec.CalledDecl(
4707 DeclareImplicitDefaultConstructor(FieldClassDecl));
4708 else if (CXXConstructorDecl *Constructor
Sebastian Redlc15c3262010-09-13 22:02:47 +00004709 = getDefaultConstructorUnsafe(*this, FieldClassDecl))
Douglas Gregor6d880b12010-07-01 22:31:05 +00004710 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00004711 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00004712 }
John McCalldb40c7f2010-12-14 08:05:40 +00004713
4714 FunctionProtoType::ExtProtoInfo EPI;
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00004715 EPI.ExceptionSpecType = ExceptSpec.hasExceptionSpecification() ?
4716 (ExceptSpec.hasAnyExceptionSpecification() ? EST_DynamicAny : EST_Dynamic) :
4717 EST_None;
John McCalldb40c7f2010-12-14 08:05:40 +00004718 EPI.NumExceptions = ExceptSpec.size();
4719 EPI.Exceptions = ExceptSpec.data();
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00004720
Douglas Gregor6d880b12010-07-01 22:31:05 +00004721 // Create the actual constructor declaration.
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004722 CanQualType ClassType
4723 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00004724 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004725 DeclarationName Name
4726 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00004727 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004728 CXXConstructorDecl *DefaultCon
Abramo Bagnaradff19302011-03-08 08:55:46 +00004729 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004730 Context.getFunctionType(Context.VoidTy,
John McCalldb40c7f2010-12-14 08:05:40 +00004731 0, 0, EPI),
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004732 /*TInfo=*/0,
4733 /*isExplicit=*/false,
4734 /*isInline=*/true,
4735 /*isImplicitlyDeclared=*/true);
4736 DefaultCon->setAccess(AS_public);
4737 DefaultCon->setImplicit();
4738 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Douglas Gregor9672f922010-07-03 00:47:00 +00004739
4740 // Note that we have declared this constructor.
Douglas Gregor9672f922010-07-03 00:47:00 +00004741 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
4742
Douglas Gregor0be31a22010-07-02 17:43:08 +00004743 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor9672f922010-07-03 00:47:00 +00004744 PushOnScopeChains(DefaultCon, S, false);
4745 ClassDecl->addDecl(DefaultCon);
4746
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004747 return DefaultCon;
4748}
4749
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00004750void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
4751 CXXConstructorDecl *Constructor) {
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00004752 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
Douglas Gregorebada0772010-06-17 23:14:26 +00004753 !Constructor->isUsed(false)) &&
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00004754 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00004755
Anders Carlsson423f5d82010-04-23 16:04:08 +00004756 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman9cf6b592009-11-09 19:20:36 +00004757 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +00004758
Douglas Gregora57478e2010-05-01 15:04:51 +00004759 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00004760 DiagnosticErrorTrap Trap(Diags);
Alexis Hunt1d792652011-01-08 20:30:50 +00004761 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00004762 Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00004763 Diag(CurrentLocation, diag::note_member_synthesized_at)
Anders Carlsson05bf0092010-04-22 05:40:53 +00004764 << CXXConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00004765 Constructor->setInvalidDecl();
Douglas Gregor73193272010-09-20 16:48:21 +00004766 return;
Eli Friedman9cf6b592009-11-09 19:20:36 +00004767 }
Douglas Gregor73193272010-09-20 16:48:21 +00004768
4769 SourceLocation Loc = Constructor->getLocation();
4770 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
4771
4772 Constructor->setUsed();
4773 MarkVTableUsed(CurrentLocation, ClassDecl);
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00004774}
4775
Sebastian Redl08905022011-02-05 19:23:19 +00004776void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
4777 // We start with an initial pass over the base classes to collect those that
4778 // inherit constructors from. If there are none, we can forgo all further
4779 // processing.
4780 typedef llvm::SmallVector<const RecordType *, 4> BasesVector;
4781 BasesVector BasesToInheritFrom;
4782 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
4783 BaseE = ClassDecl->bases_end();
4784 BaseIt != BaseE; ++BaseIt) {
4785 if (BaseIt->getInheritConstructors()) {
4786 QualType Base = BaseIt->getType();
4787 if (Base->isDependentType()) {
4788 // If we inherit constructors from anything that is dependent, just
4789 // abort processing altogether. We'll get another chance for the
4790 // instantiations.
4791 return;
4792 }
4793 BasesToInheritFrom.push_back(Base->castAs<RecordType>());
4794 }
4795 }
4796 if (BasesToInheritFrom.empty())
4797 return;
4798
4799 // Now collect the constructors that we already have in the current class.
4800 // Those take precedence over inherited constructors.
4801 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
4802 // unless there is a user-declared constructor with the same signature in
4803 // the class where the using-declaration appears.
4804 llvm::SmallSet<const Type *, 8> ExistingConstructors;
4805 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
4806 CtorE = ClassDecl->ctor_end();
4807 CtorIt != CtorE; ++CtorIt) {
4808 ExistingConstructors.insert(
4809 Context.getCanonicalType(CtorIt->getType()).getTypePtr());
4810 }
4811
4812 Scope *S = getScopeForContext(ClassDecl);
4813 DeclarationName CreatedCtorName =
4814 Context.DeclarationNames.getCXXConstructorName(
4815 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
4816
4817 // Now comes the true work.
4818 // First, we keep a map from constructor types to the base that introduced
4819 // them. Needed for finding conflicting constructors. We also keep the
4820 // actually inserted declarations in there, for pretty diagnostics.
4821 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
4822 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
4823 ConstructorToSourceMap InheritedConstructors;
4824 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
4825 BaseE = BasesToInheritFrom.end();
4826 BaseIt != BaseE; ++BaseIt) {
4827 const RecordType *Base = *BaseIt;
4828 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
4829 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
4830 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
4831 CtorE = BaseDecl->ctor_end();
4832 CtorIt != CtorE; ++CtorIt) {
4833 // Find the using declaration for inheriting this base's constructors.
4834 DeclarationName Name =
4835 Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
4836 UsingDecl *UD = dyn_cast_or_null<UsingDecl>(
4837 LookupSingleName(S, Name,SourceLocation(), LookupUsingDeclName));
4838 SourceLocation UsingLoc = UD ? UD->getLocation() :
4839 ClassDecl->getLocation();
4840
4841 // C++0x [class.inhctor]p1: The candidate set of inherited constructors
4842 // from the class X named in the using-declaration consists of actual
4843 // constructors and notional constructors that result from the
4844 // transformation of defaulted parameters as follows:
4845 // - all non-template default constructors of X, and
4846 // - for each non-template constructor of X that has at least one
4847 // parameter with a default argument, the set of constructors that
4848 // results from omitting any ellipsis parameter specification and
4849 // successively omitting parameters with a default argument from the
4850 // end of the parameter-type-list.
4851 CXXConstructorDecl *BaseCtor = *CtorIt;
4852 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
4853 const FunctionProtoType *BaseCtorType =
4854 BaseCtor->getType()->getAs<FunctionProtoType>();
4855
4856 for (unsigned params = BaseCtor->getMinRequiredArguments(),
4857 maxParams = BaseCtor->getNumParams();
4858 params <= maxParams; ++params) {
4859 // Skip default constructors. They're never inherited.
4860 if (params == 0)
4861 continue;
4862 // Skip copy and move constructors for the same reason.
4863 if (CanBeCopyOrMove && params == 1)
4864 continue;
4865
4866 // Build up a function type for this particular constructor.
4867 // FIXME: The working paper does not consider that the exception spec
4868 // for the inheriting constructor might be larger than that of the
4869 // source. This code doesn't yet, either.
4870 const Type *NewCtorType;
4871 if (params == maxParams)
4872 NewCtorType = BaseCtorType;
4873 else {
4874 llvm::SmallVector<QualType, 16> Args;
4875 for (unsigned i = 0; i < params; ++i) {
4876 Args.push_back(BaseCtorType->getArgType(i));
4877 }
4878 FunctionProtoType::ExtProtoInfo ExtInfo =
4879 BaseCtorType->getExtProtoInfo();
4880 ExtInfo.Variadic = false;
4881 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
4882 Args.data(), params, ExtInfo)
4883 .getTypePtr();
4884 }
4885 const Type *CanonicalNewCtorType =
4886 Context.getCanonicalType(NewCtorType);
4887
4888 // Now that we have the type, first check if the class already has a
4889 // constructor with this signature.
4890 if (ExistingConstructors.count(CanonicalNewCtorType))
4891 continue;
4892
4893 // Then we check if we have already declared an inherited constructor
4894 // with this signature.
4895 std::pair<ConstructorToSourceMap::iterator, bool> result =
4896 InheritedConstructors.insert(std::make_pair(
4897 CanonicalNewCtorType,
4898 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
4899 if (!result.second) {
4900 // Already in the map. If it came from a different class, that's an
4901 // error. Not if it's from the same.
4902 CanQualType PreviousBase = result.first->second.first;
4903 if (CanonicalBase != PreviousBase) {
4904 const CXXConstructorDecl *PrevCtor = result.first->second.second;
4905 const CXXConstructorDecl *PrevBaseCtor =
4906 PrevCtor->getInheritedConstructor();
4907 assert(PrevBaseCtor && "Conflicting constructor was not inherited");
4908
4909 Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
4910 Diag(BaseCtor->getLocation(),
4911 diag::note_using_decl_constructor_conflict_current_ctor);
4912 Diag(PrevBaseCtor->getLocation(),
4913 diag::note_using_decl_constructor_conflict_previous_ctor);
4914 Diag(PrevCtor->getLocation(),
4915 diag::note_using_decl_constructor_conflict_previous_using);
4916 }
4917 continue;
4918 }
4919
4920 // OK, we're there, now add the constructor.
4921 // C++0x [class.inhctor]p8: [...] that would be performed by a
4922 // user-writtern inline constructor [...]
4923 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
4924 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
Abramo Bagnaradff19302011-03-08 08:55:46 +00004925 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
4926 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
Sebastian Redl08905022011-02-05 19:23:19 +00004927 /*ImplicitlyDeclared=*/true);
4928 NewCtor->setAccess(BaseCtor->getAccess());
4929
4930 // Build up the parameter decls and add them.
4931 llvm::SmallVector<ParmVarDecl *, 16> ParamDecls;
4932 for (unsigned i = 0; i < params; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00004933 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
4934 UsingLoc, UsingLoc,
Sebastian Redl08905022011-02-05 19:23:19 +00004935 /*IdentifierInfo=*/0,
4936 BaseCtorType->getArgType(i),
4937 /*TInfo=*/0, SC_None,
4938 SC_None, /*DefaultArg=*/0));
4939 }
4940 NewCtor->setParams(ParamDecls.data(), ParamDecls.size());
4941 NewCtor->setInheritedConstructor(BaseCtor);
4942
4943 PushOnScopeChains(NewCtor, S, false);
4944 ClassDecl->addDecl(NewCtor);
4945 result.first->second.second = NewCtor;
4946 }
4947 }
4948 }
4949}
4950
Douglas Gregor0be31a22010-07-02 17:43:08 +00004951CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
Douglas Gregorf1203042010-07-01 19:09:28 +00004952 // C++ [class.dtor]p2:
4953 // If a class has no user-declared destructor, a destructor is
4954 // declared implicitly. An implicitly-declared destructor is an
4955 // inline public member of its class.
4956
4957 // C++ [except.spec]p14:
4958 // An implicitly declared special member function (Clause 12) shall have
4959 // an exception-specification.
4960 ImplicitExceptionSpecification ExceptSpec(Context);
4961
4962 // Direct base-class destructors.
4963 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4964 BEnd = ClassDecl->bases_end();
4965 B != BEnd; ++B) {
4966 if (B->isVirtual()) // Handled below.
4967 continue;
4968
4969 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
4970 ExceptSpec.CalledDecl(
Douglas Gregore71edda2010-07-01 22:47:18 +00004971 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00004972 }
4973
4974 // Virtual base-class destructors.
4975 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
4976 BEnd = ClassDecl->vbases_end();
4977 B != BEnd; ++B) {
4978 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
4979 ExceptSpec.CalledDecl(
Douglas Gregore71edda2010-07-01 22:47:18 +00004980 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00004981 }
4982
4983 // Field destructors.
4984 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4985 FEnd = ClassDecl->field_end();
4986 F != FEnd; ++F) {
4987 if (const RecordType *RecordTy
4988 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
4989 ExceptSpec.CalledDecl(
Douglas Gregore71edda2010-07-01 22:47:18 +00004990 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00004991 }
4992
Douglas Gregor7454c562010-07-02 20:37:36 +00004993 // Create the actual destructor declaration.
John McCalldb40c7f2010-12-14 08:05:40 +00004994 FunctionProtoType::ExtProtoInfo EPI;
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00004995 EPI.ExceptionSpecType = ExceptSpec.hasExceptionSpecification() ?
4996 (ExceptSpec.hasAnyExceptionSpecification() ? EST_DynamicAny : EST_Dynamic) :
4997 EST_None;
John McCalldb40c7f2010-12-14 08:05:40 +00004998 EPI.NumExceptions = ExceptSpec.size();
4999 EPI.Exceptions = ExceptSpec.data();
5000 QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregorf1203042010-07-01 19:09:28 +00005001
5002 CanQualType ClassType
5003 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00005004 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorf1203042010-07-01 19:09:28 +00005005 DeclarationName Name
5006 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00005007 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorf1203042010-07-01 19:09:28 +00005008 CXXDestructorDecl *Destructor
Abramo Bagnaradff19302011-03-08 08:55:46 +00005009 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, Ty, 0,
Douglas Gregorf1203042010-07-01 19:09:28 +00005010 /*isInline=*/true,
5011 /*isImplicitlyDeclared=*/true);
5012 Destructor->setAccess(AS_public);
5013 Destructor->setImplicit();
5014 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor7454c562010-07-02 20:37:36 +00005015
5016 // Note that we have declared this destructor.
Douglas Gregor7454c562010-07-02 20:37:36 +00005017 ++ASTContext::NumImplicitDestructorsDeclared;
5018
5019 // Introduce this destructor into its scope.
Douglas Gregor0be31a22010-07-02 17:43:08 +00005020 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor7454c562010-07-02 20:37:36 +00005021 PushOnScopeChains(Destructor, S, false);
5022 ClassDecl->addDecl(Destructor);
Douglas Gregorf1203042010-07-01 19:09:28 +00005023
5024 // This could be uniqued if it ever proves significant.
5025 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
5026
5027 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor7454c562010-07-02 20:37:36 +00005028
Douglas Gregorf1203042010-07-01 19:09:28 +00005029 return Destructor;
5030}
5031
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00005032void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00005033 CXXDestructorDecl *Destructor) {
Douglas Gregorebada0772010-06-17 23:14:26 +00005034 assert((Destructor->isImplicit() && !Destructor->isUsed(false)) &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00005035 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +00005036 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00005037 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005038
Douglas Gregor54818f02010-05-12 16:39:35 +00005039 if (Destructor->isInvalidDecl())
5040 return;
5041
Douglas Gregora57478e2010-05-01 15:04:51 +00005042 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005043
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00005044 DiagnosticErrorTrap Trap(Diags);
John McCalla6309952010-03-16 21:39:52 +00005045 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
5046 Destructor->getParent());
Mike Stump11289f42009-09-09 15:08:12 +00005047
Douglas Gregor54818f02010-05-12 16:39:35 +00005048 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00005049 Diag(CurrentLocation, diag::note_member_synthesized_at)
5050 << CXXDestructor << Context.getTagDeclType(ClassDecl);
5051
5052 Destructor->setInvalidDecl();
5053 return;
5054 }
5055
Douglas Gregor73193272010-09-20 16:48:21 +00005056 SourceLocation Loc = Destructor->getLocation();
5057 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
5058
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00005059 Destructor->setUsed();
Douglas Gregor88d292c2010-05-13 16:44:06 +00005060 MarkVTableUsed(CurrentLocation, ClassDecl);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00005061}
5062
Douglas Gregorb139cd52010-05-01 20:49:11 +00005063/// \brief Builds a statement that copies the given entity from \p From to
5064/// \c To.
5065///
5066/// This routine is used to copy the members of a class with an
5067/// implicitly-declared copy assignment operator. When the entities being
5068/// copied are arrays, this routine builds for loops to copy them.
5069///
5070/// \param S The Sema object used for type-checking.
5071///
5072/// \param Loc The location where the implicit copy is being generated.
5073///
5074/// \param T The type of the expressions being copied. Both expressions must
5075/// have this type.
5076///
5077/// \param To The expression we are copying to.
5078///
5079/// \param From The expression we are copying from.
5080///
Douglas Gregor40c92bb2010-05-04 15:20:55 +00005081/// \param CopyingBaseSubobject Whether we're copying a base subobject.
5082/// Otherwise, it's a non-static member subobject.
5083///
Douglas Gregorb139cd52010-05-01 20:49:11 +00005084/// \param Depth Internal parameter recording the depth of the recursion.
5085///
5086/// \returns A statement or a loop that copies the expressions.
John McCalldadc5752010-08-24 06:29:42 +00005087static StmtResult
Douglas Gregorb139cd52010-05-01 20:49:11 +00005088BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCallb268a282010-08-23 23:25:46 +00005089 Expr *To, Expr *From,
Douglas Gregor40c92bb2010-05-04 15:20:55 +00005090 bool CopyingBaseSubobject, unsigned Depth = 0) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00005091 // C++0x [class.copy]p30:
5092 // Each subobject is assigned in the manner appropriate to its type:
5093 //
5094 // - if the subobject is of class type, the copy assignment operator
5095 // for the class is used (as if by explicit qualification; that is,
5096 // ignoring any possible virtual overriding functions in more derived
5097 // classes);
5098 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
5099 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
5100
5101 // Look for operator=.
5102 DeclarationName Name
5103 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
5104 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
5105 S.LookupQualifiedName(OpLookup, ClassDecl, false);
5106
5107 // Filter out any result that isn't a copy-assignment operator.
5108 LookupResult::Filter F = OpLookup.makeFilter();
5109 while (F.hasNext()) {
5110 NamedDecl *D = F.next();
5111 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
5112 if (Method->isCopyAssignmentOperator())
5113 continue;
5114
5115 F.erase();
John McCallab8c2732010-03-16 06:11:48 +00005116 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00005117 F.done();
5118
Douglas Gregor40c92bb2010-05-04 15:20:55 +00005119 // Suppress the protected check (C++ [class.protected]) for each of the
5120 // assignment operators we found. This strange dance is required when
5121 // we're assigning via a base classes's copy-assignment operator. To
5122 // ensure that we're getting the right base class subobject (without
5123 // ambiguities), we need to cast "this" to that subobject type; to
5124 // ensure that we don't go through the virtual call mechanism, we need
5125 // to qualify the operator= name with the base class (see below). However,
5126 // this means that if the base class has a protected copy assignment
5127 // operator, the protected member access check will fail. So, we
5128 // rewrite "protected" access to "public" access in this case, since we
5129 // know by construction that we're calling from a derived class.
5130 if (CopyingBaseSubobject) {
5131 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
5132 L != LEnd; ++L) {
5133 if (L.getAccess() == AS_protected)
5134 L.setAccess(AS_public);
5135 }
5136 }
5137
Douglas Gregorb139cd52010-05-01 20:49:11 +00005138 // Create the nested-name-specifier that will be used to qualify the
5139 // reference to operator=; this is required to suppress the virtual
5140 // call mechanism.
5141 CXXScopeSpec SS;
Douglas Gregor869ad452011-02-24 17:54:50 +00005142 SS.MakeTrivial(S.Context,
5143 NestedNameSpecifier::Create(S.Context, 0, false,
5144 T.getTypePtr()),
5145 Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005146
5147 // Create the reference to operator=.
John McCalldadc5752010-08-24 06:29:42 +00005148 ExprResult OpEqualRef
John McCallb268a282010-08-23 23:25:46 +00005149 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Douglas Gregorb139cd52010-05-01 20:49:11 +00005150 /*FirstQualifierInScope=*/0, OpLookup,
5151 /*TemplateArgs=*/0,
5152 /*SuppressQualifierCheck=*/true);
5153 if (OpEqualRef.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00005154 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00005155
5156 // Build the call to the assignment operator.
John McCallb268a282010-08-23 23:25:46 +00005157
John McCalldadc5752010-08-24 06:29:42 +00005158 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregorce5aa332010-09-09 16:33:13 +00005159 OpEqualRef.takeAs<Expr>(),
5160 Loc, &From, 1, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005161 if (Call.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00005162 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00005163
5164 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00005165 }
John McCallab8c2732010-03-16 06:11:48 +00005166
Douglas Gregorb139cd52010-05-01 20:49:11 +00005167 // - if the subobject is of scalar type, the built-in assignment
5168 // operator is used.
5169 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
5170 if (!ArrayTy) {
John McCalle3027922010-08-25 11:45:40 +00005171 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005172 if (Assignment.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00005173 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00005174
5175 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00005176 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00005177
5178 // - if the subobject is an array, each element is assigned, in the
5179 // manner appropriate to the element type;
5180
5181 // Construct a loop over the array bounds, e.g.,
5182 //
5183 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
5184 //
5185 // that will copy each of the array elements.
5186 QualType SizeType = S.Context.getSizeType();
5187
5188 // Create the iteration variable.
5189 IdentifierInfo *IterationVarName = 0;
5190 {
5191 llvm::SmallString<8> Str;
5192 llvm::raw_svector_ostream OS(Str);
5193 OS << "__i" << Depth;
5194 IterationVarName = &S.Context.Idents.get(OS.str());
5195 }
Abramo Bagnaradff19302011-03-08 08:55:46 +00005196 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregorb139cd52010-05-01 20:49:11 +00005197 IterationVarName, SizeType,
5198 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCall8e7d6562010-08-26 03:08:43 +00005199 SC_None, SC_None);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005200
5201 // Initialize the iteration variable to zero.
5202 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00005203 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00005204
5205 // Create a reference to the iteration variable; we'll use this several
5206 // times throughout.
5207 Expr *IterationVarRef
John McCall7decc9e2010-11-18 06:31:45 +00005208 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00005209 assert(IterationVarRef && "Reference to invented variable cannot fail!");
5210
5211 // Create the DeclStmt that holds the iteration variable.
5212 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
5213
5214 // Create the comparison against the array bound.
Jay Foad6d4db0c2010-12-07 08:25:34 +00005215 llvm::APInt Upper
5216 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCallb268a282010-08-23 23:25:46 +00005217 Expr *Comparison
John McCallc3007a22010-10-26 07:05:15 +00005218 = new (S.Context) BinaryOperator(IterationVarRef,
John McCall7decc9e2010-11-18 06:31:45 +00005219 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
5220 BO_NE, S.Context.BoolTy,
5221 VK_RValue, OK_Ordinary, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005222
5223 // Create the pre-increment of the iteration variable.
John McCallb268a282010-08-23 23:25:46 +00005224 Expr *Increment
John McCall7decc9e2010-11-18 06:31:45 +00005225 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
5226 VK_LValue, OK_Ordinary, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005227
5228 // Subscript the "from" and "to" expressions with the iteration variable.
John McCallb268a282010-08-23 23:25:46 +00005229 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
5230 IterationVarRef, Loc));
5231 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
5232 IterationVarRef, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00005233
5234 // Build the copy for an individual element of the array.
John McCall7decc9e2010-11-18 06:31:45 +00005235 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
5236 To, From, CopyingBaseSubobject,
5237 Depth + 1);
Douglas Gregorb412e172010-07-25 18:17:45 +00005238 if (Copy.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00005239 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00005240
5241 // Construct the loop that copies all elements of this array.
John McCallb268a282010-08-23 23:25:46 +00005242 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregorb139cd52010-05-01 20:49:11 +00005243 S.MakeFullExpr(Comparison),
John McCall48871652010-08-21 09:40:31 +00005244 0, S.MakeFullExpr(Increment),
John McCallb268a282010-08-23 23:25:46 +00005245 Loc, Copy.take());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00005246}
5247
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005248/// \brief Determine whether the given class has a copy assignment operator
5249/// that accepts a const-qualified argument.
5250static bool hasConstCopyAssignment(Sema &S, const CXXRecordDecl *CClass) {
5251 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(CClass);
5252
5253 if (!Class->hasDeclaredCopyAssignment())
5254 S.DeclareImplicitCopyAssignment(Class);
5255
5256 QualType ClassType = S.Context.getCanonicalType(S.Context.getTypeDeclType(Class));
5257 DeclarationName OpName
5258 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
5259
5260 DeclContext::lookup_const_iterator Op, OpEnd;
5261 for (llvm::tie(Op, OpEnd) = Class->lookup(OpName); Op != OpEnd; ++Op) {
5262 // C++ [class.copy]p9:
5263 // A user-declared copy assignment operator is a non-static non-template
5264 // member function of class X with exactly one parameter of type X, X&,
5265 // const X&, volatile X& or const volatile X&.
5266 const CXXMethodDecl* Method = dyn_cast<CXXMethodDecl>(*Op);
5267 if (!Method)
5268 continue;
5269
5270 if (Method->isStatic())
5271 continue;
5272 if (Method->getPrimaryTemplate())
5273 continue;
5274 const FunctionProtoType *FnType =
5275 Method->getType()->getAs<FunctionProtoType>();
5276 assert(FnType && "Overloaded operator has no prototype.");
5277 // Don't assert on this; an invalid decl might have been left in the AST.
5278 if (FnType->getNumArgs() != 1 || FnType->isVariadic())
5279 continue;
5280 bool AcceptsConst = true;
5281 QualType ArgType = FnType->getArgType(0);
5282 if (const LValueReferenceType *Ref = ArgType->getAs<LValueReferenceType>()){
5283 ArgType = Ref->getPointeeType();
5284 // Is it a non-const lvalue reference?
5285 if (!ArgType.isConstQualified())
5286 AcceptsConst = false;
5287 }
5288 if (!S.Context.hasSameUnqualifiedType(ArgType, ClassType))
5289 continue;
5290
5291 // We have a single argument of type cv X or cv X&, i.e. we've found the
5292 // copy assignment operator. Return whether it accepts const arguments.
5293 return AcceptsConst;
5294 }
5295 assert(Class->isInvalidDecl() &&
5296 "No copy assignment operator declared in valid code.");
5297 return false;
5298}
5299
Douglas Gregor0be31a22010-07-02 17:43:08 +00005300CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005301 // Note: The following rules are largely analoguous to the copy
5302 // constructor rules. Note that virtual bases are not taken into account
5303 // for determining the argument type of the operator. Note also that
5304 // operators taking an object instead of a reference are allowed.
Douglas Gregor9672f922010-07-03 00:47:00 +00005305
5306
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005307 // C++ [class.copy]p10:
5308 // If the class definition does not explicitly declare a copy
5309 // assignment operator, one is declared implicitly.
5310 // The implicitly-defined copy assignment operator for a class X
5311 // will have the form
5312 //
5313 // X& X::operator=(const X&)
5314 //
5315 // if
5316 bool HasConstCopyAssignment = true;
5317
5318 // -- each direct base class B of X has a copy assignment operator
5319 // whose parameter is of type const B&, const volatile B& or B,
5320 // and
5321 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5322 BaseEnd = ClassDecl->bases_end();
5323 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
5324 assert(!Base->getType()->isDependentType() &&
5325 "Cannot generate implicit members for class with dependent bases.");
5326 const CXXRecordDecl *BaseClassDecl
5327 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005328 HasConstCopyAssignment = hasConstCopyAssignment(*this, BaseClassDecl);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005329 }
5330
5331 // -- for all the nonstatic data members of X that are of a class
5332 // type M (or array thereof), each such class type has a copy
5333 // assignment operator whose parameter is of type const M&,
5334 // const volatile M& or M.
5335 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5336 FieldEnd = ClassDecl->field_end();
5337 HasConstCopyAssignment && Field != FieldEnd;
5338 ++Field) {
5339 QualType FieldType = Context.getBaseElementType((*Field)->getType());
5340 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
5341 const CXXRecordDecl *FieldClassDecl
5342 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005343 HasConstCopyAssignment = hasConstCopyAssignment(*this, FieldClassDecl);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005344 }
5345 }
5346
5347 // Otherwise, the implicitly declared copy assignment operator will
5348 // have the form
5349 //
5350 // X& X::operator=(X&)
5351 QualType ArgType = Context.getTypeDeclType(ClassDecl);
5352 QualType RetType = Context.getLValueReferenceType(ArgType);
5353 if (HasConstCopyAssignment)
5354 ArgType = ArgType.withConst();
5355 ArgType = Context.getLValueReferenceType(ArgType);
5356
Douglas Gregor68e11362010-07-01 17:48:08 +00005357 // C++ [except.spec]p14:
5358 // An implicitly declared special member function (Clause 12) shall have an
5359 // exception-specification. [...]
5360 ImplicitExceptionSpecification ExceptSpec(Context);
5361 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5362 BaseEnd = ClassDecl->bases_end();
5363 Base != BaseEnd; ++Base) {
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005364 CXXRecordDecl *BaseClassDecl
Douglas Gregor68e11362010-07-01 17:48:08 +00005365 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005366
5367 if (!BaseClassDecl->hasDeclaredCopyAssignment())
5368 DeclareImplicitCopyAssignment(BaseClassDecl);
5369
Douglas Gregor68e11362010-07-01 17:48:08 +00005370 if (CXXMethodDecl *CopyAssign
5371 = BaseClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
5372 ExceptSpec.CalledDecl(CopyAssign);
5373 }
5374 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5375 FieldEnd = ClassDecl->field_end();
5376 Field != FieldEnd;
5377 ++Field) {
5378 QualType FieldType = Context.getBaseElementType((*Field)->getType());
5379 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005380 CXXRecordDecl *FieldClassDecl
Douglas Gregor68e11362010-07-01 17:48:08 +00005381 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005382
5383 if (!FieldClassDecl->hasDeclaredCopyAssignment())
5384 DeclareImplicitCopyAssignment(FieldClassDecl);
5385
Douglas Gregor68e11362010-07-01 17:48:08 +00005386 if (CXXMethodDecl *CopyAssign
5387 = FieldClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
5388 ExceptSpec.CalledDecl(CopyAssign);
5389 }
5390 }
5391
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005392 // An implicitly-declared copy assignment operator is an inline public
5393 // member of its class.
John McCalldb40c7f2010-12-14 08:05:40 +00005394 FunctionProtoType::ExtProtoInfo EPI;
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00005395 EPI.ExceptionSpecType = ExceptSpec.hasExceptionSpecification() ?
5396 (ExceptSpec.hasAnyExceptionSpecification() ? EST_DynamicAny : EST_Dynamic) :
5397 EST_None;
John McCalldb40c7f2010-12-14 08:05:40 +00005398 EPI.NumExceptions = ExceptSpec.size();
5399 EPI.Exceptions = ExceptSpec.data();
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005400 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaradff19302011-03-08 08:55:46 +00005401 SourceLocation ClassLoc = ClassDecl->getLocation();
5402 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005403 CXXMethodDecl *CopyAssignment
Abramo Bagnaradff19302011-03-08 08:55:46 +00005404 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
John McCalldb40c7f2010-12-14 08:05:40 +00005405 Context.getFunctionType(RetType, &ArgType, 1, EPI),
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005406 /*TInfo=*/0, /*isStatic=*/false,
John McCall8e7d6562010-08-26 03:08:43 +00005407 /*StorageClassAsWritten=*/SC_None,
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005408 /*isInline=*/true);
5409 CopyAssignment->setAccess(AS_public);
5410 CopyAssignment->setImplicit();
5411 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005412
5413 // Add the parameter to the operator.
5414 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaradff19302011-03-08 08:55:46 +00005415 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005416 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00005417 SC_None,
5418 SC_None, 0);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005419 CopyAssignment->setParams(&FromParam, 1);
5420
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005421 // Note that we have added this copy-assignment operator.
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005422 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
5423
Douglas Gregor0be31a22010-07-02 17:43:08 +00005424 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005425 PushOnScopeChains(CopyAssignment, S, false);
5426 ClassDecl->addDecl(CopyAssignment);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005427
5428 AddOverriddenMethods(ClassDecl, CopyAssignment);
5429 return CopyAssignment;
5430}
5431
Douglas Gregorb139cd52010-05-01 20:49:11 +00005432void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
5433 CXXMethodDecl *CopyAssignOperator) {
5434 assert((CopyAssignOperator->isImplicit() &&
5435 CopyAssignOperator->isOverloadedOperator() &&
5436 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Douglas Gregorebada0772010-06-17 23:14:26 +00005437 !CopyAssignOperator->isUsed(false)) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00005438 "DefineImplicitCopyAssignment called for wrong function");
5439
5440 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
5441
5442 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
5443 CopyAssignOperator->setInvalidDecl();
5444 return;
5445 }
5446
5447 CopyAssignOperator->setUsed();
5448
5449 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00005450 DiagnosticErrorTrap Trap(Diags);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005451
5452 // C++0x [class.copy]p30:
5453 // The implicitly-defined or explicitly-defaulted copy assignment operator
5454 // for a non-union class X performs memberwise copy assignment of its
5455 // subobjects. The direct base classes of X are assigned first, in the
5456 // order of their declaration in the base-specifier-list, and then the
5457 // immediate non-static data members of X are assigned, in the order in
5458 // which they were declared in the class definition.
5459
5460 // The statements that form the synthesized function body.
John McCall37ad5512010-08-23 06:44:23 +00005461 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005462
5463 // The parameter for the "other" object, which we are copying from.
5464 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
5465 Qualifiers OtherQuals = Other->getType().getQualifiers();
5466 QualType OtherRefType = Other->getType();
5467 if (const LValueReferenceType *OtherRef
5468 = OtherRefType->getAs<LValueReferenceType>()) {
5469 OtherRefType = OtherRef->getPointeeType();
5470 OtherQuals = OtherRefType.getQualifiers();
5471 }
5472
5473 // Our location for everything implicitly-generated.
5474 SourceLocation Loc = CopyAssignOperator->getLocation();
5475
5476 // Construct a reference to the "other" object. We'll be using this
5477 // throughout the generated ASTs.
John McCall4bc41ae2010-11-18 19:01:18 +00005478 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00005479 assert(OtherRef && "Reference to parameter cannot fail!");
5480
5481 // Construct the "this" pointer. We'll be using this throughout the generated
5482 // ASTs.
5483 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
5484 assert(This && "Reference to this cannot fail!");
5485
5486 // Assign base classes.
5487 bool Invalid = false;
5488 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5489 E = ClassDecl->bases_end(); Base != E; ++Base) {
5490 // Form the assignment:
5491 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
5492 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00005493 if (!BaseType->isRecordType()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00005494 Invalid = true;
5495 continue;
5496 }
5497
John McCallcf142162010-08-07 06:22:56 +00005498 CXXCastPath BasePath;
5499 BasePath.push_back(Base);
5500
Douglas Gregorb139cd52010-05-01 20:49:11 +00005501 // Construct the "from" expression, which is an implicit cast to the
5502 // appropriately-qualified base type.
John McCallc3007a22010-10-26 07:05:15 +00005503 Expr *From = OtherRef;
Douglas Gregorb139cd52010-05-01 20:49:11 +00005504 ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
John McCall2536c6d2010-08-25 10:28:54 +00005505 CK_UncheckedDerivedToBase,
5506 VK_LValue, &BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005507
5508 // Dereference "this".
John McCall2536c6d2010-08-25 10:28:54 +00005509 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005510
5511 // Implicitly cast "this" to the appropriately-qualified base type.
5512 Expr *ToE = To.takeAs<Expr>();
5513 ImpCastExprToType(ToE,
5514 Context.getCVRQualifiedType(BaseType,
5515 CopyAssignOperator->getTypeQualifiers()),
John McCall2536c6d2010-08-25 10:28:54 +00005516 CK_UncheckedDerivedToBase,
5517 VK_LValue, &BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005518 To = Owned(ToE);
5519
5520 // Build the copy.
John McCalldadc5752010-08-24 06:29:42 +00005521 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00005522 To.get(), From,
5523 /*CopyingBaseSubobject=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005524 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00005525 Diag(CurrentLocation, diag::note_member_synthesized_at)
5526 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5527 CopyAssignOperator->setInvalidDecl();
5528 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00005529 }
5530
5531 // Success! Record the copy.
5532 Statements.push_back(Copy.takeAs<Expr>());
5533 }
5534
5535 // \brief Reference to the __builtin_memcpy function.
5536 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian4a303072010-06-16 16:22:04 +00005537 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005538 Expr *CollectableMemCpyRef = 0;
Douglas Gregorb139cd52010-05-01 20:49:11 +00005539
5540 // Assign non-static members.
5541 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5542 FieldEnd = ClassDecl->field_end();
5543 Field != FieldEnd; ++Field) {
5544 // Check for members of reference type; we can't copy those.
5545 if (Field->getType()->isReferenceType()) {
5546 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
5547 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
5548 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00005549 Diag(CurrentLocation, diag::note_member_synthesized_at)
5550 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005551 Invalid = true;
5552 continue;
5553 }
5554
5555 // Check for members of const-qualified, non-class type.
5556 QualType BaseType = Context.getBaseElementType(Field->getType());
5557 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
5558 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
5559 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
5560 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00005561 Diag(CurrentLocation, diag::note_member_synthesized_at)
5562 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005563 Invalid = true;
5564 continue;
5565 }
5566
5567 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00005568 if (FieldType->isIncompleteArrayType()) {
5569 assert(ClassDecl->hasFlexibleArrayMember() &&
5570 "Incomplete array type is not valid");
5571 continue;
5572 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00005573
5574 // Build references to the field in the object we're copying from and to.
5575 CXXScopeSpec SS; // Intentionally empty
5576 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
5577 LookupMemberName);
5578 MemberLookup.addDecl(*Field);
5579 MemberLookup.resolveKind();
John McCalldadc5752010-08-24 06:29:42 +00005580 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall4bc41ae2010-11-18 19:01:18 +00005581 Loc, /*IsArrow=*/false,
5582 SS, 0, MemberLookup, 0);
John McCalldadc5752010-08-24 06:29:42 +00005583 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall4bc41ae2010-11-18 19:01:18 +00005584 Loc, /*IsArrow=*/true,
5585 SS, 0, MemberLookup, 0);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005586 assert(!From.isInvalid() && "Implicit field reference cannot fail");
5587 assert(!To.isInvalid() && "Implicit field reference cannot fail");
5588
5589 // If the field should be copied with __builtin_memcpy rather than via
5590 // explicit assignments, do so. This optimization only applies for arrays
5591 // of scalars and arrays of class type with trivial copy-assignment
5592 // operators.
5593 if (FieldType->isArrayType() &&
5594 (!BaseType->isRecordType() ||
5595 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl())
5596 ->hasTrivialCopyAssignment())) {
5597 // Compute the size of the memory buffer to be copied.
5598 QualType SizeType = Context.getSizeType();
5599 llvm::APInt Size(Context.getTypeSize(SizeType),
5600 Context.getTypeSizeInChars(BaseType).getQuantity());
5601 for (const ConstantArrayType *Array
5602 = Context.getAsConstantArrayType(FieldType);
5603 Array;
5604 Array = Context.getAsConstantArrayType(Array->getElementType())) {
Jay Foad6d4db0c2010-12-07 08:25:34 +00005605 llvm::APInt ArraySize
5606 = Array->getSize().zextOrTrunc(Size.getBitWidth());
Douglas Gregorb139cd52010-05-01 20:49:11 +00005607 Size *= ArraySize;
5608 }
5609
5610 // Take the address of the field references for "from" and "to".
John McCalle3027922010-08-25 11:45:40 +00005611 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
5612 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005613
5614 bool NeedsCollectableMemCpy =
5615 (BaseType->isRecordType() &&
5616 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
5617
5618 if (NeedsCollectableMemCpy) {
5619 if (!CollectableMemCpyRef) {
Fariborz Jahanian4a303072010-06-16 16:22:04 +00005620 // Create a reference to the __builtin_objc_memmove_collectable function.
5621 LookupResult R(*this,
5622 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005623 Loc, LookupOrdinaryName);
5624 LookupName(R, TUScope, true);
5625
5626 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
5627 if (!CollectableMemCpy) {
5628 // Something went horribly wrong earlier, and we will have
5629 // complained about it.
5630 Invalid = true;
5631 continue;
5632 }
5633
5634 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
5635 CollectableMemCpy->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00005636 VK_LValue, Loc, 0).take();
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005637 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
5638 }
5639 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00005640 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005641 else if (!BuiltinMemCpyRef) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00005642 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
5643 LookupOrdinaryName);
5644 LookupName(R, TUScope, true);
5645
5646 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
5647 if (!BuiltinMemCpy) {
5648 // Something went horribly wrong earlier, and we will have complained
5649 // about it.
5650 Invalid = true;
5651 continue;
5652 }
5653
5654 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
5655 BuiltinMemCpy->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00005656 VK_LValue, Loc, 0).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00005657 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
5658 }
5659
John McCall37ad5512010-08-23 06:44:23 +00005660 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005661 CallArgs.push_back(To.takeAs<Expr>());
5662 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00005663 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCalldadc5752010-08-24 06:29:42 +00005664 ExprResult Call = ExprError();
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005665 if (NeedsCollectableMemCpy)
5666 Call = ActOnCallExpr(/*Scope=*/0,
John McCallb268a282010-08-23 23:25:46 +00005667 CollectableMemCpyRef,
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005668 Loc, move_arg(CallArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00005669 Loc);
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005670 else
5671 Call = ActOnCallExpr(/*Scope=*/0,
John McCallb268a282010-08-23 23:25:46 +00005672 BuiltinMemCpyRef,
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005673 Loc, move_arg(CallArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00005674 Loc);
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005675
Douglas Gregorb139cd52010-05-01 20:49:11 +00005676 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
5677 Statements.push_back(Call.takeAs<Expr>());
5678 continue;
5679 }
5680
5681 // Build the copy of this field.
John McCalldadc5752010-08-24 06:29:42 +00005682 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
John McCallb268a282010-08-23 23:25:46 +00005683 To.get(), From.get(),
Douglas Gregor40c92bb2010-05-04 15:20:55 +00005684 /*CopyingBaseSubobject=*/false);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005685 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00005686 Diag(CurrentLocation, diag::note_member_synthesized_at)
5687 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5688 CopyAssignOperator->setInvalidDecl();
5689 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00005690 }
5691
5692 // Success! Record the copy.
5693 Statements.push_back(Copy.takeAs<Stmt>());
5694 }
5695
5696 if (!Invalid) {
5697 // Add a "return *this;"
John McCalle3027922010-08-25 11:45:40 +00005698 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005699
John McCalldadc5752010-08-24 06:29:42 +00005700 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregorb139cd52010-05-01 20:49:11 +00005701 if (Return.isInvalid())
5702 Invalid = true;
5703 else {
5704 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregor54818f02010-05-12 16:39:35 +00005705
5706 if (Trap.hasErrorOccurred()) {
5707 Diag(CurrentLocation, diag::note_member_synthesized_at)
5708 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5709 Invalid = true;
5710 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00005711 }
5712 }
5713
5714 if (Invalid) {
5715 CopyAssignOperator->setInvalidDecl();
5716 return;
5717 }
5718
John McCalldadc5752010-08-24 06:29:42 +00005719 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
Douglas Gregorb139cd52010-05-01 20:49:11 +00005720 /*isStmtExpr=*/false);
5721 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
5722 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00005723}
5724
Douglas Gregor0be31a22010-07-02 17:43:08 +00005725CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
5726 CXXRecordDecl *ClassDecl) {
Douglas Gregor54be3392010-07-01 17:57:27 +00005727 // C++ [class.copy]p4:
5728 // If the class definition does not explicitly declare a copy
5729 // constructor, one is declared implicitly.
5730
Douglas Gregor54be3392010-07-01 17:57:27 +00005731 // C++ [class.copy]p5:
5732 // The implicitly-declared copy constructor for a class X will
5733 // have the form
5734 //
5735 // X::X(const X&)
5736 //
5737 // if
5738 bool HasConstCopyConstructor = true;
5739
5740 // -- each direct or virtual base class B of X has a copy
5741 // constructor whose first parameter is of type const B& or
5742 // const volatile B&, and
5743 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5744 BaseEnd = ClassDecl->bases_end();
5745 HasConstCopyConstructor && Base != BaseEnd;
5746 ++Base) {
Douglas Gregorcfe68222010-07-01 18:27:03 +00005747 // Virtual bases are handled below.
5748 if (Base->isVirtual())
5749 continue;
5750
Douglas Gregora6d69502010-07-02 23:41:54 +00005751 CXXRecordDecl *BaseClassDecl
Douglas Gregorcfe68222010-07-01 18:27:03 +00005752 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005753 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5754 DeclareImplicitCopyConstructor(BaseClassDecl);
5755
Douglas Gregorcfe68222010-07-01 18:27:03 +00005756 HasConstCopyConstructor
5757 = BaseClassDecl->hasConstCopyConstructor(Context);
5758 }
5759
5760 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
5761 BaseEnd = ClassDecl->vbases_end();
5762 HasConstCopyConstructor && Base != BaseEnd;
5763 ++Base) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005764 CXXRecordDecl *BaseClassDecl
Douglas Gregor54be3392010-07-01 17:57:27 +00005765 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005766 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5767 DeclareImplicitCopyConstructor(BaseClassDecl);
5768
Douglas Gregor54be3392010-07-01 17:57:27 +00005769 HasConstCopyConstructor
5770 = BaseClassDecl->hasConstCopyConstructor(Context);
5771 }
5772
5773 // -- for all the nonstatic data members of X that are of a
5774 // class type M (or array thereof), each such class type
5775 // has a copy constructor whose first parameter is of type
5776 // const M& or const volatile M&.
5777 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5778 FieldEnd = ClassDecl->field_end();
5779 HasConstCopyConstructor && Field != FieldEnd;
5780 ++Field) {
Douglas Gregorcfe68222010-07-01 18:27:03 +00005781 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Douglas Gregor54be3392010-07-01 17:57:27 +00005782 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005783 CXXRecordDecl *FieldClassDecl
Douglas Gregorcfe68222010-07-01 18:27:03 +00005784 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005785 if (!FieldClassDecl->hasDeclaredCopyConstructor())
5786 DeclareImplicitCopyConstructor(FieldClassDecl);
5787
Douglas Gregor54be3392010-07-01 17:57:27 +00005788 HasConstCopyConstructor
Douglas Gregorcfe68222010-07-01 18:27:03 +00005789 = FieldClassDecl->hasConstCopyConstructor(Context);
Douglas Gregor54be3392010-07-01 17:57:27 +00005790 }
5791 }
5792
5793 // Otherwise, the implicitly declared copy constructor will have
5794 // the form
5795 //
5796 // X::X(X&)
5797 QualType ClassType = Context.getTypeDeclType(ClassDecl);
5798 QualType ArgType = ClassType;
5799 if (HasConstCopyConstructor)
5800 ArgType = ArgType.withConst();
5801 ArgType = Context.getLValueReferenceType(ArgType);
5802
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005803 // C++ [except.spec]p14:
5804 // An implicitly declared special member function (Clause 12) shall have an
5805 // exception-specification. [...]
5806 ImplicitExceptionSpecification ExceptSpec(Context);
5807 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
5808 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5809 BaseEnd = ClassDecl->bases_end();
5810 Base != BaseEnd;
5811 ++Base) {
5812 // Virtual bases are handled below.
5813 if (Base->isVirtual())
5814 continue;
5815
Douglas Gregora6d69502010-07-02 23:41:54 +00005816 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005817 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005818 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5819 DeclareImplicitCopyConstructor(BaseClassDecl);
5820
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005821 if (CXXConstructorDecl *CopyConstructor
5822 = BaseClassDecl->getCopyConstructor(Context, Quals))
5823 ExceptSpec.CalledDecl(CopyConstructor);
5824 }
5825 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
5826 BaseEnd = ClassDecl->vbases_end();
5827 Base != BaseEnd;
5828 ++Base) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005829 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005830 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005831 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5832 DeclareImplicitCopyConstructor(BaseClassDecl);
5833
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005834 if (CXXConstructorDecl *CopyConstructor
5835 = BaseClassDecl->getCopyConstructor(Context, Quals))
5836 ExceptSpec.CalledDecl(CopyConstructor);
5837 }
5838 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5839 FieldEnd = ClassDecl->field_end();
5840 Field != FieldEnd;
5841 ++Field) {
5842 QualType FieldType = Context.getBaseElementType((*Field)->getType());
5843 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005844 CXXRecordDecl *FieldClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005845 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005846 if (!FieldClassDecl->hasDeclaredCopyConstructor())
5847 DeclareImplicitCopyConstructor(FieldClassDecl);
5848
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005849 if (CXXConstructorDecl *CopyConstructor
5850 = FieldClassDecl->getCopyConstructor(Context, Quals))
5851 ExceptSpec.CalledDecl(CopyConstructor);
5852 }
5853 }
5854
Douglas Gregor54be3392010-07-01 17:57:27 +00005855 // An implicitly-declared copy constructor is an inline public
5856 // member of its class.
John McCalldb40c7f2010-12-14 08:05:40 +00005857 FunctionProtoType::ExtProtoInfo EPI;
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00005858 EPI.ExceptionSpecType = ExceptSpec.hasExceptionSpecification() ?
5859 (ExceptSpec.hasAnyExceptionSpecification() ? EST_DynamicAny : EST_Dynamic) :
5860 EST_None;
John McCalldb40c7f2010-12-14 08:05:40 +00005861 EPI.NumExceptions = ExceptSpec.size();
5862 EPI.Exceptions = ExceptSpec.data();
Douglas Gregor54be3392010-07-01 17:57:27 +00005863 DeclarationName Name
5864 = Context.DeclarationNames.getCXXConstructorName(
5865 Context.getCanonicalType(ClassType));
Abramo Bagnaradff19302011-03-08 08:55:46 +00005866 SourceLocation ClassLoc = ClassDecl->getLocation();
5867 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregor54be3392010-07-01 17:57:27 +00005868 CXXConstructorDecl *CopyConstructor
Abramo Bagnaradff19302011-03-08 08:55:46 +00005869 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Douglas Gregor54be3392010-07-01 17:57:27 +00005870 Context.getFunctionType(Context.VoidTy,
John McCalldb40c7f2010-12-14 08:05:40 +00005871 &ArgType, 1, EPI),
Douglas Gregor54be3392010-07-01 17:57:27 +00005872 /*TInfo=*/0,
5873 /*isExplicit=*/false,
5874 /*isInline=*/true,
5875 /*isImplicitlyDeclared=*/true);
5876 CopyConstructor->setAccess(AS_public);
Douglas Gregor54be3392010-07-01 17:57:27 +00005877 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
5878
Douglas Gregora6d69502010-07-02 23:41:54 +00005879 // Note that we have declared this constructor.
Douglas Gregora6d69502010-07-02 23:41:54 +00005880 ++ASTContext::NumImplicitCopyConstructorsDeclared;
5881
Douglas Gregor54be3392010-07-01 17:57:27 +00005882 // Add the parameter to the constructor.
5883 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaradff19302011-03-08 08:55:46 +00005884 ClassLoc, ClassLoc,
Douglas Gregor54be3392010-07-01 17:57:27 +00005885 /*IdentifierInfo=*/0,
5886 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00005887 SC_None,
5888 SC_None, 0);
Douglas Gregor54be3392010-07-01 17:57:27 +00005889 CopyConstructor->setParams(&FromParam, 1);
Douglas Gregor0be31a22010-07-02 17:43:08 +00005890 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora6d69502010-07-02 23:41:54 +00005891 PushOnScopeChains(CopyConstructor, S, false);
5892 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor54be3392010-07-01 17:57:27 +00005893
5894 return CopyConstructor;
5895}
5896
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005897void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
5898 CXXConstructorDecl *CopyConstructor,
5899 unsigned TypeQuals) {
Mike Stump11289f42009-09-09 15:08:12 +00005900 assert((CopyConstructor->isImplicit() &&
Douglas Gregor507eb872009-12-22 00:34:07 +00005901 CopyConstructor->isCopyConstructor(TypeQuals) &&
Douglas Gregorebada0772010-06-17 23:14:26 +00005902 !CopyConstructor->isUsed(false)) &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005903 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +00005904
Anders Carlsson7a0ffdb2010-04-23 16:24:12 +00005905 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005906 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005907
Douglas Gregora57478e2010-05-01 15:04:51 +00005908 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00005909 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005910
Alexis Hunt1d792652011-01-08 20:30:50 +00005911 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00005912 Trap.hasErrorOccurred()) {
Anders Carlsson79111502010-05-01 16:39:01 +00005913 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregor94f9a482010-05-05 05:51:00 +00005914 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson79111502010-05-01 16:39:01 +00005915 CopyConstructor->setInvalidDecl();
Douglas Gregor94f9a482010-05-05 05:51:00 +00005916 } else {
5917 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
5918 CopyConstructor->getLocation(),
5919 MultiStmtArg(*this, 0, 0),
5920 /*isStmtExpr=*/false)
5921 .takeAs<Stmt>());
Anders Carlsson53e1ba92010-04-25 00:52:09 +00005922 }
Douglas Gregor94f9a482010-05-05 05:51:00 +00005923
5924 CopyConstructor->setUsed();
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005925}
5926
John McCalldadc5752010-08-24 06:29:42 +00005927ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00005928Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +00005929 CXXConstructorDecl *Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005930 MultiExprArg ExprArgs,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005931 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00005932 unsigned ConstructKind,
5933 SourceRange ParenRange) {
Anders Carlsson250aada2009-08-16 05:13:48 +00005934 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +00005935
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005936 // C++0x [class.copy]p34:
5937 // When certain criteria are met, an implementation is allowed to
5938 // omit the copy/move construction of a class object, even if the
5939 // copy/move constructor and/or destructor for the object have
5940 // side effects. [...]
5941 // - when a temporary class object that has not been bound to a
5942 // reference (12.2) would be copied/moved to a class object
5943 // with the same cv-unqualified type, the copy/move operation
5944 // can be omitted by constructing the temporary object
5945 // directly into the target of the omitted copy/move
John McCall7a626f62010-09-15 10:14:12 +00005946 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregor3fb22ba2011-01-27 23:24:55 +00005947 Constructor->isCopyOrMoveConstructor() && ExprArgs.size() >= 1) {
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005948 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
John McCall7a626f62010-09-15 10:14:12 +00005949 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson250aada2009-08-16 05:13:48 +00005950 }
Mike Stump11289f42009-09-09 15:08:12 +00005951
5952 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005953 Elidable, move(ExprArgs), RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00005954 ConstructKind, ParenRange);
Anders Carlsson250aada2009-08-16 05:13:48 +00005955}
5956
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00005957/// BuildCXXConstructExpr - Creates a complete call to a constructor,
5958/// including handling of its default argument expressions.
John McCalldadc5752010-08-24 06:29:42 +00005959ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00005960Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
5961 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005962 MultiExprArg ExprArgs,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005963 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00005964 unsigned ConstructKind,
5965 SourceRange ParenRange) {
Anders Carlsson5995a3e2009-09-07 22:23:31 +00005966 unsigned NumExprs = ExprArgs.size();
5967 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump11289f42009-09-09 15:08:12 +00005968
Douglas Gregor27381f32009-11-23 12:27:39 +00005969 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor85dabae2009-12-16 01:38:02 +00005970 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005971 Constructor, Elidable, Exprs, NumExprs,
John McCallbfd822c2010-08-24 07:32:53 +00005972 RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00005973 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
5974 ParenRange));
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00005975}
5976
Mike Stump11289f42009-09-09 15:08:12 +00005977bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00005978 CXXConstructorDecl *Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00005979 MultiExprArg Exprs) {
Chandler Carruth01718152010-10-25 08:47:36 +00005980 // FIXME: Provide the correct paren SourceRange when available.
John McCalldadc5752010-08-24 06:29:42 +00005981 ExprResult TempResult =
Fariborz Jahanian57277c52009-10-28 18:41:06 +00005982 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Chandler Carruth01718152010-10-25 08:47:36 +00005983 move(Exprs), false, CXXConstructExpr::CK_Complete,
5984 SourceRange());
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00005985 if (TempResult.isInvalid())
5986 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005987
Anders Carlsson6eb55572009-08-25 05:12:04 +00005988 Expr *Temp = TempResult.takeAs<Expr>();
John McCallacf0ee52010-10-08 02:01:28 +00005989 CheckImplicitConversions(Temp, VD->getLocation());
Douglas Gregor77b50e12009-06-22 23:06:13 +00005990 MarkDeclarationReferenced(VD->getLocation(), Constructor);
John McCall5d413782010-12-06 08:20:24 +00005991 Temp = MaybeCreateExprWithCleanups(Temp);
Douglas Gregord5058122010-02-11 01:19:42 +00005992 VD->setInit(Temp);
Mike Stump11289f42009-09-09 15:08:12 +00005993
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00005994 return false;
Anders Carlssone6840d82009-04-16 23:50:50 +00005995}
5996
John McCall03c48482010-02-02 09:10:11 +00005997void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
5998 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Douglas Gregor422f1552010-02-25 18:11:54 +00005999 if (!ClassDecl->isInvalidDecl() && !VD->isInvalidDecl() &&
Douglas Gregor024d80e2010-05-22 17:12:29 +00006000 !ClassDecl->hasTrivialDestructor() && !ClassDecl->isDependentContext()) {
Douglas Gregore71edda2010-07-01 22:47:18 +00006001 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
John McCall6781b052010-02-02 08:45:54 +00006002 MarkDeclarationReferenced(VD->getLocation(), Destructor);
John McCall1064d7e2010-03-16 05:22:47 +00006003 CheckDestructorAccess(VD->getLocation(), Destructor,
Douglas Gregor89336232010-03-29 23:34:08 +00006004 PDiag(diag::err_access_dtor_var)
John McCall1064d7e2010-03-16 05:22:47 +00006005 << VD->getDeclName()
6006 << VD->getType());
John McCall47e40932010-08-01 20:20:59 +00006007
John McCall386dfc72010-09-18 05:25:11 +00006008 // TODO: this should be re-enabled for static locals by !CXAAtExit
6009 if (!VD->isInvalidDecl() && VD->hasGlobalStorage() && !VD->isStaticLocal())
John McCall47e40932010-08-01 20:20:59 +00006010 Diag(VD->getLocation(), diag::warn_global_destructor);
John McCall6781b052010-02-02 08:45:54 +00006011 }
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00006012}
6013
Mike Stump11289f42009-09-09 15:08:12 +00006014/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006015/// ActOnDeclarator, when a C++ direct initializer is present.
6016/// e.g: "int x(1);"
John McCall48871652010-08-21 09:40:31 +00006017void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl,
Chris Lattner83f095c2009-03-28 19:18:32 +00006018 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006019 MultiExprArg Exprs,
Richard Smith30482bc2011-02-20 03:19:35 +00006020 SourceLocation RParenLoc,
6021 bool TypeMayContainAuto) {
Daniel Dunbar2db411f2009-12-24 19:19:26 +00006022 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006023
6024 // If there is no declaration, there was an error parsing it. Just ignore
6025 // the initializer.
Chris Lattner83f095c2009-03-28 19:18:32 +00006026 if (RealDecl == 0)
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006027 return;
Mike Stump11289f42009-09-09 15:08:12 +00006028
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006029 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
6030 if (!VDecl) {
6031 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
6032 RealDecl->setInvalidDecl();
6033 return;
6034 }
6035
Richard Smith30482bc2011-02-20 03:19:35 +00006036 // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
6037 if (TypeMayContainAuto && VDecl->getType()->getContainedAutoType()) {
Richard Smith30482bc2011-02-20 03:19:35 +00006038 // FIXME: n3225 doesn't actually seem to indicate this is ill-formed
6039 if (Exprs.size() > 1) {
6040 Diag(Exprs.get()[1]->getSourceRange().getBegin(),
6041 diag::err_auto_var_init_multiple_expressions)
6042 << VDecl->getDeclName() << VDecl->getType()
6043 << VDecl->getSourceRange();
6044 RealDecl->setInvalidDecl();
6045 return;
6046 }
6047
6048 Expr *Init = Exprs.get()[0];
6049 QualType DeducedType;
6050 if (!DeduceAutoType(VDecl->getType(), Init, DeducedType)) {
6051 Diag(VDecl->getLocation(), diag::err_auto_var_deduction_failure)
6052 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
6053 << Init->getSourceRange();
6054 RealDecl->setInvalidDecl();
6055 return;
6056 }
6057 VDecl->setType(DeducedType);
6058
6059 // If this is a redeclaration, check that the type we just deduced matches
6060 // the previously declared type.
6061 if (VarDecl *Old = VDecl->getPreviousDeclaration())
6062 MergeVarDeclTypes(VDecl, Old);
6063 }
6064
Douglas Gregor402250f2009-08-26 21:14:46 +00006065 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00006066 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006067 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
6068 //
6069 // Clients that want to distinguish between the two forms, can check for
6070 // direct initializer using VarDecl::hasCXXDirectInitializer().
6071 // A major benefit is that clients that don't particularly care about which
6072 // exactly form was it (like the CodeGen) can handle both cases without
6073 // special case code.
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00006074
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006075 // C++ 8.5p11:
6076 // The form of initialization (using parentheses or '=') is generally
6077 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00006078 // class type.
6079
Douglas Gregor50dc2192010-02-11 22:55:30 +00006080 if (!VDecl->getType()->isDependentType() &&
6081 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor4044d992009-03-24 16:43:20 +00006082 diag::err_typecheck_decl_incomplete_type)) {
6083 VDecl->setInvalidDecl();
6084 return;
6085 }
6086
Douglas Gregorb6ea6082009-12-22 22:17:25 +00006087 // The variable can not have an abstract class type.
6088 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
6089 diag::err_abstract_type_in_decl,
6090 AbstractVariableType))
6091 VDecl->setInvalidDecl();
6092
Sebastian Redl5ca79842010-02-01 20:16:42 +00006093 const VarDecl *Def;
6094 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregorb6ea6082009-12-22 22:17:25 +00006095 Diag(VDecl->getLocation(), diag::err_redefinition)
6096 << VDecl->getDeclName();
6097 Diag(Def->getLocation(), diag::note_previous_definition);
6098 VDecl->setInvalidDecl();
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00006099 return;
6100 }
Douglas Gregor50dc2192010-02-11 22:55:30 +00006101
Douglas Gregorf0f83692010-08-24 05:27:49 +00006102 // C++ [class.static.data]p4
6103 // If a static data member is of const integral or const
6104 // enumeration type, its declaration in the class definition can
6105 // specify a constant-initializer which shall be an integral
6106 // constant expression (5.19). In that case, the member can appear
6107 // in integral constant expressions. The member shall still be
6108 // defined in a namespace scope if it is used in the program and the
6109 // namespace scope definition shall not contain an initializer.
6110 //
6111 // We already performed a redefinition check above, but for static
6112 // data members we also need to check whether there was an in-class
6113 // declaration with an initializer.
6114 const VarDecl* PrevInit = 0;
6115 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
6116 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
6117 Diag(PrevInit->getLocation(), diag::note_previous_definition);
6118 return;
6119 }
6120
Douglas Gregor71f39c92010-12-16 01:31:22 +00006121 bool IsDependent = false;
6122 for (unsigned I = 0, N = Exprs.size(); I != N; ++I) {
6123 if (DiagnoseUnexpandedParameterPack(Exprs.get()[I], UPPC_Expression)) {
6124 VDecl->setInvalidDecl();
6125 return;
6126 }
6127
6128 if (Exprs.get()[I]->isTypeDependent())
6129 IsDependent = true;
6130 }
6131
Douglas Gregor50dc2192010-02-11 22:55:30 +00006132 // If either the declaration has a dependent type or if any of the
6133 // expressions is type-dependent, we represent the initialization
6134 // via a ParenListExpr for later use during template instantiation.
Douglas Gregor71f39c92010-12-16 01:31:22 +00006135 if (VDecl->getType()->isDependentType() || IsDependent) {
Douglas Gregor50dc2192010-02-11 22:55:30 +00006136 // Let clients know that initialization was done with a direct initializer.
6137 VDecl->setCXXDirectInitializer(true);
6138
6139 // Store the initialization expressions as a ParenListExpr.
6140 unsigned NumExprs = Exprs.size();
6141 VDecl->setInit(new (Context) ParenListExpr(Context, LParenLoc,
6142 (Expr **)Exprs.release(),
6143 NumExprs, RParenLoc));
6144 return;
6145 }
Douglas Gregorb6ea6082009-12-22 22:17:25 +00006146
6147 // Capture the variable that is being initialized and the style of
6148 // initialization.
6149 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
6150
6151 // FIXME: Poor source location information.
6152 InitializationKind Kind
6153 = InitializationKind::CreateDirect(VDecl->getLocation(),
6154 LParenLoc, RParenLoc);
6155
6156 InitializationSequence InitSeq(*this, Entity, Kind,
John McCallb268a282010-08-23 23:25:46 +00006157 Exprs.get(), Exprs.size());
John McCalldadc5752010-08-24 06:29:42 +00006158 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
Douglas Gregorb6ea6082009-12-22 22:17:25 +00006159 if (Result.isInvalid()) {
6160 VDecl->setInvalidDecl();
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006161 return;
6162 }
John McCallacf0ee52010-10-08 02:01:28 +00006163
6164 CheckImplicitConversions(Result.get(), LParenLoc);
Douglas Gregorb6ea6082009-12-22 22:17:25 +00006165
Douglas Gregora40433a2010-12-07 00:41:46 +00006166 Result = MaybeCreateExprWithCleanups(Result);
Douglas Gregord5058122010-02-11 01:19:42 +00006167 VDecl->setInit(Result.takeAs<Expr>());
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006168 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00006169
John McCall8b7fd8f12011-01-19 11:48:09 +00006170 CheckCompleteVariableDeclaration(VDecl);
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006171}
Douglas Gregor8e1cf602008-10-29 00:13:59 +00006172
Douglas Gregor5d3507d2009-09-09 23:08:42 +00006173/// \brief Given a constructor and the set of arguments provided for the
6174/// constructor, convert the arguments and add any required default arguments
6175/// to form a proper call to this constructor.
6176///
6177/// \returns true if an error occurred, false otherwise.
6178bool
6179Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
6180 MultiExprArg ArgsPtr,
6181 SourceLocation Loc,
John McCall37ad5512010-08-23 06:44:23 +00006182 ASTOwningVector<Expr*> &ConvertedArgs) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +00006183 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
6184 unsigned NumArgs = ArgsPtr.size();
6185 Expr **Args = (Expr **)ArgsPtr.get();
6186
6187 const FunctionProtoType *Proto
6188 = Constructor->getType()->getAs<FunctionProtoType>();
6189 assert(Proto && "Constructor without a prototype?");
6190 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor5d3507d2009-09-09 23:08:42 +00006191
6192 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00006193 if (NumArgs < NumArgsInProto)
Douglas Gregor5d3507d2009-09-09 23:08:42 +00006194 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00006195 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +00006196 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00006197
6198 VariadicCallType CallType =
6199 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
6200 llvm::SmallVector<Expr *, 8> AllArgs;
6201 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
6202 Proto, 0, Args, NumArgs, AllArgs,
6203 CallType);
6204 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
6205 ConvertedArgs.push_back(AllArgs[i]);
6206 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00006207}
6208
Anders Carlssone363c8e2009-12-12 00:32:00 +00006209static inline bool
6210CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
6211 const FunctionDecl *FnDecl) {
Sebastian Redl50c68252010-08-31 00:36:30 +00006212 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlssone363c8e2009-12-12 00:32:00 +00006213 if (isa<NamespaceDecl>(DC)) {
6214 return SemaRef.Diag(FnDecl->getLocation(),
6215 diag::err_operator_new_delete_declared_in_namespace)
6216 << FnDecl->getDeclName();
6217 }
6218
6219 if (isa<TranslationUnitDecl>(DC) &&
John McCall8e7d6562010-08-26 03:08:43 +00006220 FnDecl->getStorageClass() == SC_Static) {
Anders Carlssone363c8e2009-12-12 00:32:00 +00006221 return SemaRef.Diag(FnDecl->getLocation(),
6222 diag::err_operator_new_delete_declared_static)
6223 << FnDecl->getDeclName();
6224 }
6225
Anders Carlsson60659a82009-12-12 02:43:16 +00006226 return false;
Anders Carlssone363c8e2009-12-12 00:32:00 +00006227}
6228
Anders Carlsson7e0b2072009-12-13 17:53:43 +00006229static inline bool
6230CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
6231 CanQualType ExpectedResultType,
6232 CanQualType ExpectedFirstParamType,
6233 unsigned DependentParamTypeDiag,
6234 unsigned InvalidParamTypeDiag) {
6235 QualType ResultType =
6236 FnDecl->getType()->getAs<FunctionType>()->getResultType();
6237
6238 // Check that the result type is not dependent.
6239 if (ResultType->isDependentType())
6240 return SemaRef.Diag(FnDecl->getLocation(),
6241 diag::err_operator_new_delete_dependent_result_type)
6242 << FnDecl->getDeclName() << ExpectedResultType;
6243
6244 // Check that the result type is what we expect.
6245 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
6246 return SemaRef.Diag(FnDecl->getLocation(),
6247 diag::err_operator_new_delete_invalid_result_type)
6248 << FnDecl->getDeclName() << ExpectedResultType;
6249
6250 // A function template must have at least 2 parameters.
6251 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
6252 return SemaRef.Diag(FnDecl->getLocation(),
6253 diag::err_operator_new_delete_template_too_few_parameters)
6254 << FnDecl->getDeclName();
6255
6256 // The function decl must have at least 1 parameter.
6257 if (FnDecl->getNumParams() == 0)
6258 return SemaRef.Diag(FnDecl->getLocation(),
6259 diag::err_operator_new_delete_too_few_parameters)
6260 << FnDecl->getDeclName();
6261
6262 // Check the the first parameter type is not dependent.
6263 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
6264 if (FirstParamType->isDependentType())
6265 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
6266 << FnDecl->getDeclName() << ExpectedFirstParamType;
6267
6268 // Check that the first parameter type is what we expect.
Douglas Gregor684d7bd2009-12-22 23:42:49 +00006269 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson7e0b2072009-12-13 17:53:43 +00006270 ExpectedFirstParamType)
6271 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
6272 << FnDecl->getDeclName() << ExpectedFirstParamType;
6273
6274 return false;
6275}
6276
Anders Carlsson12308f42009-12-11 23:23:22 +00006277static bool
Anders Carlsson7e0b2072009-12-13 17:53:43 +00006278CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlssone363c8e2009-12-12 00:32:00 +00006279 // C++ [basic.stc.dynamic.allocation]p1:
6280 // A program is ill-formed if an allocation function is declared in a
6281 // namespace scope other than global scope or declared static in global
6282 // scope.
6283 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
6284 return true;
Anders Carlsson7e0b2072009-12-13 17:53:43 +00006285
6286 CanQualType SizeTy =
6287 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
6288
6289 // C++ [basic.stc.dynamic.allocation]p1:
6290 // The return type shall be void*. The first parameter shall have type
6291 // std::size_t.
6292 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
6293 SizeTy,
6294 diag::err_operator_new_dependent_param_type,
6295 diag::err_operator_new_param_type))
6296 return true;
6297
6298 // C++ [basic.stc.dynamic.allocation]p1:
6299 // The first parameter shall not have an associated default argument.
6300 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlsson22f443f2009-12-12 00:26:23 +00006301 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson7e0b2072009-12-13 17:53:43 +00006302 diag::err_operator_new_default_arg)
6303 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
6304
6305 return false;
Anders Carlsson22f443f2009-12-12 00:26:23 +00006306}
6307
6308static bool
Anders Carlsson12308f42009-12-11 23:23:22 +00006309CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
6310 // C++ [basic.stc.dynamic.deallocation]p1:
6311 // A program is ill-formed if deallocation functions are declared in a
6312 // namespace scope other than global scope or declared static in global
6313 // scope.
Anders Carlssone363c8e2009-12-12 00:32:00 +00006314 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
6315 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00006316
6317 // C++ [basic.stc.dynamic.deallocation]p2:
6318 // Each deallocation function shall return void and its first parameter
6319 // shall be void*.
Anders Carlsson7e0b2072009-12-13 17:53:43 +00006320 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
6321 SemaRef.Context.VoidPtrTy,
6322 diag::err_operator_delete_dependent_param_type,
6323 diag::err_operator_delete_param_type))
6324 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00006325
Anders Carlsson12308f42009-12-11 23:23:22 +00006326 return false;
6327}
6328
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006329/// CheckOverloadedOperatorDeclaration - Check whether the declaration
6330/// of this overloaded operator is well-formed. If so, returns false;
6331/// otherwise, emits appropriate diagnostics and returns true.
6332bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +00006333 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006334 "Expected an overloaded operator declaration");
6335
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006336 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
6337
Mike Stump11289f42009-09-09 15:08:12 +00006338 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006339 // The allocation and deallocation functions, operator new,
6340 // operator new[], operator delete and operator delete[], are
6341 // described completely in 3.7.3. The attributes and restrictions
6342 // found in the rest of this subclause do not apply to them unless
6343 // explicitly stated in 3.7.3.
Anders Carlssonf1f46952009-12-11 23:31:21 +00006344 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson12308f42009-12-11 23:23:22 +00006345 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanian4e088942009-11-10 23:47:18 +00006346
Anders Carlsson22f443f2009-12-12 00:26:23 +00006347 if (Op == OO_New || Op == OO_Array_New)
6348 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006349
6350 // C++ [over.oper]p6:
6351 // An operator function shall either be a non-static member
6352 // function or be a non-member function and have at least one
6353 // parameter whose type is a class, a reference to a class, an
6354 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +00006355 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
6356 if (MethodDecl->isStatic())
6357 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00006358 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006359 } else {
6360 bool ClassOrEnumParam = false;
Douglas Gregord69246b2008-11-17 16:14:12 +00006361 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
6362 ParamEnd = FnDecl->param_end();
6363 Param != ParamEnd; ++Param) {
6364 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +00006365 if (ParamType->isDependentType() || ParamType->isRecordType() ||
6366 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006367 ClassOrEnumParam = true;
6368 break;
6369 }
6370 }
6371
Douglas Gregord69246b2008-11-17 16:14:12 +00006372 if (!ClassOrEnumParam)
6373 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00006374 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00006375 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006376 }
6377
6378 // C++ [over.oper]p8:
6379 // An operator function cannot have default arguments (8.3.6),
6380 // except where explicitly stated below.
6381 //
Mike Stump11289f42009-09-09 15:08:12 +00006382 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006383 // (C++ [over.call]p1).
6384 if (Op != OO_Call) {
6385 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
6386 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson7e0b2072009-12-13 17:53:43 +00006387 if ((*Param)->hasDefaultArg())
Mike Stump11289f42009-09-09 15:08:12 +00006388 return Diag((*Param)->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +00006389 diag::err_operator_overload_default_arg)
Anders Carlsson7e0b2072009-12-13 17:53:43 +00006390 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006391 }
6392 }
6393
Douglas Gregor6cf08062008-11-10 13:38:07 +00006394 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
6395 { false, false, false }
6396#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
6397 , { Unary, Binary, MemberOnly }
6398#include "clang/Basic/OperatorKinds.def"
6399 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006400
Douglas Gregor6cf08062008-11-10 13:38:07 +00006401 bool CanBeUnaryOperator = OperatorUses[Op][0];
6402 bool CanBeBinaryOperator = OperatorUses[Op][1];
6403 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006404
6405 // C++ [over.oper]p8:
6406 // [...] Operator functions cannot have more or fewer parameters
6407 // than the number required for the corresponding operator, as
6408 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +00006409 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +00006410 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006411 if (Op != OO_Call &&
6412 ((NumParams == 1 && !CanBeUnaryOperator) ||
6413 (NumParams == 2 && !CanBeBinaryOperator) ||
6414 (NumParams < 1) || (NumParams > 2))) {
6415 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00006416 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +00006417 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00006418 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +00006419 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00006420 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +00006421 } else {
Chris Lattner2b786902008-11-21 07:50:02 +00006422 assert(CanBeBinaryOperator &&
6423 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00006424 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +00006425 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006426
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00006427 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00006428 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006429 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00006430
Douglas Gregord69246b2008-11-17 16:14:12 +00006431 // Overloaded operators other than operator() cannot be variadic.
6432 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +00006433 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +00006434 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00006435 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006436 }
6437
6438 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +00006439 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
6440 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00006441 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00006442 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006443 }
6444
6445 // C++ [over.inc]p1:
6446 // The user-defined function called operator++ implements the
6447 // prefix and postfix ++ operator. If this function is a member
6448 // function with no parameters, or a non-member function with one
6449 // parameter of class or enumeration type, it defines the prefix
6450 // increment operator ++ for objects of that type. If the function
6451 // is a member function with one parameter (which shall be of type
6452 // int) or a non-member function with two parameters (the second
6453 // of which shall be of type int), it defines the postfix
6454 // increment operator ++ for objects of that type.
6455 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
6456 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
6457 bool ParamIsInt = false;
John McCall9dd450b2009-09-21 23:43:11 +00006458 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006459 ParamIsInt = BT->getKind() == BuiltinType::Int;
6460
Chris Lattner2b786902008-11-21 07:50:02 +00006461 if (!ParamIsInt)
6462 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00006463 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006464 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006465 }
6466
Douglas Gregord69246b2008-11-17 16:14:12 +00006467 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006468}
Chris Lattner3b024a32008-12-17 07:09:26 +00006469
Alexis Huntc88db062010-01-13 09:01:02 +00006470/// CheckLiteralOperatorDeclaration - Check whether the declaration
6471/// of this literal operator function is well-formed. If so, returns
6472/// false; otherwise, emits appropriate diagnostics and returns true.
6473bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
6474 DeclContext *DC = FnDecl->getDeclContext();
6475 Decl::Kind Kind = DC->getDeclKind();
6476 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
6477 Kind != Decl::LinkageSpec) {
6478 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
6479 << FnDecl->getDeclName();
6480 return true;
6481 }
6482
6483 bool Valid = false;
6484
Alexis Hunt7dd26172010-04-07 23:11:06 +00006485 // template <char...> type operator "" name() is the only valid template
6486 // signature, and the only valid signature with no parameters.
6487 if (FnDecl->param_size() == 0) {
6488 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
6489 // Must have only one template parameter
6490 TemplateParameterList *Params = TpDecl->getTemplateParameters();
6491 if (Params->size() == 1) {
6492 NonTypeTemplateParmDecl *PmDecl =
6493 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Alexis Huntc88db062010-01-13 09:01:02 +00006494
Alexis Hunt7dd26172010-04-07 23:11:06 +00006495 // The template parameter must be a char parameter pack.
Alexis Hunt7dd26172010-04-07 23:11:06 +00006496 if (PmDecl && PmDecl->isTemplateParameterPack() &&
6497 Context.hasSameType(PmDecl->getType(), Context.CharTy))
6498 Valid = true;
6499 }
6500 }
6501 } else {
Alexis Huntc88db062010-01-13 09:01:02 +00006502 // Check the first parameter
Alexis Hunt7dd26172010-04-07 23:11:06 +00006503 FunctionDecl::param_iterator Param = FnDecl->param_begin();
6504
Alexis Huntc88db062010-01-13 09:01:02 +00006505 QualType T = (*Param)->getType();
6506
Alexis Hunt079a6f72010-04-07 22:57:35 +00006507 // unsigned long long int, long double, and any character type are allowed
6508 // as the only parameters.
Alexis Huntc88db062010-01-13 09:01:02 +00006509 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
6510 Context.hasSameType(T, Context.LongDoubleTy) ||
6511 Context.hasSameType(T, Context.CharTy) ||
6512 Context.hasSameType(T, Context.WCharTy) ||
6513 Context.hasSameType(T, Context.Char16Ty) ||
6514 Context.hasSameType(T, Context.Char32Ty)) {
6515 if (++Param == FnDecl->param_end())
6516 Valid = true;
6517 goto FinishedParams;
6518 }
6519
Alexis Hunt079a6f72010-04-07 22:57:35 +00006520 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Alexis Huntc88db062010-01-13 09:01:02 +00006521 const PointerType *PT = T->getAs<PointerType>();
6522 if (!PT)
6523 goto FinishedParams;
6524 T = PT->getPointeeType();
6525 if (!T.isConstQualified())
6526 goto FinishedParams;
6527 T = T.getUnqualifiedType();
6528
6529 // Move on to the second parameter;
6530 ++Param;
6531
6532 // If there is no second parameter, the first must be a const char *
6533 if (Param == FnDecl->param_end()) {
6534 if (Context.hasSameType(T, Context.CharTy))
6535 Valid = true;
6536 goto FinishedParams;
6537 }
6538
6539 // const char *, const wchar_t*, const char16_t*, and const char32_t*
6540 // are allowed as the first parameter to a two-parameter function
6541 if (!(Context.hasSameType(T, Context.CharTy) ||
6542 Context.hasSameType(T, Context.WCharTy) ||
6543 Context.hasSameType(T, Context.Char16Ty) ||
6544 Context.hasSameType(T, Context.Char32Ty)))
6545 goto FinishedParams;
6546
6547 // The second and final parameter must be an std::size_t
6548 T = (*Param)->getType().getUnqualifiedType();
6549 if (Context.hasSameType(T, Context.getSizeType()) &&
6550 ++Param == FnDecl->param_end())
6551 Valid = true;
6552 }
6553
6554 // FIXME: This diagnostic is absolutely terrible.
6555FinishedParams:
6556 if (!Valid) {
6557 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
6558 << FnDecl->getDeclName();
6559 return true;
6560 }
6561
6562 return false;
6563}
6564
Douglas Gregor07665a62009-01-05 19:45:36 +00006565/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
6566/// linkage specification, including the language and (if present)
6567/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
6568/// the location of the language string literal, which is provided
6569/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
6570/// the '{' brace. Otherwise, this linkage specification does not
6571/// have any braces.
Chris Lattner8ea64422010-11-09 20:15:55 +00006572Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
6573 SourceLocation LangLoc,
6574 llvm::StringRef Lang,
6575 SourceLocation LBraceLoc) {
Chris Lattner438e5012008-12-17 07:13:27 +00006576 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerbebee842010-05-03 13:08:54 +00006577 if (Lang == "\"C\"")
Chris Lattner438e5012008-12-17 07:13:27 +00006578 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerbebee842010-05-03 13:08:54 +00006579 else if (Lang == "\"C++\"")
Chris Lattner438e5012008-12-17 07:13:27 +00006580 Language = LinkageSpecDecl::lang_cxx;
6581 else {
Douglas Gregor07665a62009-01-05 19:45:36 +00006582 Diag(LangLoc, diag::err_bad_language);
John McCall48871652010-08-21 09:40:31 +00006583 return 0;
Chris Lattner438e5012008-12-17 07:13:27 +00006584 }
Mike Stump11289f42009-09-09 15:08:12 +00006585
Chris Lattner438e5012008-12-17 07:13:27 +00006586 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +00006587
Douglas Gregor07665a62009-01-05 19:45:36 +00006588 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Abramo Bagnara66a35d72011-03-03 16:52:29 +00006589 LangLoc, Language);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006590 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +00006591 PushDeclContext(S, D);
John McCall48871652010-08-21 09:40:31 +00006592 return D;
Chris Lattner438e5012008-12-17 07:13:27 +00006593}
6594
Abramo Bagnaraed5b6892010-07-30 16:47:02 +00006595/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor07665a62009-01-05 19:45:36 +00006596/// the C++ linkage specification LinkageSpec. If RBraceLoc is
6597/// valid, it's the position of the closing '}' brace in a linkage
6598/// specification that uses braces.
John McCall48871652010-08-21 09:40:31 +00006599Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara4a8cda82011-03-03 14:52:38 +00006600 Decl *LinkageSpec,
6601 SourceLocation RBraceLoc) {
6602 if (LinkageSpec) {
6603 if (RBraceLoc.isValid()) {
6604 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
6605 LSDecl->setRBraceLoc(RBraceLoc);
6606 }
Douglas Gregor07665a62009-01-05 19:45:36 +00006607 PopDeclContext();
Abramo Bagnara4a8cda82011-03-03 14:52:38 +00006608 }
Douglas Gregor07665a62009-01-05 19:45:36 +00006609 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +00006610}
6611
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006612/// \brief Perform semantic analysis for the variable declaration that
6613/// occurs within a C++ catch clause, returning the newly-created
6614/// variable.
Abramo Bagnaradff19302011-03-08 08:55:46 +00006615VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCallbcd03502009-12-07 02:54:59 +00006616 TypeSourceInfo *TInfo,
Abramo Bagnaradff19302011-03-08 08:55:46 +00006617 SourceLocation StartLoc,
6618 SourceLocation Loc,
6619 IdentifierInfo *Name) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006620 bool Invalid = false;
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006621 QualType ExDeclType = TInfo->getType();
6622
Sebastian Redl54c04d42008-12-22 19:15:10 +00006623 // Arrays and functions decay.
6624 if (ExDeclType->isArrayType())
6625 ExDeclType = Context.getArrayDecayedType(ExDeclType);
6626 else if (ExDeclType->isFunctionType())
6627 ExDeclType = Context.getPointerType(ExDeclType);
6628
6629 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
6630 // The exception-declaration shall not denote a pointer or reference to an
6631 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +00006632 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +00006633 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006634 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlb28b4072009-03-22 23:49:27 +00006635 Invalid = true;
6636 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006637
Douglas Gregor104ee002010-03-08 01:47:36 +00006638 // GCC allows catching pointers and references to incomplete types
6639 // as an extension; so do we, but we warn by default.
6640
Sebastian Redl54c04d42008-12-22 19:15:10 +00006641 QualType BaseType = ExDeclType;
6642 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +00006643 unsigned DK = diag::err_catch_incomplete;
Douglas Gregor104ee002010-03-08 01:47:36 +00006644 bool IncompleteCatchIsInvalid = true;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006645 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00006646 BaseType = Ptr->getPointeeType();
6647 Mode = 1;
Douglas Gregor104ee002010-03-08 01:47:36 +00006648 DK = diag::ext_catch_incomplete_ptr;
6649 IncompleteCatchIsInvalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00006650 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00006651 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +00006652 BaseType = Ref->getPointeeType();
6653 Mode = 2;
Douglas Gregor104ee002010-03-08 01:47:36 +00006654 DK = diag::ext_catch_incomplete_ref;
6655 IncompleteCatchIsInvalid = false;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006656 }
Sebastian Redlb28b4072009-03-22 23:49:27 +00006657 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor104ee002010-03-08 01:47:36 +00006658 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
6659 IncompleteCatchIsInvalid)
Sebastian Redl54c04d42008-12-22 19:15:10 +00006660 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006661
Mike Stump11289f42009-09-09 15:08:12 +00006662 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006663 RequireNonAbstractType(Loc, ExDeclType,
6664 diag::err_abstract_type_in_decl,
6665 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +00006666 Invalid = true;
6667
John McCall2ca705e2010-07-24 00:37:23 +00006668 // Only the non-fragile NeXT runtime currently supports C++ catches
6669 // of ObjC types, and no runtime supports catching ObjC types by value.
6670 if (!Invalid && getLangOptions().ObjC1) {
6671 QualType T = ExDeclType;
6672 if (const ReferenceType *RT = T->getAs<ReferenceType>())
6673 T = RT->getPointeeType();
6674
6675 if (T->isObjCObjectType()) {
6676 Diag(Loc, diag::err_objc_object_catch);
6677 Invalid = true;
6678 } else if (T->isObjCObjectPointerType()) {
6679 if (!getLangOptions().NeXTRuntime) {
6680 Diag(Loc, diag::err_objc_pointer_cxx_catch_gnu);
6681 Invalid = true;
6682 } else if (!getLangOptions().ObjCNonFragileABI) {
6683 Diag(Loc, diag::err_objc_pointer_cxx_catch_fragile);
6684 Invalid = true;
6685 }
6686 }
6687 }
6688
Abramo Bagnaradff19302011-03-08 08:55:46 +00006689 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
6690 ExDeclType, TInfo, SC_None, SC_None);
Douglas Gregor3f324d562010-05-03 18:51:14 +00006691 ExDecl->setExceptionVariable(true);
6692
Douglas Gregor6de584c2010-03-05 23:38:39 +00006693 if (!Invalid) {
John McCall1bf58462011-02-16 08:02:54 +00006694 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
Douglas Gregor6de584c2010-03-05 23:38:39 +00006695 // C++ [except.handle]p16:
6696 // The object declared in an exception-declaration or, if the
6697 // exception-declaration does not specify a name, a temporary (12.2) is
6698 // copy-initialized (8.5) from the exception object. [...]
6699 // The object is destroyed when the handler exits, after the destruction
6700 // of any automatic objects initialized within the handler.
6701 //
6702 // We just pretend to initialize the object with itself, then make sure
6703 // it can be destroyed later.
John McCall1bf58462011-02-16 08:02:54 +00006704 QualType initType = ExDeclType;
6705
6706 InitializedEntity entity =
6707 InitializedEntity::InitializeVariable(ExDecl);
6708 InitializationKind initKind =
6709 InitializationKind::CreateCopy(Loc, SourceLocation());
6710
6711 Expr *opaqueValue =
6712 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
6713 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
6714 ExprResult result = sequence.Perform(*this, entity, initKind,
6715 MultiExprArg(&opaqueValue, 1));
6716 if (result.isInvalid())
Douglas Gregor6de584c2010-03-05 23:38:39 +00006717 Invalid = true;
John McCall1bf58462011-02-16 08:02:54 +00006718 else {
6719 // If the constructor used was non-trivial, set this as the
6720 // "initializer".
6721 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
6722 if (!construct->getConstructor()->isTrivial()) {
6723 Expr *init = MaybeCreateExprWithCleanups(construct);
6724 ExDecl->setInit(init);
6725 }
6726
6727 // And make sure it's destructable.
6728 FinalizeVarWithDestructor(ExDecl, recordType);
6729 }
Douglas Gregor6de584c2010-03-05 23:38:39 +00006730 }
6731 }
6732
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006733 if (Invalid)
6734 ExDecl->setInvalidDecl();
6735
6736 return ExDecl;
6737}
6738
6739/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
6740/// handler.
John McCall48871652010-08-21 09:40:31 +00006741Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCall8cb7bdf2010-06-04 23:28:52 +00006742 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregor72772f62010-12-16 17:48:04 +00006743 bool Invalid = D.isInvalidType();
6744
6745 // Check for unexpanded parameter packs.
6746 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
6747 UPPC_ExceptionType)) {
6748 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
6749 D.getIdentifierLoc());
6750 Invalid = true;
6751 }
6752
Sebastian Redl54c04d42008-12-22 19:15:10 +00006753 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +00006754 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +00006755 LookupOrdinaryName,
6756 ForRedeclaration)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00006757 // The scope should be freshly made just for us. There is just no way
6758 // it contains any previous declaration.
John McCall48871652010-08-21 09:40:31 +00006759 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl54c04d42008-12-22 19:15:10 +00006760 if (PrevDecl->isTemplateParameter()) {
6761 // Maybe we will complain about the shadowed template parameter.
6762 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00006763 }
6764 }
6765
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00006766 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00006767 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
6768 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00006769 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006770 }
6771
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006772 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Abramo Bagnaradff19302011-03-08 08:55:46 +00006773 D.getSourceRange().getBegin(),
6774 D.getIdentifierLoc(),
6775 D.getIdentifier());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00006776 if (Invalid)
6777 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00006778
Sebastian Redl54c04d42008-12-22 19:15:10 +00006779 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +00006780 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006781 PushOnScopeChains(ExDecl, S);
6782 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006783 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00006784
Douglas Gregor758a8692009-06-17 21:51:59 +00006785 ProcessDeclAttributes(S, ExDecl, D);
John McCall48871652010-08-21 09:40:31 +00006786 return ExDecl;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006787}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006788
John McCall48871652010-08-21 09:40:31 +00006789Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
John McCallb268a282010-08-23 23:25:46 +00006790 Expr *AssertExpr,
6791 Expr *AssertMessageExpr_) {
6792 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006793
Anders Carlsson54b26982009-03-14 00:33:21 +00006794 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
6795 llvm::APSInt Value(32);
6796 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
6797 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
6798 AssertExpr->getSourceRange();
John McCall48871652010-08-21 09:40:31 +00006799 return 0;
Anders Carlsson54b26982009-03-14 00:33:21 +00006800 }
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006801
Anders Carlsson54b26982009-03-14 00:33:21 +00006802 if (Value == 0) {
Mike Stump11289f42009-09-09 15:08:12 +00006803 Diag(AssertLoc, diag::err_static_assert_failed)
Benjamin Kramerb11118b2009-12-11 13:33:18 +00006804 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlsson54b26982009-03-14 00:33:21 +00006805 }
6806 }
Mike Stump11289f42009-09-09 15:08:12 +00006807
Douglas Gregoref68fee2010-12-15 23:55:21 +00006808 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
6809 return 0;
6810
Mike Stump11289f42009-09-09 15:08:12 +00006811 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006812 AssertExpr, AssertMessage);
Mike Stump11289f42009-09-09 15:08:12 +00006813
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006814 CurContext->addDecl(Decl);
John McCall48871652010-08-21 09:40:31 +00006815 return Decl;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006816}
Sebastian Redlf769df52009-03-24 22:27:57 +00006817
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006818/// \brief Perform semantic analysis of the given friend type declaration.
6819///
6820/// \returns A friend declaration that.
6821FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc,
6822 TypeSourceInfo *TSInfo) {
6823 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
6824
6825 QualType T = TSInfo->getType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006826 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006827
Douglas Gregor3b4abb62010-04-07 17:57:12 +00006828 if (!getLangOptions().CPlusPlus0x) {
6829 // C++03 [class.friend]p2:
6830 // An elaborated-type-specifier shall be used in a friend declaration
6831 // for a class.*
6832 //
6833 // * The class-key of the elaborated-type-specifier is required.
6834 if (!ActiveTemplateInstantiations.empty()) {
6835 // Do not complain about the form of friend template types during
6836 // template instantiation; we will already have complained when the
6837 // template was declared.
6838 } else if (!T->isElaboratedTypeSpecifier()) {
6839 // If we evaluated the type to a record type, suggest putting
6840 // a tag in front.
6841 if (const RecordType *RT = T->getAs<RecordType>()) {
6842 RecordDecl *RD = RT->getDecl();
6843
6844 std::string InsertionText = std::string(" ") + RD->getKindName();
6845
6846 Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type)
6847 << (unsigned) RD->getTagKind()
6848 << T
6849 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
6850 InsertionText);
6851 } else {
6852 Diag(FriendLoc, diag::ext_nonclass_type_friend)
6853 << T
6854 << SourceRange(FriendLoc, TypeRange.getEnd());
6855 }
6856 } else if (T->getAs<EnumType>()) {
6857 Diag(FriendLoc, diag::ext_enum_friend)
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006858 << T
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006859 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006860 }
6861 }
6862
Douglas Gregor3b4abb62010-04-07 17:57:12 +00006863 // C++0x [class.friend]p3:
6864 // If the type specifier in a friend declaration designates a (possibly
6865 // cv-qualified) class type, that class is declared as a friend; otherwise,
6866 // the friend declaration is ignored.
6867
6868 // FIXME: C++0x has some syntactic restrictions on friend type declarations
6869 // in [class.friend]p3 that we do not implement.
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006870
6871 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc);
6872}
6873
John McCallace48cd2010-10-19 01:40:49 +00006874/// Handle a friend tag declaration where the scope specifier was
6875/// templated.
6876Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
6877 unsigned TagSpec, SourceLocation TagLoc,
6878 CXXScopeSpec &SS,
6879 IdentifierInfo *Name, SourceLocation NameLoc,
6880 AttributeList *Attr,
6881 MultiTemplateParamsArg TempParamLists) {
6882 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
6883
6884 bool isExplicitSpecialization = false;
6885 unsigned NumMatchedTemplateParamLists = TempParamLists.size();
6886 bool Invalid = false;
6887
6888 if (TemplateParameterList *TemplateParams
6889 = MatchTemplateParametersToScopeSpecifier(TagLoc, SS,
6890 TempParamLists.get(),
6891 TempParamLists.size(),
6892 /*friend*/ true,
6893 isExplicitSpecialization,
6894 Invalid)) {
6895 --NumMatchedTemplateParamLists;
6896
6897 if (TemplateParams->size() > 0) {
6898 // This is a declaration of a class template.
6899 if (Invalid)
6900 return 0;
6901
6902 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
6903 SS, Name, NameLoc, Attr,
6904 TemplateParams, AS_public).take();
6905 } else {
6906 // The "template<>" header is extraneous.
6907 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
6908 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
6909 isExplicitSpecialization = true;
6910 }
6911 }
6912
6913 if (Invalid) return 0;
6914
6915 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
6916
6917 bool isAllExplicitSpecializations = true;
6918 for (unsigned I = 0; I != NumMatchedTemplateParamLists; ++I) {
6919 if (TempParamLists.get()[I]->size()) {
6920 isAllExplicitSpecializations = false;
6921 break;
6922 }
6923 }
6924
6925 // FIXME: don't ignore attributes.
6926
6927 // If it's explicit specializations all the way down, just forget
6928 // about the template header and build an appropriate non-templated
6929 // friend. TODO: for source fidelity, remember the headers.
6930 if (isAllExplicitSpecializations) {
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00006931 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallace48cd2010-10-19 01:40:49 +00006932 ElaboratedTypeKeyword Keyword
6933 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00006934 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00006935 *Name, NameLoc);
John McCallace48cd2010-10-19 01:40:49 +00006936 if (T.isNull())
6937 return 0;
6938
6939 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
6940 if (isa<DependentNameType>(T)) {
6941 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
6942 TL.setKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00006943 TL.setQualifierLoc(QualifierLoc);
John McCallace48cd2010-10-19 01:40:49 +00006944 TL.setNameLoc(NameLoc);
6945 } else {
6946 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
6947 TL.setKeywordLoc(TagLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00006948 TL.setQualifierLoc(QualifierLoc);
John McCallace48cd2010-10-19 01:40:49 +00006949 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
6950 }
6951
6952 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
6953 TSI, FriendLoc);
6954 Friend->setAccess(AS_public);
6955 CurContext->addDecl(Friend);
6956 return Friend;
6957 }
6958
6959 // Handle the case of a templated-scope friend class. e.g.
6960 // template <class T> class A<T>::B;
6961 // FIXME: we don't support these right now.
6962 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
6963 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
6964 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
6965 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
6966 TL.setKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00006967 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCallace48cd2010-10-19 01:40:49 +00006968 TL.setNameLoc(NameLoc);
6969
6970 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
6971 TSI, FriendLoc);
6972 Friend->setAccess(AS_public);
6973 Friend->setUnsupportedFriend(true);
6974 CurContext->addDecl(Friend);
6975 return Friend;
6976}
6977
6978
John McCall11083da2009-09-16 22:47:08 +00006979/// Handle a friend type declaration. This works in tandem with
6980/// ActOnTag.
6981///
6982/// Notes on friend class templates:
6983///
6984/// We generally treat friend class declarations as if they were
6985/// declaring a class. So, for example, the elaborated type specifier
6986/// in a friend declaration is required to obey the restrictions of a
6987/// class-head (i.e. no typedefs in the scope chain), template
6988/// parameters are required to match up with simple template-ids, &c.
6989/// However, unlike when declaring a template specialization, it's
6990/// okay to refer to a template specialization without an empty
6991/// template parameter declaration, e.g.
6992/// friend class A<T>::B<unsigned>;
6993/// We permit this as a special case; if there are any template
6994/// parameters present at all, require proper matching, i.e.
6995/// template <> template <class T> friend class A<int>::B;
John McCall48871652010-08-21 09:40:31 +00006996Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallc9739e32010-10-16 07:23:36 +00006997 MultiTemplateParamsArg TempParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00006998 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall07e91c02009-08-06 02:15:43 +00006999
7000 assert(DS.isFriendSpecified());
7001 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
7002
John McCall11083da2009-09-16 22:47:08 +00007003 // Try to convert the decl specifier to a type. This works for
7004 // friend templates because ActOnTag never produces a ClassTemplateDecl
7005 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +00007006 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +00007007 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
7008 QualType T = TSI->getType();
Chris Lattner1fb66f42009-10-25 17:47:27 +00007009 if (TheDeclarator.isInvalidType())
John McCall48871652010-08-21 09:40:31 +00007010 return 0;
John McCall07e91c02009-08-06 02:15:43 +00007011
Douglas Gregor6c110f32010-12-16 01:14:37 +00007012 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
7013 return 0;
7014
John McCall11083da2009-09-16 22:47:08 +00007015 // This is definitely an error in C++98. It's probably meant to
7016 // be forbidden in C++0x, too, but the specification is just
7017 // poorly written.
7018 //
7019 // The problem is with declarations like the following:
7020 // template <T> friend A<T>::foo;
7021 // where deciding whether a class C is a friend or not now hinges
7022 // on whether there exists an instantiation of A that causes
7023 // 'foo' to equal C. There are restrictions on class-heads
7024 // (which we declare (by fiat) elaborated friend declarations to
7025 // be) that makes this tractable.
7026 //
7027 // FIXME: handle "template <> friend class A<T>;", which
7028 // is possibly well-formed? Who even knows?
Douglas Gregore677daf2010-03-31 22:19:08 +00007029 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCall11083da2009-09-16 22:47:08 +00007030 Diag(Loc, diag::err_tagless_friend_type_template)
7031 << DS.getSourceRange();
John McCall48871652010-08-21 09:40:31 +00007032 return 0;
John McCall11083da2009-09-16 22:47:08 +00007033 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +00007034
John McCallaa74a0c2009-08-28 07:59:38 +00007035 // C++98 [class.friend]p1: A friend of a class is a function
7036 // or class that is not a member of the class . . .
John McCall463e10c2009-12-22 00:59:39 +00007037 // This is fixed in DR77, which just barely didn't make the C++03
7038 // deadline. It's also a very silly restriction that seriously
7039 // affects inner classes and which nobody else seems to implement;
7040 // thus we never diagnose it, not even in -pedantic.
John McCall15ad0962010-03-25 18:04:51 +00007041 //
7042 // But note that we could warn about it: it's always useless to
7043 // friend one of your own members (it's not, however, worthless to
7044 // friend a member of an arbitrary specialization of your template).
John McCallaa74a0c2009-08-28 07:59:38 +00007045
John McCall11083da2009-09-16 22:47:08 +00007046 Decl *D;
Douglas Gregorafb9bc12010-04-07 16:53:43 +00007047 if (unsigned NumTempParamLists = TempParams.size())
John McCall11083da2009-09-16 22:47:08 +00007048 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +00007049 NumTempParamLists,
John McCallc9739e32010-10-16 07:23:36 +00007050 TempParams.release(),
John McCall15ad0962010-03-25 18:04:51 +00007051 TSI,
John McCall11083da2009-09-16 22:47:08 +00007052 DS.getFriendSpecLoc());
7053 else
Douglas Gregorafb9bc12010-04-07 16:53:43 +00007054 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
7055
7056 if (!D)
John McCall48871652010-08-21 09:40:31 +00007057 return 0;
Douglas Gregorafb9bc12010-04-07 16:53:43 +00007058
John McCall11083da2009-09-16 22:47:08 +00007059 D->setAccess(AS_public);
7060 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +00007061
John McCall48871652010-08-21 09:40:31 +00007062 return D;
John McCallaa74a0c2009-08-28 07:59:38 +00007063}
7064
John McCallde3fd222010-10-12 23:13:28 +00007065Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, bool IsDefinition,
7066 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00007067 const DeclSpec &DS = D.getDeclSpec();
7068
7069 assert(DS.isFriendSpecified());
7070 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
7071
7072 SourceLocation Loc = D.getIdentifierLoc();
John McCall8cb7bdf2010-06-04 23:28:52 +00007073 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
7074 QualType T = TInfo->getType();
John McCall07e91c02009-08-06 02:15:43 +00007075
7076 // C++ [class.friend]p1
7077 // A friend of a class is a function or class....
7078 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +00007079 // It *doesn't* see through dependent types, which is correct
7080 // according to [temp.arg.type]p3:
7081 // If a declaration acquires a function type through a
7082 // type dependent on a template-parameter and this causes
7083 // a declaration that does not use the syntactic form of a
7084 // function declarator to have a function type, the program
7085 // is ill-formed.
John McCall07e91c02009-08-06 02:15:43 +00007086 if (!T->isFunctionType()) {
7087 Diag(Loc, diag::err_unexpected_friend);
7088
7089 // It might be worthwhile to try to recover by creating an
7090 // appropriate declaration.
John McCall48871652010-08-21 09:40:31 +00007091 return 0;
John McCall07e91c02009-08-06 02:15:43 +00007092 }
7093
7094 // C++ [namespace.memdef]p3
7095 // - If a friend declaration in a non-local class first declares a
7096 // class or function, the friend class or function is a member
7097 // of the innermost enclosing namespace.
7098 // - The name of the friend is not found by simple name lookup
7099 // until a matching declaration is provided in that namespace
7100 // scope (either before or after the class declaration granting
7101 // friendship).
7102 // - If a friend function is called, its name may be found by the
7103 // name lookup that considers functions from namespaces and
7104 // classes associated with the types of the function arguments.
7105 // - When looking for a prior declaration of a class or a function
7106 // declared as a friend, scopes outside the innermost enclosing
7107 // namespace scope are not considered.
7108
John McCallde3fd222010-10-12 23:13:28 +00007109 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007110 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
7111 DeclarationName Name = NameInfo.getName();
John McCall07e91c02009-08-06 02:15:43 +00007112 assert(Name);
7113
Douglas Gregor6c110f32010-12-16 01:14:37 +00007114 // Check for unexpanded parameter packs.
7115 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
7116 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
7117 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
7118 return 0;
7119
John McCall07e91c02009-08-06 02:15:43 +00007120 // The context we found the declaration in, or in which we should
7121 // create the declaration.
7122 DeclContext *DC;
John McCallccbc0322010-10-13 06:22:15 +00007123 Scope *DCScope = S;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007124 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +00007125 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +00007126
John McCallde3fd222010-10-12 23:13:28 +00007127 // FIXME: there are different rules in local classes
John McCall07e91c02009-08-06 02:15:43 +00007128
John McCallde3fd222010-10-12 23:13:28 +00007129 // There are four cases here.
7130 // - There's no scope specifier, in which case we just go to the
John McCallf7cfb222010-10-13 05:45:15 +00007131 // appropriate scope and look for a function or function template
John McCallde3fd222010-10-12 23:13:28 +00007132 // there as appropriate.
7133 // Recover from invalid scope qualifiers as if they just weren't there.
7134 if (SS.isInvalid() || !SS.isSet()) {
John McCallf7cfb222010-10-13 05:45:15 +00007135 // C++0x [namespace.memdef]p3:
7136 // If the name in a friend declaration is neither qualified nor
7137 // a template-id and the declaration is a function or an
7138 // elaborated-type-specifier, the lookup to determine whether
7139 // the entity has been previously declared shall not consider
7140 // any scopes outside the innermost enclosing namespace.
7141 // C++0x [class.friend]p11:
7142 // If a friend declaration appears in a local class and the name
7143 // specified is an unqualified name, a prior declaration is
7144 // looked up without considering scopes that are outside the
7145 // innermost enclosing non-class scope. For a friend function
7146 // declaration, if there is no prior declaration, the program is
7147 // ill-formed.
7148 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCallf4776592010-10-14 22:22:28 +00007149 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall07e91c02009-08-06 02:15:43 +00007150
John McCallf7cfb222010-10-13 05:45:15 +00007151 // Find the appropriate context according to the above.
John McCall07e91c02009-08-06 02:15:43 +00007152 DC = CurContext;
7153 while (true) {
7154 // Skip class contexts. If someone can cite chapter and verse
7155 // for this behavior, that would be nice --- it's what GCC and
7156 // EDG do, and it seems like a reasonable intent, but the spec
7157 // really only says that checks for unqualified existing
7158 // declarations should stop at the nearest enclosing namespace,
7159 // not that they should only consider the nearest enclosing
7160 // namespace.
Douglas Gregora29a3ff2009-09-28 00:08:27 +00007161 while (DC->isRecord())
7162 DC = DC->getParent();
John McCall07e91c02009-08-06 02:15:43 +00007163
John McCall1f82f242009-11-18 22:49:29 +00007164 LookupQualifiedName(Previous, DC);
John McCall07e91c02009-08-06 02:15:43 +00007165
7166 // TODO: decide what we think about using declarations.
John McCallf7cfb222010-10-13 05:45:15 +00007167 if (isLocal || !Previous.empty())
John McCall07e91c02009-08-06 02:15:43 +00007168 break;
John McCallf7cfb222010-10-13 05:45:15 +00007169
John McCallf4776592010-10-14 22:22:28 +00007170 if (isTemplateId) {
7171 if (isa<TranslationUnitDecl>(DC)) break;
7172 } else {
7173 if (DC->isFileContext()) break;
7174 }
John McCall07e91c02009-08-06 02:15:43 +00007175 DC = DC->getParent();
7176 }
7177
7178 // C++ [class.friend]p1: A friend of a class is a function or
7179 // class that is not a member of the class . . .
John McCall93343b92009-08-06 20:49:32 +00007180 // C++0x changes this for both friend types and functions.
7181 // Most C++ 98 compilers do seem to give an error here, so
7182 // we do, too.
John McCall1f82f242009-11-18 22:49:29 +00007183 if (!Previous.empty() && DC->Equals(CurContext)
7184 && !getLangOptions().CPlusPlus0x)
John McCall07e91c02009-08-06 02:15:43 +00007185 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
John McCallde3fd222010-10-12 23:13:28 +00007186
John McCallccbc0322010-10-13 06:22:15 +00007187 DCScope = getScopeForDeclContext(S, DC);
John McCallf7cfb222010-10-13 05:45:15 +00007188
John McCallde3fd222010-10-12 23:13:28 +00007189 // - There's a non-dependent scope specifier, in which case we
7190 // compute it and do a previous lookup there for a function
7191 // or function template.
7192 } else if (!SS.getScopeRep()->isDependent()) {
7193 DC = computeDeclContext(SS);
7194 if (!DC) return 0;
7195
7196 if (RequireCompleteDeclContext(SS, DC)) return 0;
7197
7198 LookupQualifiedName(Previous, DC);
7199
7200 // Ignore things found implicitly in the wrong scope.
7201 // TODO: better diagnostics for this case. Suggesting the right
7202 // qualified scope would be nice...
7203 LookupResult::Filter F = Previous.makeFilter();
7204 while (F.hasNext()) {
7205 NamedDecl *D = F.next();
7206 if (!DC->InEnclosingNamespaceSetOf(
7207 D->getDeclContext()->getRedeclContext()))
7208 F.erase();
7209 }
7210 F.done();
7211
7212 if (Previous.empty()) {
7213 D.setInvalidType();
7214 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
7215 return 0;
7216 }
7217
7218 // C++ [class.friend]p1: A friend of a class is a function or
7219 // class that is not a member of the class . . .
7220 if (DC->Equals(CurContext))
7221 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
7222
7223 // - There's a scope specifier that does not match any template
7224 // parameter lists, in which case we use some arbitrary context,
7225 // create a method or method template, and wait for instantiation.
7226 // - There's a scope specifier that does match some template
7227 // parameter lists, which we don't handle right now.
7228 } else {
7229 DC = CurContext;
7230 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall07e91c02009-08-06 02:15:43 +00007231 }
7232
John McCallf7cfb222010-10-13 05:45:15 +00007233 if (!DC->isRecord()) {
John McCall07e91c02009-08-06 02:15:43 +00007234 // This implies that it has to be an operator or function.
Douglas Gregor7861a802009-11-03 01:35:08 +00007235 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
7236 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
7237 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall07e91c02009-08-06 02:15:43 +00007238 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor7861a802009-11-03 01:35:08 +00007239 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
7240 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall48871652010-08-21 09:40:31 +00007241 return 0;
John McCall07e91c02009-08-06 02:15:43 +00007242 }
John McCall07e91c02009-08-06 02:15:43 +00007243 }
7244
Douglas Gregora29a3ff2009-09-28 00:08:27 +00007245 bool Redeclaration = false;
John McCallccbc0322010-10-13 06:22:15 +00007246 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, T, TInfo, Previous,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00007247 move(TemplateParams),
John McCalld1e9d832009-08-11 06:59:38 +00007248 IsDefinition,
7249 Redeclaration);
John McCall48871652010-08-21 09:40:31 +00007250 if (!ND) return 0;
John McCall759e32b2009-08-31 22:39:49 +00007251
Douglas Gregora29a3ff2009-09-28 00:08:27 +00007252 assert(ND->getDeclContext() == DC);
7253 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +00007254
John McCall759e32b2009-08-31 22:39:49 +00007255 // Add the function declaration to the appropriate lookup tables,
7256 // adjusting the redeclarations list as necessary. We don't
7257 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +00007258 //
John McCall759e32b2009-08-31 22:39:49 +00007259 // Also update the scope-based lookup if the target context's
7260 // lookup context is in lexical scope.
7261 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00007262 DC = DC->getRedeclContext();
Douglas Gregora29a3ff2009-09-28 00:08:27 +00007263 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00007264 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +00007265 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00007266 }
John McCallaa74a0c2009-08-28 07:59:38 +00007267
7268 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +00007269 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +00007270 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +00007271 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +00007272 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +00007273
John McCallde3fd222010-10-12 23:13:28 +00007274 if (ND->isInvalidDecl())
7275 FrD->setInvalidDecl();
John McCall2c2eb122010-10-16 06:59:13 +00007276 else {
7277 FunctionDecl *FD;
7278 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
7279 FD = FTD->getTemplatedDecl();
7280 else
7281 FD = cast<FunctionDecl>(ND);
7282
7283 // Mark templated-scope function declarations as unsupported.
7284 if (FD->getNumTemplateParameterLists())
7285 FrD->setUnsupportedFriend(true);
7286 }
John McCallde3fd222010-10-12 23:13:28 +00007287
John McCall48871652010-08-21 09:40:31 +00007288 return ND;
Anders Carlsson38811702009-05-11 22:55:49 +00007289}
7290
John McCall48871652010-08-21 09:40:31 +00007291void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
7292 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +00007293
Sebastian Redlf769df52009-03-24 22:27:57 +00007294 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
7295 if (!Fn) {
7296 Diag(DelLoc, diag::err_deleted_non_function);
7297 return;
7298 }
7299 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
7300 Diag(DelLoc, diag::err_deleted_decl_not_first);
7301 Diag(Prev->getLocation(), diag::note_previous_declaration);
7302 // If the declaration wasn't the first, we delete the function anyway for
7303 // recovery.
7304 }
7305 Fn->setDeleted();
7306}
Sebastian Redl4c018662009-04-27 21:33:24 +00007307
7308static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall8322c3a2011-02-13 04:07:26 +00007309 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl4c018662009-04-27 21:33:24 +00007310 Stmt *SubStmt = *CI;
7311 if (!SubStmt)
7312 continue;
7313 if (isa<ReturnStmt>(SubStmt))
7314 Self.Diag(SubStmt->getSourceRange().getBegin(),
7315 diag::err_return_in_constructor_handler);
7316 if (!isa<Expr>(SubStmt))
7317 SearchForReturnInStmt(Self, SubStmt);
7318 }
7319}
7320
7321void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
7322 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
7323 CXXCatchStmt *Handler = TryBlock->getHandler(I);
7324 SearchForReturnInStmt(*this, Handler);
7325 }
7326}
Anders Carlssonf2a2e332009-05-14 01:09:04 +00007327
Mike Stump11289f42009-09-09 15:08:12 +00007328bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +00007329 const CXXMethodDecl *Old) {
John McCall9dd450b2009-09-21 23:43:11 +00007330 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
7331 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +00007332
Chandler Carruth284bb2e2010-02-15 11:53:20 +00007333 if (Context.hasSameType(NewTy, OldTy) ||
7334 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssonf2a2e332009-05-14 01:09:04 +00007335 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007336
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007337 // Check if the return types are covariant
7338 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +00007339
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007340 /// Both types must be pointers or references to classes.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00007341 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
7342 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007343 NewClassTy = NewPT->getPointeeType();
7344 OldClassTy = OldPT->getPointeeType();
7345 }
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00007346 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
7347 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
7348 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
7349 NewClassTy = NewRT->getPointeeType();
7350 OldClassTy = OldRT->getPointeeType();
7351 }
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007352 }
7353 }
Mike Stump11289f42009-09-09 15:08:12 +00007354
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007355 // The return types aren't either both pointers or references to a class type.
7356 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +00007357 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007358 diag::err_different_return_type_for_overriding_virtual_function)
7359 << New->getDeclName() << NewTy << OldTy;
7360 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump11289f42009-09-09 15:08:12 +00007361
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007362 return true;
7363 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +00007364
Anders Carlssone60365b2009-12-31 18:34:24 +00007365 // C++ [class.virtual]p6:
7366 // If the return type of D::f differs from the return type of B::f, the
7367 // class type in the return type of D::f shall be complete at the point of
7368 // declaration of D::f or shall be the class type D.
Anders Carlsson0c9dd842009-12-31 18:54:35 +00007369 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
7370 if (!RT->isBeingDefined() &&
7371 RequireCompleteType(New->getLocation(), NewClassTy,
7372 PDiag(diag::err_covariant_return_incomplete)
7373 << New->getDeclName()))
Anders Carlssone60365b2009-12-31 18:34:24 +00007374 return true;
Anders Carlsson0c9dd842009-12-31 18:54:35 +00007375 }
Anders Carlssone60365b2009-12-31 18:34:24 +00007376
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00007377 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007378 // Check if the new class derives from the old class.
7379 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
7380 Diag(New->getLocation(),
7381 diag::err_covariant_return_not_derived)
7382 << New->getDeclName() << NewTy << OldTy;
7383 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
7384 return true;
7385 }
Mike Stump11289f42009-09-09 15:08:12 +00007386
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007387 // Check if we the conversion from derived to base is valid.
John McCall1064d7e2010-03-16 05:22:47 +00007388 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlsson7afe4242010-04-24 17:11:09 +00007389 diag::err_covariant_return_inaccessible_base,
7390 diag::err_covariant_return_ambiguous_derived_to_base_conv,
7391 // FIXME: Should this point to the return type?
7392 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCallc1465822011-02-14 07:13:47 +00007393 // FIXME: this note won't trigger for delayed access control
7394 // diagnostics, and it's impossible to get an undelayed error
7395 // here from access control during the original parse because
7396 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007397 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
7398 return true;
7399 }
7400 }
Mike Stump11289f42009-09-09 15:08:12 +00007401
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007402 // The qualifiers of the return types must be the same.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00007403 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007404 Diag(New->getLocation(),
7405 diag::err_covariant_return_type_different_qualifications)
Anders Carlssonf2a2e332009-05-14 01:09:04 +00007406 << New->getDeclName() << NewTy << OldTy;
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007407 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
7408 return true;
7409 };
Mike Stump11289f42009-09-09 15:08:12 +00007410
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007411
7412 // The new class type must have the same or less qualifiers as the old type.
7413 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
7414 Diag(New->getLocation(),
7415 diag::err_covariant_return_type_class_type_more_qualified)
7416 << New->getDeclName() << NewTy << OldTy;
7417 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
7418 return true;
7419 };
Mike Stump11289f42009-09-09 15:08:12 +00007420
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007421 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +00007422}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00007423
Douglas Gregor21920e372009-12-01 17:24:26 +00007424/// \brief Mark the given method pure.
7425///
7426/// \param Method the method to be marked pure.
7427///
7428/// \param InitRange the source range that covers the "0" initializer.
7429bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
7430 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
7431 Method->setPure();
Douglas Gregor21920e372009-12-01 17:24:26 +00007432 return false;
7433 }
7434
7435 if (!Method->isInvalidDecl())
7436 Diag(Method->getLocation(), diag::err_non_virtual_pure)
7437 << Method->getDeclName() << InitRange;
7438 return true;
7439}
7440
John McCall1f4ee7b2009-12-19 09:28:58 +00007441/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
7442/// an initializer for the out-of-line declaration 'Dcl'. The scope
7443/// is a fresh scope pushed for just this purpose.
7444///
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00007445/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
7446/// static data member of class X, names should be looked up in the scope of
7447/// class X.
John McCall48871652010-08-21 09:40:31 +00007448void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00007449 // If there is no declaration, there was an error parsing it.
John McCall1f4ee7b2009-12-19 09:28:58 +00007450 if (D == 0) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00007451
John McCall1f4ee7b2009-12-19 09:28:58 +00007452 // We should only get called for declarations with scope specifiers, like:
7453 // int foo::bar;
7454 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +00007455 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00007456}
7457
7458/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall48871652010-08-21 09:40:31 +00007459/// initializer for the out-of-line declaration 'D'.
7460void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00007461 // If there is no declaration, there was an error parsing it.
John McCall1f4ee7b2009-12-19 09:28:58 +00007462 if (D == 0) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00007463
John McCall1f4ee7b2009-12-19 09:28:58 +00007464 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +00007465 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00007466}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00007467
7468/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
7469/// C++ if/switch/while/for statement.
7470/// e.g: "if (int x = f()) {...}"
John McCall48871652010-08-21 09:40:31 +00007471DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00007472 // C++ 6.4p2:
7473 // The declarator shall not specify a function or an array.
7474 // The type-specifier-seq shall not contain typedef and shall not declare a
7475 // new class or enumeration.
7476 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
7477 "Parser allowed 'typedef' as storage class of condition decl.");
7478
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00007479 TagDecl *OwnedTag = 0;
John McCall8cb7bdf2010-06-04 23:28:52 +00007480 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S, &OwnedTag);
7481 QualType Ty = TInfo->getType();
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00007482
7483 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
7484 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
7485 // would be created and CXXConditionDeclExpr wants a VarDecl.
7486 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
7487 << D.getSourceRange();
7488 return DeclResult();
7489 } else if (OwnedTag && OwnedTag->isDefinition()) {
7490 // The type-specifier-seq shall not declare a new class or enumeration.
7491 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
7492 }
7493
John McCall48871652010-08-21 09:40:31 +00007494 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00007495 if (!Dcl)
7496 return DeclResult();
7497
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00007498 return Dcl;
7499}
Anders Carlssonf98849e2009-12-02 17:15:43 +00007500
Douglas Gregor88d292c2010-05-13 16:44:06 +00007501void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
7502 bool DefinitionRequired) {
7503 // Ignore any vtable uses in unevaluated operands or for classes that do
7504 // not have a vtable.
7505 if (!Class->isDynamicClass() || Class->isDependentContext() ||
7506 CurContext->isDependentContext() ||
7507 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolae7113ca2010-03-10 02:19:29 +00007508 return;
7509
Douglas Gregor88d292c2010-05-13 16:44:06 +00007510 // Try to insert this class into the map.
7511 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
7512 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
7513 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
7514 if (!Pos.second) {
Daniel Dunbar53217762010-05-25 00:33:13 +00007515 // If we already had an entry, check to see if we are promoting this vtable
7516 // to required a definition. If so, we need to reappend to the VTableUses
7517 // list, since we may have already processed the first entry.
7518 if (DefinitionRequired && !Pos.first->second) {
7519 Pos.first->second = true;
7520 } else {
7521 // Otherwise, we can early exit.
7522 return;
7523 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00007524 }
7525
7526 // Local classes need to have their virtual members marked
7527 // immediately. For all other classes, we mark their virtual members
7528 // at the end of the translation unit.
7529 if (Class->isLocalClass())
7530 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar0547ad32010-05-11 21:32:35 +00007531 else
Douglas Gregor88d292c2010-05-13 16:44:06 +00007532 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregor0c4aad12010-05-11 20:24:17 +00007533}
7534
Douglas Gregor88d292c2010-05-13 16:44:06 +00007535bool Sema::DefineUsedVTables() {
Douglas Gregor88d292c2010-05-13 16:44:06 +00007536 if (VTableUses.empty())
Anders Carlsson82fccd02009-12-07 08:24:59 +00007537 return false;
Chandler Carruth88bfa5e2010-12-12 21:36:11 +00007538
Douglas Gregor88d292c2010-05-13 16:44:06 +00007539 // Note: The VTableUses vector could grow as a result of marking
7540 // the members of a class as "used", so we check the size each
7541 // time through the loop and prefer indices (with are stable) to
7542 // iterators (which are not).
7543 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbar105ce6d2010-05-25 00:32:58 +00007544 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor88d292c2010-05-13 16:44:06 +00007545 if (!Class)
7546 continue;
7547
7548 SourceLocation Loc = VTableUses[I].second;
7549
7550 // If this class has a key function, but that key function is
7551 // defined in another translation unit, we don't need to emit the
7552 // vtable even though we're using it.
7553 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00007554 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor88d292c2010-05-13 16:44:06 +00007555 switch (KeyFunction->getTemplateSpecializationKind()) {
7556 case TSK_Undeclared:
7557 case TSK_ExplicitSpecialization:
7558 case TSK_ExplicitInstantiationDeclaration:
7559 // The key function is in another translation unit.
7560 continue;
7561
7562 case TSK_ExplicitInstantiationDefinition:
7563 case TSK_ImplicitInstantiation:
7564 // We will be instantiating the key function.
7565 break;
7566 }
7567 } else if (!KeyFunction) {
7568 // If we have a class with no key function that is the subject
7569 // of an explicit instantiation declaration, suppress the
7570 // vtable; it will live with the explicit instantiation
7571 // definition.
7572 bool IsExplicitInstantiationDeclaration
7573 = Class->getTemplateSpecializationKind()
7574 == TSK_ExplicitInstantiationDeclaration;
7575 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
7576 REnd = Class->redecls_end();
7577 R != REnd; ++R) {
7578 TemplateSpecializationKind TSK
7579 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
7580 if (TSK == TSK_ExplicitInstantiationDeclaration)
7581 IsExplicitInstantiationDeclaration = true;
7582 else if (TSK == TSK_ExplicitInstantiationDefinition) {
7583 IsExplicitInstantiationDeclaration = false;
7584 break;
7585 }
7586 }
7587
7588 if (IsExplicitInstantiationDeclaration)
7589 continue;
7590 }
7591
7592 // Mark all of the virtual members of this class as referenced, so
7593 // that we can build a vtable. Then, tell the AST consumer that a
7594 // vtable for this class is required.
7595 MarkVirtualMembersReferenced(Loc, Class);
7596 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
7597 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
7598
7599 // Optionally warn if we're emitting a weak vtable.
7600 if (Class->getLinkage() == ExternalLinkage &&
7601 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00007602 if (!KeyFunction || (KeyFunction->hasBody() && KeyFunction->isInlined()))
Douglas Gregor88d292c2010-05-13 16:44:06 +00007603 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
7604 }
Anders Carlssonf98849e2009-12-02 17:15:43 +00007605 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00007606 VTableUses.clear();
7607
Anders Carlsson82fccd02009-12-07 08:24:59 +00007608 return true;
Anders Carlssonf98849e2009-12-02 17:15:43 +00007609}
Anders Carlsson82fccd02009-12-07 08:24:59 +00007610
Rafael Espindola5b334082010-03-26 00:36:59 +00007611void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
7612 const CXXRecordDecl *RD) {
Anders Carlsson82fccd02009-12-07 08:24:59 +00007613 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
7614 e = RD->method_end(); i != e; ++i) {
7615 CXXMethodDecl *MD = *i;
7616
7617 // C++ [basic.def.odr]p2:
7618 // [...] A virtual member function is used if it is not pure. [...]
7619 if (MD->isVirtual() && !MD->isPure())
7620 MarkDeclarationReferenced(Loc, MD);
7621 }
Rafael Espindola5b334082010-03-26 00:36:59 +00007622
7623 // Only classes that have virtual bases need a VTT.
7624 if (RD->getNumVBases() == 0)
7625 return;
7626
7627 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
7628 e = RD->bases_end(); i != e; ++i) {
7629 const CXXRecordDecl *Base =
7630 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola5b334082010-03-26 00:36:59 +00007631 if (Base->getNumVBases() == 0)
7632 continue;
7633 MarkVirtualMembersReferenced(Loc, Base);
7634 }
Anders Carlsson82fccd02009-12-07 08:24:59 +00007635}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007636
7637/// SetIvarInitializers - This routine builds initialization ASTs for the
7638/// Objective-C implementation whose ivars need be initialized.
7639void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
7640 if (!getLangOptions().CPlusPlus)
7641 return;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00007642 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007643 llvm::SmallVector<ObjCIvarDecl*, 8> ivars;
7644 CollectIvarsToConstructOrDestruct(OID, ivars);
7645 if (ivars.empty())
7646 return;
Alexis Hunt1d792652011-01-08 20:30:50 +00007647 llvm::SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007648 for (unsigned i = 0; i < ivars.size(); i++) {
7649 FieldDecl *Field = ivars[i];
Douglas Gregor527786e2010-05-20 02:24:22 +00007650 if (Field->isInvalidDecl())
7651 continue;
7652
Alexis Hunt1d792652011-01-08 20:30:50 +00007653 CXXCtorInitializer *Member;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007654 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
7655 InitializationKind InitKind =
7656 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
7657
7658 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCalldadc5752010-08-24 06:29:42 +00007659 ExprResult MemberInit =
John McCallfaf5fb42010-08-26 23:41:50 +00007660 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregora40433a2010-12-07 00:41:46 +00007661 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007662 // Note, MemberInit could actually come back empty if no initialization
7663 // is required (e.g., because it would call a trivial default constructor)
7664 if (!MemberInit.get() || MemberInit.isInvalid())
7665 continue;
John McCallacf0ee52010-10-08 02:01:28 +00007666
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007667 Member =
Alexis Hunt1d792652011-01-08 20:30:50 +00007668 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
7669 SourceLocation(),
7670 MemberInit.takeAs<Expr>(),
7671 SourceLocation());
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007672 AllToInit.push_back(Member);
Douglas Gregor527786e2010-05-20 02:24:22 +00007673
7674 // Be sure that the destructor is accessible and is marked as referenced.
7675 if (const RecordType *RecordTy
7676 = Context.getBaseElementType(Field->getType())
7677 ->getAs<RecordType>()) {
7678 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregore71edda2010-07-01 22:47:18 +00007679 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Douglas Gregor527786e2010-05-20 02:24:22 +00007680 MarkDeclarationReferenced(Field->getLocation(), Destructor);
7681 CheckDestructorAccess(Field->getLocation(), Destructor,
7682 PDiag(diag::err_access_dtor_ivar)
7683 << Context.getBaseElementType(Field->getType()));
7684 }
7685 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007686 }
7687 ObjCImplementation->setIvarInitializers(Context,
7688 AllToInit.data(), AllToInit.size());
7689 }
7690}