blob: 0565a7fef90044310d7024d4107debb05f7e321e [file] [log] [blame]
Chris Lattner3d1cee32008-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 McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
John McCall5f1e0942010-08-24 08:50:51 +000015#include "clang/Sema/CXXFieldCollector.h"
16#include "clang/Sema/Scope.h"
Douglas Gregore737f502010-08-12 20:07:10 +000017#include "clang/Sema/Initialization.h"
18#include "clang/Sema/Lookup.h"
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +000019#include "clang/AST/ASTConsumer.h"
Douglas Gregore37ac4f2008-04-13 21:30:24 +000020#include "clang/AST/ASTContext.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000021#include "clang/AST/CharUnits.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000022#include "clang/AST/CXXInheritance.h"
Anders Carlsson8211eff2009-03-24 01:19:16 +000023#include "clang/AST/DeclVisitor.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000024#include "clang/AST/RecordLayout.h"
25#include "clang/AST/StmtVisitor.h"
Douglas Gregor802ab452009-12-02 22:36:29 +000026#include "clang/AST/TypeLoc.h"
Douglas Gregor02189362008-10-22 21:13:31 +000027#include "clang/AST/TypeOrdering.h"
John McCall19510852010-08-20 18:27:03 +000028#include "clang/Sema/DeclSpec.h"
29#include "clang/Sema/ParsedTemplate.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000030#include "clang/Basic/PartialDiagnostic.h"
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +000031#include "clang/Lex/Preprocessor.h"
John McCall50df6ae2010-08-25 07:03:20 +000032#include "llvm/ADT/DenseSet.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000033#include "llvm/ADT/STLExtras.h"
Douglas Gregorf8268ae2008-10-22 17:49:05 +000034#include <map>
Douglas Gregora8f32e02009-10-06 17:59:45 +000035#include <set>
Chris Lattner3d1cee32008-04-08 05:04:30 +000036
37using namespace clang;
38
Chris Lattner8123a952008-04-10 02:22:51 +000039//===----------------------------------------------------------------------===//
40// CheckDefaultArgumentVisitor
41//===----------------------------------------------------------------------===//
42
Chris Lattner9e979552008-04-12 23:52:44 +000043namespace {
44 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
45 /// the default argument of a parameter to determine whether it
46 /// contains any ill-formed subexpressions. For example, this will
47 /// diagnose the use of local variables or parameters within the
48 /// default argument expression.
Benjamin Kramer85b45212009-11-28 19:45:26 +000049 class CheckDefaultArgumentVisitor
Chris Lattnerb77792e2008-07-26 22:17:49 +000050 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattner9e979552008-04-12 23:52:44 +000051 Expr *DefaultArg;
52 Sema *S;
Chris Lattner8123a952008-04-10 02:22:51 +000053
Chris Lattner9e979552008-04-12 23:52:44 +000054 public:
Mike Stump1eb44332009-09-09 15:08:12 +000055 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattner9e979552008-04-12 23:52:44 +000056 : DefaultArg(defarg), S(s) {}
Chris Lattner8123a952008-04-10 02:22:51 +000057
Chris Lattner9e979552008-04-12 23:52:44 +000058 bool VisitExpr(Expr *Node);
59 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor796da182008-11-04 14:32:21 +000060 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattner9e979552008-04-12 23:52:44 +000061 };
Chris Lattner8123a952008-04-10 02:22:51 +000062
Chris Lattner9e979552008-04-12 23:52:44 +000063 /// VisitExpr - Visit all of the children of this expression.
64 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
65 bool IsInvalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +000066 for (Stmt::child_iterator I = Node->child_begin(),
Chris Lattnerb77792e2008-07-26 22:17:49 +000067 E = Node->child_end(); I != E; ++I)
68 IsInvalid |= Visit(*I);
Chris Lattner9e979552008-04-12 23:52:44 +000069 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000070 }
71
Chris Lattner9e979552008-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 Gregor8e9bebd2008-10-21 16:13:35 +000076 NamedDecl *Decl = DRE->getDecl();
Chris Lattner9e979552008-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 Stump1eb44332009-09-09 15:08:12 +000086 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000087 diag::err_param_default_argument_references_param)
Chris Lattner08631c52008-11-23 21:45:46 +000088 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff248a7532008-04-15 22:42:06 +000089 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000090 // C++ [dcl.fct.default]p7
91 // Local variables shall not be used in default argument
92 // expressions.
John McCallb6bbcc92010-10-15 04:57:14 +000093 if (VDecl->isLocalVarDecl())
Mike Stump1eb44332009-09-09 15:08:12 +000094 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000095 diag::err_param_default_argument_references_local)
Chris Lattner08631c52008-11-23 21:45:46 +000096 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +000097 }
Chris Lattner8123a952008-04-10 02:22:51 +000098
Douglas Gregor3996f232008-11-04 13:41:56 +000099 return false;
100 }
Chris Lattner9e979552008-04-12 23:52:44 +0000101
Douglas Gregor796da182008-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 Lattnerfa25bbb2008-11-19 05:08:23 +0000108 diag::err_param_default_argument_references_this)
109 << ThisE->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000110 }
Chris Lattner8123a952008-04-10 02:22:51 +0000111}
112
Anders Carlssoned961f92009-08-25 02:29:20 +0000113bool
John McCall9ae2f072010-08-23 23:25:46 +0000114Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump1eb44332009-09-09 15:08:12 +0000115 SourceLocation EqualLoc) {
Anders Carlsson5653ca52009-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 Carlssoned961f92009-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 Jahanian745da3a2010-09-24 17:30:16 +0000128 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
129 Param);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000130 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
131 EqualLoc);
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000132 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
John McCall60d7b3a2010-08-24 06:29:42 +0000133 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
Nico Weber6bb4dcb2010-11-28 22:53:37 +0000134 MultiExprArg(*this, &Arg, 1));
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000135 if (Result.isInvalid())
Anders Carlsson9351c172009-08-25 03:18:48 +0000136 return true;
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000137 Arg = Result.takeAs<Expr>();
Anders Carlssoned961f92009-08-25 02:29:20 +0000138
John McCallb4eb64d2010-10-08 02:01:28 +0000139 CheckImplicitConversions(Arg, EqualLoc);
John McCall4765fa02010-12-06 08:20:24 +0000140 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000141
Anders Carlssoned961f92009-08-25 02:29:20 +0000142 // Okay: add the default argument to the parameter
143 Param->setDefaultArg(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000144
Douglas Gregor8cfb7a32010-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 Carlsson9351c172009-08-25 03:18:48 +0000157 return false;
Anders Carlssoned961f92009-08-25 02:29:20 +0000158}
159
Chris Lattner8123a952008-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 Lattner3d1cee32008-04-08 05:04:30 +0000163void
John McCalld226f652010-08-21 09:40:31 +0000164Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000165 Expr *DefaultArg) {
166 if (!param || !DefaultArg)
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000167 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000168
John McCalld226f652010-08-21 09:40:31 +0000169 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000170 UnparsedDefaultArgLocs.erase(Param);
171
Chris Lattner3d1cee32008-04-08 05:04:30 +0000172 // Default arguments are only permitted in C++
173 if (!getLangOptions().CPlusPlus) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000174 Diag(EqualLoc, diag::err_param_default_argument)
175 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000176 Param->setInvalidDecl();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000177 return;
178 }
179
Douglas Gregor6f526752010-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 Carlsson66e30672009-08-25 01:02:06 +0000186 // Check that the default argument is well-formed
John McCall9ae2f072010-08-23 23:25:46 +0000187 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
188 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlsson66e30672009-08-25 01:02:06 +0000189 Param->setInvalidDecl();
190 return;
191 }
Mike Stump1eb44332009-09-09 15:08:12 +0000192
John McCall9ae2f072010-08-23 23:25:46 +0000193 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000194}
195
Douglas Gregor61366e92008-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 McCalld226f652010-08-21 09:40:31 +0000200void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson5e300d12009-06-12 16:51:40 +0000201 SourceLocation EqualLoc,
202 SourceLocation ArgLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000203 if (!param)
204 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000205
John McCalld226f652010-08-21 09:40:31 +0000206 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000207 if (Param)
208 Param->setUnparsedDefaultArg();
Mike Stump1eb44332009-09-09 15:08:12 +0000209
Anders Carlsson5e300d12009-06-12 16:51:40 +0000210 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor61366e92008-12-24 00:01:03 +0000211}
212
Douglas Gregor72b505b2008-12-16 21:30:33 +0000213/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
214/// the default argument for the parameter param failed.
John McCalld226f652010-08-21 09:40:31 +0000215void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000216 if (!param)
217 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000218
John McCalld226f652010-08-21 09:40:31 +0000219 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Mike Stump1eb44332009-09-09 15:08:12 +0000220
Anders Carlsson5e300d12009-06-12 16:51:40 +0000221 Param->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000222
Anders Carlsson5e300d12009-06-12 16:51:40 +0000223 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000224}
225
Douglas Gregor6d6eb572008-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 Lattnerb28317a2009-03-28 19:18:32 +0000239 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000240 DeclaratorChunk &chunk = D.getTypeObject(i);
241 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000242 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
243 ParmVarDecl *Param =
John McCalld226f652010-08-21 09:40:31 +0000244 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000245 if (Param->hasUnparsedDefaultArg()) {
246 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-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 Gregor61366e92008-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 Gregor6d6eb572008-05-07 04:49:29 +0000255 }
256 }
257 }
258 }
259}
260
Chris Lattner3d1cee32008-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 Gregorcda9c672009-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 Lattner3d1cee32008-04-08 05:04:30 +0000268 // C++ [dcl.fct.default]p4:
Chris Lattner3d1cee32008-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 Gregor6cc15182009-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 Lattner3d1cee32008-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 Gregor6cc15182009-09-11 18:44:32 +0000290 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
Douglas Gregor4f123ff2010-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 Stump1eb44332009-09-09 15:08:12 +0000300 Diag(NewParam->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000301 diag::err_param_default_argument_redefinition)
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000302 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-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 Gregorcda9c672009-02-16 17:45:42 +0000316 Invalid = true;
Douglas Gregord85cef52009-09-17 19:51:30 +0000317 } else if (OldParam->hasDefaultArg()) {
John McCall3d6c1782010-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 McCall4765fa02010-12-06 08:20:24 +0000320 // strips off any top-level ExprWithCleanups.
John McCallbf73b352010-03-12 18:31:32 +0000321 NewParam->setHasInheritedDefaultArg();
Douglas Gregord85cef52009-09-17 19:51:30 +0000322 if (OldParam->hasUninstantiatedDefaultArg())
323 NewParam->setUninstantiatedDefaultArg(
324 OldParam->getUninstantiatedDefaultArg());
325 else
John McCall3d6c1782010-05-04 01:53:42 +0000326 NewParam->setDefaultArg(OldParam->getInit());
Douglas Gregor6cc15182009-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 Gregor096ebfd2009-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 Gregor8c638ab2009-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 Gregor096ebfd2009-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 Gregor6cc15182009-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 Lattner3d1cee32008-04-08 05:04:30 +0000377 }
378 }
379
Douglas Gregore13ad832010-02-12 07:32:17 +0000380 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000381 Invalid = true;
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000382
Douglas Gregorcda9c672009-02-16 17:45:42 +0000383 return Invalid;
Chris Lattner3d1cee32008-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 Carlsson5f49a0c2009-08-25 01:23:32 +0000396 if (Param->hasDefaultArg())
Chris Lattner3d1cee32008-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 Stump1eb44332009-09-09 15:08:12 +0000407 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000408 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000409 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000410 if (Param->isInvalidDecl())
411 /* We already complained about this parameter. */;
412 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000413 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000414 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000415 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000416 else
Mike Stump1eb44332009-09-09 15:08:12 +0000417 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000418 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000419
Chris Lattner3d1cee32008-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 Carlsson5e300d12009-06-12 16:51:40 +0000431 if (Param->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000432 Param->setDefaultArg(0);
433 }
434 }
435 }
436}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000437
Douglas Gregorb48fe382008-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 Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000442bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
443 const CXXScopeSpec *SS) {
Douglas Gregorb862b8f2010-01-11 23:29:10 +0000444 assert(getLangOptions().CPlusPlus && "No class names in C!");
445
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000446 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +0000447 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +0000448 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-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 Gregor6f7a17b2010-02-05 06:12:42 +0000453 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregorb48fe382008-10-31 09:07:45 +0000454 return &II == CurDecl->getIdentifier();
455 else
456 return false;
457}
458
Mike Stump1eb44332009-09-09 15:08:12 +0000459/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-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 Gregorf90b27a2011-01-03 22:36:02 +0000467 TypeSourceInfo *TInfo,
468 SourceLocation EllipsisLoc) {
Nick Lewycky56062202010-07-26 16:56:01 +0000469 QualType BaseType = TInfo->getType();
470
Douglas Gregor2943aed2009-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 Gregorf90b27a2011-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 Gregor2943aed2009-03-03 04:44:36 +0000486 if (BaseType->isDependentType())
Mike Stump1eb44332009-09-09 15:08:12 +0000487 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +0000488 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000489 Access, TInfo, EllipsisLoc);
Nick Lewycky56062202010-07-26 16:56:01 +0000490
491 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
Douglas Gregor2943aed2009-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 Stump1eb44332009-09-09 15:08:12 +0000509 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000510 PDiag(diag::err_incomplete_base_class)
John McCall572fc622010-08-17 07:23:57 +0000511 << SpecifierRange)) {
512 Class->setInvalidDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000513 return 0;
John McCall572fc622010-08-17 07:23:57 +0000514 }
Douglas Gregor2943aed2009-03-03 04:44:36 +0000515
Eli Friedman1d954f62009-08-15 21:55:26 +0000516 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +0000517 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000518 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor952b0172010-02-11 01:04:33 +0000519 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000520 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedman1d954f62009-08-15 21:55:26 +0000521 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
522 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +0000523
Anders Carlssondfc2f102011-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 Carlssoncb88a1f2011-01-24 16:26:15 +0000528 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
Anders Carlssondfc2f102011-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 McCall572fc622010-08-17 07:23:57 +0000536 if (BaseDecl->isInvalidDecl())
537 Class->setInvalidDecl();
Anders Carlsson51f94042009-12-03 17:49:57 +0000538
539 // Create the base specifier.
Anders Carlsson51f94042009-12-03 17:49:57 +0000540 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +0000541 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000542 Access, TInfo, EllipsisLoc);
Anders Carlsson51f94042009-12-03 17:49:57 +0000543}
544
Douglas Gregore37ac4f2008-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 Stump1eb44332009-09-09 15:08:12 +0000547/// example:
548/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000549/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallf312b1e2010-08-26 23:41:50 +0000550BaseResult
John McCalld226f652010-08-21 09:40:31 +0000551Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000552 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000553 ParsedType basetype, SourceLocation BaseLoc,
554 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000555 if (!classdecl)
556 return true;
557
Douglas Gregor40808ce2009-03-09 23:48:35 +0000558 AdjustDeclIfTemplate(classdecl);
John McCalld226f652010-08-21 09:40:31 +0000559 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregor5fe8c042010-02-27 00:25:28 +0000560 if (!Class)
561 return true;
562
Nick Lewycky56062202010-07-26 16:56:01 +0000563 TypeSourceInfo *TInfo = 0;
564 GetTypeFromParser(basetype, &TInfo);
Douglas Gregord0937222010-12-13 22:49:22 +0000565
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000566 if (EllipsisLoc.isInvalid() &&
567 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregord0937222010-12-13 22:49:22 +0000568 UPPC_BaseType))
569 return true;
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000570
Douglas Gregor2943aed2009-03-03 04:44:36 +0000571 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000572 Virtual, Access, TInfo,
573 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +0000574 return BaseSpec;
Mike Stump1eb44332009-09-09 15:08:12 +0000575
Douglas Gregor2943aed2009-03-03 04:44:36 +0000576 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000577}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000578
Douglas Gregor2943aed2009-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 Gregorf8268ae2008-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 Gregor57c856b2008-10-23 18:13:27 +0000588 // that the key is always the unqualified canonical type of the base
589 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000590 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
591
592 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +0000593 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +0000594 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +0000595 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +0000596 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +0000597 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +0000598 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Fariborz Jahanian0ed5c5d2010-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 Gregorf8268ae2008-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 Gregor2943aed2009-03-03 04:44:36 +0000610 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000611 diag::err_duplicate_base_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000612 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +0000613 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +0000614
615 // Delete the duplicate base class specifier; we're going to
616 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000617 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000618
619 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000620 } else {
621 // Okay, add this new base class.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000622 KnownBaseTypes[NewBaseType] = Bases[idx];
623 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000624 }
625 }
626
627 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +0000628 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-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 Gregor2aef06d2009-07-22 20:55:49 +0000633 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-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 McCalld226f652010-08-21 09:40:31 +0000641void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, BaseTy **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000642 unsigned NumBases) {
643 if (!ClassDecl || !Bases || !NumBases)
644 return;
645
646 AdjustDeclIfTemplate(ClassDecl);
John McCalld226f652010-08-21 09:40:31 +0000647 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor2943aed2009-03-03 04:44:36 +0000648 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000649}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000650
John McCall3cb0ebd2010-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 Gregora8f32e02009-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 McCall3cb0ebd2010-03-10 03:28:59 +0000665
666 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
667 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000668 return false;
669
John McCall3cb0ebd2010-03-10 03:28:59 +0000670 CXXRecordDecl *BaseRD = GetClassForType(Base);
671 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000672 return false;
673
John McCall86ff3082010-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 Gregora8f32e02009-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 McCall3cb0ebd2010-03-10 03:28:59 +0000684 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
685 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000686 return false;
687
John McCall3cb0ebd2010-03-10 03:28:59 +0000688 CXXRecordDecl *BaseRD = GetClassForType(Base);
689 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000690 return false;
691
Douglas Gregora8f32e02009-10-06 17:59:45 +0000692 return DerivedRD->isDerivedFrom(BaseRD, Paths);
693}
694
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000695void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallf871d0c2010-08-07 06:22:56 +0000696 CXXCastPath &BasePathArray) {
Anders Carlsson5cf86ba2010-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 McCallf871d0c2010-08-07 06:22:56 +0000715 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000716}
717
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000718/// \brief Determine whether the given base path includes a virtual
719/// base class.
John McCallf871d0c2010-08-07 06:22:56 +0000720bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
721 for (CXXCastPath::const_iterator B = BasePath.begin(),
722 BEnd = BasePath.end();
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000723 B != BEnd; ++B)
724 if ((*B)->isVirtual())
725 return true;
726
727 return false;
728}
729
Douglas Gregora8f32e02009-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 McCall58e6f342010-03-16 05:22:47 +0000740 unsigned InaccessibleBaseID,
Douglas Gregora8f32e02009-10-06 17:59:45 +0000741 unsigned AmbigiousBaseConvID,
742 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +0000743 DeclarationName Name,
John McCallf871d0c2010-08-07 06:22:56 +0000744 CXXCastPath *BasePath) {
Douglas Gregora8f32e02009-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 Carlsson5cf86ba2010-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 Carlssone25a96c2010-04-24 17:11:09 +0000767 }
John McCall6b2accb2010-02-10 09:31:12 +0000768 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000769
770 // Build a base path if necessary.
771 if (BasePath)
772 BuildBasePathArray(Paths, *BasePath);
773 return false;
Douglas Gregora8f32e02009-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 Redla82e4ae2009-11-14 21:15:49 +0000801 SourceLocation Loc, SourceRange Range,
John McCallf871d0c2010-08-07 06:22:56 +0000802 CXXCastPath *BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000803 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +0000804 return CheckDerivedToBaseConversion(Derived, Base,
John McCall58e6f342010-03-16 05:22:47 +0000805 IgnoreAccess ? 0
806 : diag::err_upcast_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +0000807 diag::err_ambiguous_derived_to_base_conv,
Anders Carlssone25a96c2010-04-24 17:11:09 +0000808 Loc, Range, DeclarationName(),
809 BasePath);
Douglas Gregora8f32e02009-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 Kyrtzidis07952322008-07-01 10:37:29 +0000844//===----------------------------------------------------------------------===//
845// C++ class member Handling
846//===----------------------------------------------------------------------===//
847
Abramo Bagnara6206d532010-06-05 05:09:32 +0000848/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
John McCalld226f652010-08-21 09:40:31 +0000849Decl *Sema::ActOnAccessSpecifier(AccessSpecifier Access,
850 SourceLocation ASLoc,
851 SourceLocation ColonLoc) {
Abramo Bagnara6206d532010-06-05 05:09:32 +0000852 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCalld226f652010-08-21 09:40:31 +0000853 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnara6206d532010-06-05 05:09:32 +0000854 ASLoc, ColonLoc);
855 CurContext->addHiddenDecl(ASDecl);
John McCalld226f652010-08-21 09:40:31 +0000856 return ASDecl;
Abramo Bagnara6206d532010-06-05 05:09:32 +0000857}
858
Anders Carlsson9e682d92011-01-20 05:57:14 +0000859/// CheckOverrideControl - Check C++0x override control semantics.
Anders Carlsson4ebf1602011-01-20 06:29:02 +0000860void Sema::CheckOverrideControl(const Decl *D) {
Anders Carlsson9e682d92011-01-20 05:57:14 +0000861 const CXXMethodDecl *MD = llvm::dyn_cast<CXXMethodDecl>(D);
862 if (!MD || !MD->isVirtual())
863 return;
864
Anders Carlsson3ffe1832011-01-20 06:33:26 +0000865 if (MD->isDependentContext())
866 return;
867
Anders Carlsson9e682d92011-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 Carlssoncb88a1f2011-01-24 16:26:15 +0000874 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) {
Anders Carlsson4ebf1602011-01-20 06:29:02 +0000875 Diag(MD->getLocation(),
Anders Carlsson9e682d92011-01-20 05:57:14 +0000876 diag::err_function_marked_override_not_overriding)
877 << MD->getDeclName();
878 return;
879 }
Anders Carlssonaa23d282011-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 Carlssoncb88a1f2011-01-24 16:26:15 +0000886 if (MD->getParent()->hasAttr<ExplicitAttr>() && !isa<CXXDestructorDecl>(MD) &&
887 HasOverriddenMethods && !MD->hasAttr<OverrideAttr>()) {
Anders Carlssonaa23d282011-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 Carlsson9e682d92011-01-20 05:57:14 +0000900}
901
Anders Carlsson2e1c7302011-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 Carlssoncb88a1f2011-01-24 16:26:15 +0000907 if (!Old->hasAttr<FinalAttr>())
Anders Carlssonf89e0422011-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 Carlsson2e1c7302011-01-20 16:25:36 +0000914}
915
Argyrios Kyrtzidis07952322008-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 Lattnerb6688e02009-04-12 22:37:57 +0000919/// any.
John McCalld226f652010-08-21 09:40:31 +0000920Decl *
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000921Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +0000922 MultiTemplateParamsArg TemplateParameterLists,
Anders Carlsson69a87352011-01-20 03:57:25 +0000923 ExprTy *BW, const VirtSpecifiers &VS,
924 ExprTy *InitExpr, bool IsDefinition,
Sebastian Redld1a78462009-11-24 23:38:44 +0000925 bool Deleted) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000926 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +0000927 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
928 DeclarationName Name = NameInfo.getName();
929 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor90ba6d52010-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 Kyrtzidis07952322008-07-01 10:37:29 +0000935 Expr *BitWidth = static_cast<Expr*>(BW);
936 Expr *Init = static_cast<Expr*>(InitExpr);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000937
John McCall4bde1e12010-06-04 08:34:12 +0000938 assert(isa<CXXRecordDecl>(CurContext));
John McCall67d1a672009-08-06 02:15:43 +0000939 assert(!DS.isFriendSpecified());
940
John McCall4bde1e12010-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 McCallb3d87482010-08-24 05:47:05 +0000946 QualType TDType = GetTypeFromParser(DS.getRepAsType());
John McCall4bde1e12010-06-04 08:34:12 +0000947 isFunc = TDType->isFunctionType();
948 }
949
Argyrios Kyrtzidis07952322008-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 Redl669d5d72008-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 Kyrtzidis07952322008-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 Redl669d5d72008-11-14 23:42:31 +0000961 case DeclSpec::SCS_mutable:
962 if (isFunc) {
963 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000964 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +0000965 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000966 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +0000967
Sebastian Redla11f42f2008-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 Redl669d5d72008-11-14 23:42:31 +0000970 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redl669d5d72008-11-14 23:42:31 +0000971 }
972 break;
Argyrios Kyrtzidis07952322008-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 Redl669d5d72008-11-14 23:42:31 +0000982 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
983 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000984 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000985
986 Decl *Member;
Chris Lattner24793662009-03-05 22:45:59 +0000987 if (isInstField) {
Douglas Gregor922fff22010-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 Gregor37b372b2009-08-20 22:52:58 +00001009 // FIXME: Check for template parameters!
Douglas Gregor56c04582010-12-16 00:46:58 +00001010 // FIXME: Check that the name is an identifier!
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001011 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
1012 AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001013 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +00001014 } else {
John McCalld226f652010-08-21 09:40:31 +00001015 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001016 if (!Member) {
John McCalld226f652010-08-21 09:40:31 +00001017 return 0;
Chris Lattner6f8ce142009-03-05 23:03:49 +00001018 }
Chris Lattner8b963ef2009-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 Gregor2d2e9cf2009-03-11 20:22:50 +00001024 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-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 Stump1eb44332009-09-09 15:08:12 +00001037 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +00001038 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +00001039 }
Mike Stump1eb44332009-09-09 15:08:12 +00001040
Chris Lattner8b963ef2009-03-05 23:01:03 +00001041 BitWidth = 0;
1042 Member->setInvalidDecl();
1043 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001044
1045 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +00001046
Douglas Gregor37b372b2009-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 Lattner24793662009-03-05 22:45:59 +00001051 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001052
Anders Carlssonaae5af22011-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 Carlsson9e682d92011-01-20 05:57:14 +00001059 } else
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001060 MD->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
Anders Carlssonaae5af22011-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 Carlsson9e682d92011-01-20 05:57:14 +00001068 } else
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001069 MD->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlssonaae5af22011-01-20 04:34:22 +00001070 }
Anders Carlsson9e682d92011-01-20 05:57:14 +00001071
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001072 CheckOverrideControl(Member);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001073
Douglas Gregor10bd3682008-11-17 22:58:34 +00001074 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001075
Douglas Gregor021c3b32009-03-11 23:00:04 +00001076 if (Init)
John McCall9ae2f072010-08-23 23:25:46 +00001077 AddInitializerToDecl(Member, Init, false);
Sebastian Redle2b68332009-04-12 17:16:29 +00001078 if (Deleted) // FIXME: Source location is not very good.
John McCalld226f652010-08-21 09:40:31 +00001079 SetDeclDeleted(Member, D.getSourceRange().getBegin());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001080
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001081 if (isInstField) {
Douglas Gregor44b43212008-12-11 16:49:14 +00001082 FieldCollector->Add(cast<FieldDecl>(Member));
John McCalld226f652010-08-21 09:40:31 +00001083 return 0;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001084 }
John McCalld226f652010-08-21 09:40:31 +00001085 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001086}
1087
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001088/// \brief Find the direct and/or virtual base specifiers that
1089/// correspond to the given base type, for use in base initialization
1090/// within a constructor.
1091static bool FindBaseInitializer(Sema &SemaRef,
1092 CXXRecordDecl *ClassDecl,
1093 QualType BaseType,
1094 const CXXBaseSpecifier *&DirectBaseSpec,
1095 const CXXBaseSpecifier *&VirtualBaseSpec) {
1096 // First, check for a direct base class.
1097 DirectBaseSpec = 0;
1098 for (CXXRecordDecl::base_class_const_iterator Base
1099 = ClassDecl->bases_begin();
1100 Base != ClassDecl->bases_end(); ++Base) {
1101 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1102 // We found a direct base of this type. That's what we're
1103 // initializing.
1104 DirectBaseSpec = &*Base;
1105 break;
1106 }
1107 }
1108
1109 // Check for a virtual base class.
1110 // FIXME: We might be able to short-circuit this if we know in advance that
1111 // there are no virtual bases.
1112 VirtualBaseSpec = 0;
1113 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1114 // We haven't found a base yet; search the class hierarchy for a
1115 // virtual base class.
1116 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1117 /*DetectVirtual=*/false);
1118 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1119 BaseType, Paths)) {
1120 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1121 Path != Paths.end(); ++Path) {
1122 if (Path->back().Base->isVirtual()) {
1123 VirtualBaseSpec = Path->back().Base;
1124 break;
1125 }
1126 }
1127 }
1128 }
1129
1130 return DirectBaseSpec || VirtualBaseSpec;
1131}
1132
Douglas Gregor7ad83902008-11-05 04:29:56 +00001133/// ActOnMemInitializer - Handle a C++ member initializer.
John McCallf312b1e2010-08-26 23:41:50 +00001134MemInitResult
John McCalld226f652010-08-21 09:40:31 +00001135Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001136 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001137 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001138 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00001139 ParsedType TemplateTypeTy,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001140 SourceLocation IdLoc,
1141 SourceLocation LParenLoc,
1142 ExprTy **Args, unsigned NumArgs,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001143 SourceLocation RParenLoc,
1144 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001145 if (!ConstructorD)
1146 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001147
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001148 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00001149
1150 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00001151 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001152 if (!Constructor) {
1153 // The user wrote a constructor initializer on a function that is
1154 // not a C++ constructor. Ignore the error for now, because we may
1155 // have more member initializers coming; we'll diagnose it just
1156 // once in ActOnMemInitializers.
1157 return true;
1158 }
1159
1160 CXXRecordDecl *ClassDecl = Constructor->getParent();
1161
1162 // C++ [class.base.init]p2:
1163 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky7663f392010-11-20 01:29:55 +00001164 // constructor's class and, if not found in that scope, are looked
1165 // up in the scope containing the constructor's definition.
1166 // [Note: if the constructor's class contains a member with the
1167 // same name as a direct or virtual base class of the class, a
1168 // mem-initializer-id naming the member or base class and composed
1169 // of a single identifier refers to the class member. A
Douglas Gregor7ad83902008-11-05 04:29:56 +00001170 // mem-initializer-id for the hidden base class may be specified
1171 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00001172 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001173 // Look for a member, first.
1174 FieldDecl *Member = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001175 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001176 = ClassDecl->lookup(MemberOrBase);
Francois Pichet87c2e122010-11-21 06:08:52 +00001177 if (Result.first != Result.second) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001178 Member = dyn_cast<FieldDecl>(*Result.first);
Francois Pichet87c2e122010-11-21 06:08:52 +00001179
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001180 if (Member) {
1181 if (EllipsisLoc.isValid())
1182 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1183 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1184
Francois Pichet00eb3f92010-12-04 09:14:42 +00001185 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
Douglas Gregor802ab452009-12-02 22:36:29 +00001186 LParenLoc, RParenLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001187 }
1188
Francois Pichet00eb3f92010-12-04 09:14:42 +00001189 // Handle anonymous union case.
1190 if (IndirectFieldDecl* IndirectField
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001191 = dyn_cast<IndirectFieldDecl>(*Result.first)) {
1192 if (EllipsisLoc.isValid())
1193 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1194 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1195
Francois Pichet00eb3f92010-12-04 09:14:42 +00001196 return BuildMemberInitializer(IndirectField, (Expr**)Args,
1197 NumArgs, IdLoc,
1198 LParenLoc, RParenLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001199 }
Francois Pichet00eb3f92010-12-04 09:14:42 +00001200 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001201 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001202 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00001203 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00001204 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00001205
1206 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00001207 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
John McCall2b194412009-12-21 10:41:20 +00001208 } else {
1209 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1210 LookupParsedName(R, S, &SS);
1211
1212 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1213 if (!TyD) {
1214 if (R.isAmbiguous()) return true;
1215
John McCallfd225442010-04-09 19:01:14 +00001216 // We don't want access-control diagnostics here.
1217 R.suppressDiagnostics();
1218
Douglas Gregor7a886e12010-01-19 06:46:48 +00001219 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1220 bool NotUnknownSpecialization = false;
1221 DeclContext *DC = computeDeclContext(SS, false);
1222 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1223 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1224
1225 if (!NotUnknownSpecialization) {
1226 // When the scope specifier can refer to a member of an unknown
1227 // specialization, we take it as a type name.
Douglas Gregor107de902010-04-24 15:35:55 +00001228 BaseType = CheckTypenameType(ETK_None,
1229 (NestedNameSpecifier *)SS.getScopeRep(),
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00001230 *MemberOrBase, SourceLocation(),
1231 SS.getRange(), IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00001232 if (BaseType.isNull())
1233 return true;
1234
Douglas Gregor7a886e12010-01-19 06:46:48 +00001235 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00001236 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001237 }
1238 }
1239
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001240 // If no results were found, try to correct typos.
Douglas Gregor7a886e12010-01-19 06:46:48 +00001241 if (R.empty() && BaseType.isNull() &&
Douglas Gregoraaf87162010-04-14 20:04:41 +00001242 CorrectTypo(R, S, &SS, ClassDecl, 0, CTC_NoKeywords) &&
1243 R.isSingleResult()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001244 if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00001245 if (Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl)) {
Douglas Gregorfe0241e2009-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 Gregor849b2432010-03-31 17:46:05 +00001251 << FixItHint::CreateReplacement(R.getNameLoc(),
1252 R.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +00001253 Diag(Member->getLocation(), diag::note_previous_decl)
1254 << Member->getDeclName();
Douglas Gregorfe0241e2009-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 Gregor849b2432010-03-31 17:46:05 +00001270 << FixItHint::CreateReplacement(R.getNameLoc(),
1271 R.getLookupName().getAsString());
Douglas Gregor0d535c82010-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 Gregorfe0241e2009-12-31 09:10:24 +00001280 TyD = Type;
1281 }
1282 }
1283 }
1284
Douglas Gregor7a886e12010-01-19 06:46:48 +00001285 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-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 McCall2b194412009-12-21 10:41:20 +00001290 }
1291
Douglas Gregor7a886e12010-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 McCall2b194412009-12-21 10:41:20 +00001297
Douglas Gregor7a886e12010-01-19 06:46:48 +00001298 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001299 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001300 }
John McCall2b194412009-12-21 10:41:20 +00001301 }
1302 }
Mike Stump1eb44332009-09-09 15:08:12 +00001303
John McCalla93c9342009-12-07 02:54:59 +00001304 if (!TInfo)
1305 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001306
John McCalla93c9342009-12-07 02:54:59 +00001307 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001308 LParenLoc, RParenLoc, ClassDecl, EllipsisLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00001309}
1310
John McCallb4190042009-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 Lewycky43ad1822010-06-15 07:32:55 +00001315static bool InitExprContainsUninitializedFields(const Stmt *S,
Francois Pichet00eb3f92010-12-04 09:14:42 +00001316 const ValueDecl *LhsField,
Nick Lewycky43ad1822010-06-15 07:32:55 +00001317 SourceLocation *L) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00001318 assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField));
1319
Nick Lewycky43ad1822010-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 Carlsson175ffbf2010-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 Lewyckyedd59112010-10-06 18:37:39 +00001335 (void)VD;
Anders Carlsson175ffbf2010-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 McCallb4190042009-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 Lewycky43ad1822010-06-15 07:32:55 +00001349 const Expr *base = ME->getBase();
John McCallb4190042009-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 Kyrtzidisff8819b2010-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 McCallb4190042009-11-04 23:02:40 +00001367 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00001368 for (Stmt::const_child_iterator it = S->child_begin(), e = S->child_end();
1369 it != e; ++it) {
1370 if (!*it) {
1371 // An expression such as 'member(arg ?: "")' may trigger this.
John McCallb4190042009-11-04 23:02:40 +00001372 continue;
1373 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00001374 if (InitExprContainsUninitializedFields(*it, LhsField, L))
1375 return true;
John McCallb4190042009-11-04 23:02:40 +00001376 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00001377 return false;
John McCallb4190042009-11-04 23:02:40 +00001378}
1379
John McCallf312b1e2010-08-26 23:41:50 +00001380MemInitResult
Chandler Carruth894aed92010-12-06 09:23:57 +00001381Sema::BuildMemberInitializer(ValueDecl *Member, Expr **Args,
Eli Friedman59c04372009-07-29 19:44:27 +00001382 unsigned NumArgs, SourceLocation IdLoc,
Douglas Gregor802ab452009-12-02 22:36:29 +00001383 SourceLocation LParenLoc,
Eli Friedman59c04372009-07-29 19:44:27 +00001384 SourceLocation RParenLoc) {
Chandler Carruth894aed92010-12-06 09:23:57 +00001385 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
1386 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
1387 assert((DirectMember || IndirectMember) &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00001388 "Member must be a FieldDecl or IndirectFieldDecl");
1389
Douglas Gregor464b2f02010-11-05 22:21:31 +00001390 if (Member->isInvalidDecl())
1391 return true;
Chandler Carruth894aed92010-12-06 09:23:57 +00001392
John McCallb4190042009-11-04 23:02:40 +00001393 // Diagnose value-uses of fields to initialize themselves, e.g.
1394 // foo(foo)
1395 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00001396 // TODO: implement -Wuninitialized and fold this into that framework.
John McCallb4190042009-11-04 23:02:40 +00001397 for (unsigned i = 0; i < NumArgs; ++i) {
1398 SourceLocation L;
1399 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1400 // FIXME: Return true in the case when other fields are used before being
1401 // uninitialized. For example, let this field be the i'th field. When
1402 // initializing the i'th field, throw a warning if any of the >= i'th
1403 // fields are used, as they are not yet initialized.
1404 // Right now we are only handling the case where the i'th field uses
1405 // itself in its initializer.
1406 Diag(L, diag::warn_field_is_uninit);
1407 }
1408 }
1409
Eli Friedman59c04372009-07-29 19:44:27 +00001410 bool HasDependentArg = false;
1411 for (unsigned i = 0; i < NumArgs; i++)
1412 HasDependentArg |= Args[i]->isTypeDependent();
1413
Chandler Carruth894aed92010-12-06 09:23:57 +00001414 Expr *Init;
Eli Friedman0f2b97d2010-07-24 21:19:15 +00001415 if (Member->getType()->isDependentType() || HasDependentArg) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001416 // Can't check initialization for a member of dependent type or when
1417 // any of the arguments are type-dependent expressions.
Chandler Carruth894aed92010-12-06 09:23:57 +00001418 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1419 RParenLoc);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001420
1421 // Erase any temporaries within this evaluation context; we're not
1422 // going to track them in the AST, since we'll be rebuilding the
1423 // ASTs during template instantiation.
1424 ExprTemporaries.erase(
1425 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1426 ExprTemporaries.end());
Chandler Carruth894aed92010-12-06 09:23:57 +00001427 } else {
1428 // Initialize the member.
1429 InitializedEntity MemberEntity =
1430 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
1431 : InitializedEntity::InitializeMember(IndirectMember, 0);
1432 InitializationKind Kind =
1433 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc);
John McCallb4eb64d2010-10-08 02:01:28 +00001434
Chandler Carruth894aed92010-12-06 09:23:57 +00001435 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
1436
1437 ExprResult MemberInit =
1438 InitSeq.Perform(*this, MemberEntity, Kind,
1439 MultiExprArg(*this, Args, NumArgs), 0);
1440 if (MemberInit.isInvalid())
1441 return true;
1442
1443 CheckImplicitConversions(MemberInit.get(), LParenLoc);
1444
1445 // C++0x [class.base.init]p7:
1446 // The initialization of each base and member constitutes a
1447 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00001448 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Chandler Carruth894aed92010-12-06 09:23:57 +00001449 if (MemberInit.isInvalid())
1450 return true;
1451
1452 // If we are in a dependent context, template instantiation will
1453 // perform this type-checking again. Just save the arguments that we
1454 // received in a ParenListExpr.
1455 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1456 // of the information that we have about the member
1457 // initializer. However, deconstructing the ASTs is a dicey process,
1458 // and this approach is far more likely to get the corner cases right.
1459 if (CurContext->isDependentContext())
1460 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1461 RParenLoc);
1462 else
1463 Init = MemberInit.get();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001464 }
1465
Chandler Carruth894aed92010-12-06 09:23:57 +00001466 if (DirectMember) {
Sean Huntcbb67482011-01-08 20:30:50 +00001467 return new (Context) CXXCtorInitializer(Context, DirectMember,
Chandler Carruth894aed92010-12-06 09:23:57 +00001468 IdLoc, LParenLoc, Init,
1469 RParenLoc);
1470 } else {
Sean Huntcbb67482011-01-08 20:30:50 +00001471 return new (Context) CXXCtorInitializer(Context, IndirectMember,
Chandler Carruth894aed92010-12-06 09:23:57 +00001472 IdLoc, LParenLoc, Init,
1473 RParenLoc);
1474 }
Eli Friedman59c04372009-07-29 19:44:27 +00001475}
1476
John McCallf312b1e2010-08-26 23:41:50 +00001477MemInitResult
Sean Hunt97fcc492011-01-08 19:20:43 +00001478Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo,
1479 Expr **Args, unsigned NumArgs,
1480 SourceLocation LParenLoc,
1481 SourceLocation RParenLoc,
1482 CXXRecordDecl *ClassDecl,
1483 SourceLocation EllipsisLoc) {
1484 SourceLocation Loc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
1485 if (!LangOpts.CPlusPlus0x)
1486 return Diag(Loc, diag::err_delegation_0x_only)
1487 << TInfo->getTypeLoc().getLocalSourceRange();
1488
1489 return Diag(Loc, diag::err_delegation_unimplemented)
1490 << TInfo->getTypeLoc().getLocalSourceRange();
1491}
1492
1493MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00001494Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Douglas Gregor802ab452009-12-02 22:36:29 +00001495 Expr **Args, unsigned NumArgs,
1496 SourceLocation LParenLoc, SourceLocation RParenLoc,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001497 CXXRecordDecl *ClassDecl,
1498 SourceLocation EllipsisLoc) {
Eli Friedman59c04372009-07-29 19:44:27 +00001499 bool HasDependentArg = false;
1500 for (unsigned i = 0; i < NumArgs; i++)
1501 HasDependentArg |= Args[i]->isTypeDependent();
1502
Douglas Gregor3956b1a2010-06-16 16:03:14 +00001503 SourceLocation BaseLoc
1504 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
1505
1506 if (!BaseType->isDependentType() && !BaseType->isRecordType())
1507 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1508 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
1509
1510 // C++ [class.base.init]p2:
1511 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00001512 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00001513 // of that class, the mem-initializer is ill-formed. A
1514 // mem-initializer-list can initialize a base class using any
1515 // name that denotes that base class type.
1516 bool Dependent = BaseType->isDependentType() || HasDependentArg;
1517
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001518 if (EllipsisLoc.isValid()) {
1519 // This is a pack expansion.
1520 if (!BaseType->containsUnexpandedParameterPack()) {
1521 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1522 << SourceRange(BaseLoc, RParenLoc);
1523
1524 EllipsisLoc = SourceLocation();
1525 }
1526 } else {
1527 // Check for any unexpanded parameter packs.
1528 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
1529 return true;
1530
1531 for (unsigned I = 0; I != NumArgs; ++I)
1532 if (DiagnoseUnexpandedParameterPack(Args[I]))
1533 return true;
1534 }
1535
Douglas Gregor3956b1a2010-06-16 16:03:14 +00001536 // Check for direct and virtual base classes.
1537 const CXXBaseSpecifier *DirectBaseSpec = 0;
1538 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1539 if (!Dependent) {
Sean Hunt97fcc492011-01-08 19:20:43 +00001540 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
1541 BaseType))
1542 return BuildDelegatingInitializer(BaseTInfo, Args, NumArgs,
1543 LParenLoc, RParenLoc, ClassDecl,
1544 EllipsisLoc);
1545
Douglas Gregor3956b1a2010-06-16 16:03:14 +00001546 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1547 VirtualBaseSpec);
1548
1549 // C++ [base.class.init]p2:
1550 // Unless the mem-initializer-id names a nonstatic data member of the
1551 // constructor's class or a direct or virtual base of that class, the
1552 // mem-initializer is ill-formed.
1553 if (!DirectBaseSpec && !VirtualBaseSpec) {
1554 // If the class has any dependent bases, then it's possible that
1555 // one of those types will resolve to the same type as
1556 // BaseType. Therefore, just treat this as a dependent base
1557 // class initialization. FIXME: Should we try to check the
1558 // initialization anyway? It seems odd.
1559 if (ClassDecl->hasAnyDependentBases())
1560 Dependent = true;
1561 else
1562 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1563 << BaseType << Context.getTypeDeclType(ClassDecl)
1564 << BaseTInfo->getTypeLoc().getLocalSourceRange();
1565 }
1566 }
1567
1568 if (Dependent) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001569 // Can't check initialization for a base of dependent type or when
1570 // any of the arguments are type-dependent expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00001571 ExprResult BaseInit
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001572 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1573 RParenLoc));
Eli Friedman59c04372009-07-29 19:44:27 +00001574
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001575 // Erase any temporaries within this evaluation context; we're not
1576 // going to track them in the AST, since we'll be rebuilding the
1577 // ASTs during template instantiation.
1578 ExprTemporaries.erase(
1579 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1580 ExprTemporaries.end());
Mike Stump1eb44332009-09-09 15:08:12 +00001581
Sean Huntcbb67482011-01-08 20:30:50 +00001582 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001583 /*IsVirtual=*/false,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001584 LParenLoc,
1585 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001586 RParenLoc,
1587 EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001588 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001589
1590 // C++ [base.class.init]p2:
1591 // If a mem-initializer-id is ambiguous because it designates both
1592 // a direct non-virtual base class and an inherited virtual base
1593 // class, the mem-initializer is ill-formed.
1594 if (DirectBaseSpec && VirtualBaseSpec)
1595 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00001596 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001597
1598 CXXBaseSpecifier *BaseSpec
1599 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
1600 if (!BaseSpec)
1601 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1602
1603 // Initialize the base.
1604 InitializedEntity BaseEntity =
Anders Carlsson711f34a2010-04-21 19:52:01 +00001605 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001606 InitializationKind Kind =
1607 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc);
1608
1609 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
1610
John McCall60d7b3a2010-08-24 06:29:42 +00001611 ExprResult BaseInit =
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001612 InitSeq.Perform(*this, BaseEntity, Kind,
John McCallca0408f2010-08-23 06:44:23 +00001613 MultiExprArg(*this, Args, NumArgs), 0);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001614 if (BaseInit.isInvalid())
1615 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00001616
1617 CheckImplicitConversions(BaseInit.get(), LParenLoc);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001618
1619 // C++0x [class.base.init]p7:
1620 // The initialization of each base and member constitutes a
1621 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00001622 BaseInit = MaybeCreateExprWithCleanups(BaseInit);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001623 if (BaseInit.isInvalid())
1624 return true;
1625
1626 // If we are in a dependent context, template instantiation will
1627 // perform this type-checking again. Just save the arguments that we
1628 // received in a ParenListExpr.
1629 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1630 // of the information that we have about the base
1631 // initializer. However, deconstructing the ASTs is a dicey process,
1632 // and this approach is far more likely to get the corner cases right.
1633 if (CurContext->isDependentContext()) {
John McCall60d7b3a2010-08-24 06:29:42 +00001634 ExprResult Init
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001635 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1636 RParenLoc));
Sean Huntcbb67482011-01-08 20:30:50 +00001637 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001638 BaseSpec->isVirtual(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001639 LParenLoc,
1640 Init.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001641 RParenLoc,
1642 EllipsisLoc);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001643 }
1644
Sean Huntcbb67482011-01-08 20:30:50 +00001645 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001646 BaseSpec->isVirtual(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001647 LParenLoc,
1648 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001649 RParenLoc,
1650 EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001651}
1652
Anders Carlssone5ef7402010-04-23 03:10:23 +00001653/// ImplicitInitializerKind - How an implicit base or member initializer should
1654/// initialize its base or member.
1655enum ImplicitInitializerKind {
1656 IIK_Default,
1657 IIK_Copy,
1658 IIK_Move
1659};
1660
Anders Carlssondefefd22010-04-23 02:00:02 +00001661static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001662BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00001663 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00001664 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00001665 bool IsInheritedVirtualBase,
Sean Huntcbb67482011-01-08 20:30:50 +00001666 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00001667 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00001668 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
1669 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00001670
John McCall60d7b3a2010-08-24 06:29:42 +00001671 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00001672
1673 switch (ImplicitInitKind) {
1674 case IIK_Default: {
1675 InitializationKind InitKind
1676 = InitializationKind::CreateDefault(Constructor->getLocation());
1677 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
1678 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00001679 MultiExprArg(SemaRef, 0, 0));
Anders Carlssone5ef7402010-04-23 03:10:23 +00001680 break;
1681 }
Anders Carlsson84688f22010-04-20 23:11:20 +00001682
Anders Carlssone5ef7402010-04-23 03:10:23 +00001683 case IIK_Copy: {
1684 ParmVarDecl *Param = Constructor->getParamDecl(0);
1685 QualType ParamType = Param->getType().getNonReferenceType();
1686
1687 Expr *CopyCtorArg =
1688 DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param,
John McCallf89e55a2010-11-18 06:31:45 +00001689 Constructor->getLocation(), ParamType,
1690 VK_LValue, 0);
Anders Carlssone5ef7402010-04-23 03:10:23 +00001691
Anders Carlssonc7957502010-04-24 22:02:54 +00001692 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00001693 QualType ArgTy =
1694 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
1695 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00001696
1697 CXXCastPath BasePath;
1698 BasePath.push_back(BaseSpec);
Sebastian Redl906082e2010-07-20 04:20:21 +00001699 SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
John McCall2de56d12010-08-25 11:45:40 +00001700 CK_UncheckedDerivedToBase,
John McCall5baba9d2010-08-25 10:28:54 +00001701 VK_LValue, &BasePath);
Anders Carlssonc7957502010-04-24 22:02:54 +00001702
Anders Carlssone5ef7402010-04-23 03:10:23 +00001703 InitializationKind InitKind
1704 = InitializationKind::CreateDirect(Constructor->getLocation(),
1705 SourceLocation(), SourceLocation());
1706 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
1707 &CopyCtorArg, 1);
1708 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00001709 MultiExprArg(&CopyCtorArg, 1));
Anders Carlssone5ef7402010-04-23 03:10:23 +00001710 break;
1711 }
Anders Carlsson84688f22010-04-20 23:11:20 +00001712
Anders Carlssone5ef7402010-04-23 03:10:23 +00001713 case IIK_Move:
1714 assert(false && "Unhandled initializer kind!");
1715 }
John McCall9ae2f072010-08-23 23:25:46 +00001716
Douglas Gregor53c374f2010-12-07 00:41:46 +00001717 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00001718 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00001719 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00001720
Anders Carlssondefefd22010-04-23 02:00:02 +00001721 CXXBaseInit =
Sean Huntcbb67482011-01-08 20:30:50 +00001722 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlsson84688f22010-04-20 23:11:20 +00001723 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
1724 SourceLocation()),
1725 BaseSpec->isVirtual(),
1726 SourceLocation(),
1727 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001728 SourceLocation(),
Anders Carlsson84688f22010-04-20 23:11:20 +00001729 SourceLocation());
1730
Anders Carlssondefefd22010-04-23 02:00:02 +00001731 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00001732}
1733
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001734static bool
1735BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00001736 ImplicitInitializerKind ImplicitInitKind,
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001737 FieldDecl *Field,
Sean Huntcbb67482011-01-08 20:30:50 +00001738 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00001739 if (Field->isInvalidDecl())
1740 return true;
1741
Chandler Carruthf186b542010-06-29 23:50:44 +00001742 SourceLocation Loc = Constructor->getLocation();
1743
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001744 if (ImplicitInitKind == IIK_Copy) {
1745 ParmVarDecl *Param = Constructor->getParamDecl(0);
1746 QualType ParamType = Param->getType().getNonReferenceType();
1747
1748 Expr *MemberExprBase =
1749 DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param,
John McCallf89e55a2010-11-18 06:31:45 +00001750 Loc, ParamType, VK_LValue, 0);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001751
1752 // Build a reference to this field within the parameter.
1753 CXXScopeSpec SS;
1754 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
1755 Sema::LookupMemberName);
1756 MemberLookup.addDecl(Field, AS_public);
1757 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00001758 ExprResult CopyCtorArg
John McCall9ae2f072010-08-23 23:25:46 +00001759 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001760 ParamType, Loc,
1761 /*IsArrow=*/false,
1762 SS,
1763 /*FirstQualifierInScope=*/0,
1764 MemberLookup,
1765 /*TemplateArgs=*/0);
1766 if (CopyCtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001767 return true;
1768
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001769 // When the field we are copying is an array, create index variables for
1770 // each dimension of the array. We use these index variables to subscript
1771 // the source array, and other clients (e.g., CodeGen) will perform the
1772 // necessary iteration with these index variables.
1773 llvm::SmallVector<VarDecl *, 4> IndexVariables;
1774 QualType BaseType = Field->getType();
1775 QualType SizeType = SemaRef.Context.getSizeType();
1776 while (const ConstantArrayType *Array
1777 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
1778 // Create the iteration variable for this array index.
1779 IdentifierInfo *IterationVarName = 0;
1780 {
1781 llvm::SmallString<8> Str;
1782 llvm::raw_svector_ostream OS(Str);
1783 OS << "__i" << IndexVariables.size();
1784 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
1785 }
1786 VarDecl *IterationVar
1787 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc,
1788 IterationVarName, SizeType,
1789 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00001790 SC_None, SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001791 IndexVariables.push_back(IterationVar);
1792
1793 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00001794 ExprResult IterationVarRef
John McCallf89e55a2010-11-18 06:31:45 +00001795 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001796 assert(!IterationVarRef.isInvalid() &&
1797 "Reference to invented variable cannot fail!");
1798
1799 // Subscript the array with this iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00001800 CopyCtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CopyCtorArg.take(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001801 Loc,
John McCall9ae2f072010-08-23 23:25:46 +00001802 IterationVarRef.take(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001803 Loc);
1804 if (CopyCtorArg.isInvalid())
1805 return true;
1806
1807 BaseType = Array->getElementType();
1808 }
1809
1810 // Construct the entity that we will be initializing. For an array, this
1811 // will be first element in the array, which may require several levels
1812 // of array-subscript entities.
1813 llvm::SmallVector<InitializedEntity, 4> Entities;
1814 Entities.reserve(1 + IndexVariables.size());
1815 Entities.push_back(InitializedEntity::InitializeMember(Field));
1816 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
1817 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
1818 0,
1819 Entities.back()));
1820
1821 // Direct-initialize to use the copy constructor.
1822 InitializationKind InitKind =
1823 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
1824
1825 Expr *CopyCtorArgE = CopyCtorArg.takeAs<Expr>();
1826 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
1827 &CopyCtorArgE, 1);
1828
John McCall60d7b3a2010-08-24 06:29:42 +00001829 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001830 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00001831 MultiExprArg(&CopyCtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00001832 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001833 if (MemberInit.isInvalid())
1834 return true;
1835
1836 CXXMemberInit
Sean Huntcbb67482011-01-08 20:30:50 +00001837 = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001838 MemberInit.takeAs<Expr>(), Loc,
1839 IndexVariables.data(),
1840 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00001841 return false;
1842 }
1843
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001844 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
1845
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001846 QualType FieldBaseElementType =
1847 SemaRef.Context.getBaseElementType(Field->getType());
1848
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001849 if (FieldBaseElementType->isRecordType()) {
1850 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001851 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00001852 InitializationKind::CreateDefault(Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001853
1854 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00001855 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00001856 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCall9ae2f072010-08-23 23:25:46 +00001857
Douglas Gregor53c374f2010-12-07 00:41:46 +00001858 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001859 if (MemberInit.isInvalid())
1860 return true;
1861
1862 CXXMemberInit =
Sean Huntcbb67482011-01-08 20:30:50 +00001863 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Chandler Carruthf186b542010-06-29 23:50:44 +00001864 Field, Loc, Loc,
John McCall9ae2f072010-08-23 23:25:46 +00001865 MemberInit.get(),
Chandler Carruthf186b542010-06-29 23:50:44 +00001866 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001867 return false;
1868 }
Anders Carlsson114a2972010-04-23 03:07:47 +00001869
1870 if (FieldBaseElementType->isReferenceType()) {
1871 SemaRef.Diag(Constructor->getLocation(),
1872 diag::err_uninitialized_member_in_ctor)
1873 << (int)Constructor->isImplicit()
1874 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1875 << 0 << Field->getDeclName();
1876 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1877 return true;
1878 }
1879
1880 if (FieldBaseElementType.isConstQualified()) {
1881 SemaRef.Diag(Constructor->getLocation(),
1882 diag::err_uninitialized_member_in_ctor)
1883 << (int)Constructor->isImplicit()
1884 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1885 << 1 << Field->getDeclName();
1886 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1887 return true;
1888 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001889
1890 // Nothing to initialize.
1891 CXXMemberInit = 0;
1892 return false;
1893}
John McCallf1860e52010-05-20 23:23:51 +00001894
1895namespace {
1896struct BaseAndFieldInfo {
1897 Sema &S;
1898 CXXConstructorDecl *Ctor;
1899 bool AnyErrorsInInits;
1900 ImplicitInitializerKind IIK;
Sean Huntcbb67482011-01-08 20:30:50 +00001901 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
1902 llvm::SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallf1860e52010-05-20 23:23:51 +00001903
1904 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
1905 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
1906 // FIXME: Handle implicit move constructors.
1907 if (Ctor->isImplicit() && Ctor->isCopyConstructor())
1908 IIK = IIK_Copy;
1909 else
1910 IIK = IIK_Default;
1911 }
1912};
1913}
1914
1915static bool CollectFieldInitializer(BaseAndFieldInfo &Info,
1916 FieldDecl *Top, FieldDecl *Field) {
1917
Chandler Carruthe861c602010-06-30 02:59:29 +00001918 // Overwhelmingly common case: we have a direct initializer for this field.
Sean Huntcbb67482011-01-08 20:30:50 +00001919 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00001920 Info.AllToInit.push_back(Init);
John McCallf1860e52010-05-20 23:23:51 +00001921 return false;
1922 }
1923
1924 if (Info.IIK == IIK_Default && Field->isAnonymousStructOrUnion()) {
1925 const RecordType *FieldClassType = Field->getType()->getAs<RecordType>();
1926 assert(FieldClassType && "anonymous struct/union without record type");
John McCallf1860e52010-05-20 23:23:51 +00001927 CXXRecordDecl *FieldClassDecl
1928 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Chandler Carruthe861c602010-06-30 02:59:29 +00001929
1930 // Even though union members never have non-trivial default
1931 // constructions in C++03, we still build member initializers for aggregate
1932 // record types which can be union members, and C++0x allows non-trivial
1933 // default constructors for union members, so we ensure that only one
1934 // member is initialized for these.
1935 if (FieldClassDecl->isUnion()) {
1936 // First check for an explicit initializer for one field.
1937 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
1938 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
Sean Huntcbb67482011-01-08 20:30:50 +00001939 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(*FA)) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00001940 Info.AllToInit.push_back(Init);
Chandler Carruthe861c602010-06-30 02:59:29 +00001941
1942 // Once we've initialized a field of an anonymous union, the union
1943 // field in the class is also initialized, so exit immediately.
1944 return false;
Argyrios Kyrtzidis881b36c2010-08-16 17:27:13 +00001945 } else if ((*FA)->isAnonymousStructOrUnion()) {
1946 if (CollectFieldInitializer(Info, Top, *FA))
1947 return true;
Chandler Carruthe861c602010-06-30 02:59:29 +00001948 }
1949 }
1950
1951 // Fallthrough and construct a default initializer for the union as
1952 // a whole, which can call its default constructor if such a thing exists
1953 // (C++0x perhaps). FIXME: It's not clear that this is the correct
1954 // behavior going forward with C++0x, when anonymous unions there are
1955 // finalized, we should revisit this.
1956 } else {
1957 // For structs, we simply descend through to initialize all members where
1958 // necessary.
1959 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
1960 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1961 if (CollectFieldInitializer(Info, Top, *FA))
1962 return true;
1963 }
1964 }
John McCallf1860e52010-05-20 23:23:51 +00001965 }
1966
1967 // Don't try to build an implicit initializer if there were semantic
1968 // errors in any of the initializers (and therefore we might be
1969 // missing some that the user actually wrote).
1970 if (Info.AnyErrorsInInits)
1971 return false;
1972
Sean Huntcbb67482011-01-08 20:30:50 +00001973 CXXCtorInitializer *Init = 0;
John McCallf1860e52010-05-20 23:23:51 +00001974 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, Init))
1975 return true;
John McCallf1860e52010-05-20 23:23:51 +00001976
Francois Pichet00eb3f92010-12-04 09:14:42 +00001977 if (Init)
1978 Info.AllToInit.push_back(Init);
1979
John McCallf1860e52010-05-20 23:23:51 +00001980 return false;
1981}
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001982
Eli Friedman80c30da2009-11-09 19:20:36 +00001983bool
Sean Huntcbb67482011-01-08 20:30:50 +00001984Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
1985 CXXCtorInitializer **Initializers,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001986 unsigned NumInitializers,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001987 bool AnyErrors) {
John McCalld6ca8da2010-04-10 07:37:23 +00001988 if (Constructor->getDeclContext()->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001989 // Just store the initializers as written, they will be checked during
1990 // instantiation.
1991 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00001992 Constructor->setNumCtorInitializers(NumInitializers);
1993 CXXCtorInitializer **baseOrMemberInitializers =
1994 new (Context) CXXCtorInitializer*[NumInitializers];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001995 memcpy(baseOrMemberInitializers, Initializers,
Sean Huntcbb67482011-01-08 20:30:50 +00001996 NumInitializers * sizeof(CXXCtorInitializer*));
1997 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001998 }
1999
2000 return false;
2001 }
2002
John McCallf1860e52010-05-20 23:23:51 +00002003 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00002004
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002005 // We need to build the initializer AST according to order of construction
2006 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00002007 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00002008 if (!ClassDecl)
2009 return true;
2010
Eli Friedman80c30da2009-11-09 19:20:36 +00002011 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002012
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002013 for (unsigned i = 0; i < NumInitializers; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00002014 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002015
2016 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00002017 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002018 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00002019 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002020 }
2021
Anders Carlsson711f34a2010-04-21 19:52:01 +00002022 // Keep track of the direct virtual bases.
2023 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
2024 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
2025 E = ClassDecl->bases_end(); I != E; ++I) {
2026 if (I->isVirtual())
2027 DirectVBases.insert(I);
2028 }
2029
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002030 // Push virtual bases before others.
2031 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2032 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2033
Sean Huntcbb67482011-01-08 20:30:50 +00002034 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00002035 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
2036 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002037 } else if (!AnyErrors) {
Anders Carlsson711f34a2010-04-21 19:52:01 +00002038 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00002039 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00002040 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002041 VBase, IsInheritedVirtualBase,
2042 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002043 HadError = true;
2044 continue;
2045 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002046
John McCallf1860e52010-05-20 23:23:51 +00002047 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002048 }
2049 }
Mike Stump1eb44332009-09-09 15:08:12 +00002050
John McCallf1860e52010-05-20 23:23:51 +00002051 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002052 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2053 E = ClassDecl->bases_end(); Base != E; ++Base) {
2054 // Virtuals are in the virtual base list and already constructed.
2055 if (Base->isVirtual())
2056 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00002057
Sean Huntcbb67482011-01-08 20:30:50 +00002058 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00002059 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
2060 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002061 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00002062 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00002063 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002064 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00002065 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002066 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002067 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002068 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00002069
John McCallf1860e52010-05-20 23:23:51 +00002070 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002071 }
2072 }
Mike Stump1eb44332009-09-09 15:08:12 +00002073
John McCallf1860e52010-05-20 23:23:51 +00002074 // Fields.
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002075 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00002076 E = ClassDecl->field_end(); Field != E; ++Field) {
2077 if ((*Field)->getType()->isIncompleteArrayType()) {
2078 assert(ClassDecl->hasFlexibleArrayMember() &&
2079 "Incomplete array type is not valid");
2080 continue;
2081 }
John McCallf1860e52010-05-20 23:23:51 +00002082 if (CollectFieldInitializer(Info, *Field, *Field))
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002083 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00002084 }
Mike Stump1eb44332009-09-09 15:08:12 +00002085
John McCallf1860e52010-05-20 23:23:51 +00002086 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002087 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00002088 Constructor->setNumCtorInitializers(NumInitializers);
2089 CXXCtorInitializer **baseOrMemberInitializers =
2090 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00002091 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00002092 NumInitializers * sizeof(CXXCtorInitializer*));
2093 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00002094
John McCallef027fe2010-03-16 21:39:52 +00002095 // Constructors implicitly reference the base and member
2096 // destructors.
2097 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
2098 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002099 }
Eli Friedman80c30da2009-11-09 19:20:36 +00002100
2101 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002102}
2103
Eli Friedman6347f422009-07-21 19:28:10 +00002104static void *GetKeyForTopLevelField(FieldDecl *Field) {
2105 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00002106 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00002107 if (RT->getDecl()->isAnonymousStructOrUnion())
2108 return static_cast<void *>(RT->getDecl());
2109 }
2110 return static_cast<void *>(Field);
2111}
2112
Anders Carlssonea356fb2010-04-02 05:42:15 +00002113static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCallf4c73712011-01-19 06:33:43 +00002114 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssoncdc83c72009-09-01 06:22:14 +00002115}
2116
Anders Carlssonea356fb2010-04-02 05:42:15 +00002117static void *GetKeyForMember(ASTContext &Context,
Sean Huntcbb67482011-01-08 20:30:50 +00002118 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002119 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00002120 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00002121
Eli Friedman6347f422009-07-21 19:28:10 +00002122 // For fields injected into the class via declaration of an anonymous union,
2123 // use its anonymous union class declaration as the unique key.
Francois Pichet00eb3f92010-12-04 09:14:42 +00002124 FieldDecl *Field = Member->getAnyMember();
2125
John McCall3c3ccdb2010-04-10 09:28:51 +00002126 // If the field is a member of an anonymous struct or union, our key
2127 // is the anonymous record decl that's a direct child of the class.
Anders Carlssonee11b2d2010-03-30 16:19:37 +00002128 RecordDecl *RD = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00002129 if (RD->isAnonymousStructOrUnion()) {
2130 while (true) {
2131 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
2132 if (Parent->isAnonymousStructOrUnion())
2133 RD = Parent;
2134 else
2135 break;
2136 }
2137
Anders Carlssonee11b2d2010-03-30 16:19:37 +00002138 return static_cast<void *>(RD);
John McCall3c3ccdb2010-04-10 09:28:51 +00002139 }
Mike Stump1eb44332009-09-09 15:08:12 +00002140
Anders Carlsson8f1a2402010-03-30 15:39:27 +00002141 return static_cast<void *>(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00002142}
2143
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002144static void
2145DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson071d6102010-04-02 03:38:04 +00002146 const CXXConstructorDecl *Constructor,
Sean Huntcbb67482011-01-08 20:30:50 +00002147 CXXCtorInitializer **Inits,
John McCalld6ca8da2010-04-10 07:37:23 +00002148 unsigned NumInits) {
2149 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00002150 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002151
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00002152 // Don't check initializers order unless the warning is enabled at the
2153 // location of at least one initializer.
2154 bool ShouldCheckOrder = false;
2155 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00002156 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00002157 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
2158 Init->getSourceLocation())
2159 != Diagnostic::Ignored) {
2160 ShouldCheckOrder = true;
2161 break;
2162 }
2163 }
2164 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002165 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002166
John McCalld6ca8da2010-04-10 07:37:23 +00002167 // Build the list of bases and members in the order that they'll
2168 // actually be initialized. The explicit initializers should be in
2169 // this same order but may be missing things.
2170 llvm::SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00002171
Anders Carlsson071d6102010-04-02 03:38:04 +00002172 const CXXRecordDecl *ClassDecl = Constructor->getParent();
2173
John McCalld6ca8da2010-04-10 07:37:23 +00002174 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00002175 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002176 ClassDecl->vbases_begin(),
2177 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00002178 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002179
John McCalld6ca8da2010-04-10 07:37:23 +00002180 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00002181 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002182 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002183 if (Base->isVirtual())
2184 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00002185 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002186 }
Mike Stump1eb44332009-09-09 15:08:12 +00002187
John McCalld6ca8da2010-04-10 07:37:23 +00002188 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002189 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2190 E = ClassDecl->field_end(); Field != E; ++Field)
John McCalld6ca8da2010-04-10 07:37:23 +00002191 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Mike Stump1eb44332009-09-09 15:08:12 +00002192
John McCalld6ca8da2010-04-10 07:37:23 +00002193 unsigned NumIdealInits = IdealInitKeys.size();
2194 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00002195
Sean Huntcbb67482011-01-08 20:30:50 +00002196 CXXCtorInitializer *PrevInit = 0;
John McCalld6ca8da2010-04-10 07:37:23 +00002197 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00002198 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichet00eb3f92010-12-04 09:14:42 +00002199 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00002200
2201 // Scan forward to try to find this initializer in the idealized
2202 // initializers list.
2203 for (; IdealIndex != NumIdealInits; ++IdealIndex)
2204 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002205 break;
John McCalld6ca8da2010-04-10 07:37:23 +00002206
2207 // If we didn't find this initializer, it must be because we
2208 // scanned past it on a previous iteration. That can only
2209 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00002210 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00002211 Sema::SemaDiagnosticBuilder D =
2212 SemaRef.Diag(PrevInit->getSourceLocation(),
2213 diag::warn_initializer_out_of_order);
2214
Francois Pichet00eb3f92010-12-04 09:14:42 +00002215 if (PrevInit->isAnyMemberInitializer())
2216 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00002217 else
2218 D << 1 << PrevInit->getBaseClassInfo()->getType();
2219
Francois Pichet00eb3f92010-12-04 09:14:42 +00002220 if (Init->isAnyMemberInitializer())
2221 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00002222 else
2223 D << 1 << Init->getBaseClassInfo()->getType();
2224
2225 // Move back to the initializer's location in the ideal list.
2226 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
2227 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002228 break;
John McCalld6ca8da2010-04-10 07:37:23 +00002229
2230 assert(IdealIndex != NumIdealInits &&
2231 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00002232 }
John McCalld6ca8da2010-04-10 07:37:23 +00002233
2234 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00002235 }
Anders Carlssona7b35212009-03-25 02:58:17 +00002236}
2237
John McCall3c3ccdb2010-04-10 09:28:51 +00002238namespace {
2239bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00002240 CXXCtorInitializer *Init,
2241 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00002242 if (!PrevInit) {
2243 PrevInit = Init;
2244 return false;
2245 }
2246
2247 if (FieldDecl *Field = Init->getMember())
2248 S.Diag(Init->getSourceLocation(),
2249 diag::err_multiple_mem_initialization)
2250 << Field->getDeclName()
2251 << Init->getSourceRange();
2252 else {
John McCallf4c73712011-01-19 06:33:43 +00002253 const Type *BaseClass = Init->getBaseClass();
John McCall3c3ccdb2010-04-10 09:28:51 +00002254 assert(BaseClass && "neither field nor base");
2255 S.Diag(Init->getSourceLocation(),
2256 diag::err_multiple_base_initialization)
2257 << QualType(BaseClass, 0)
2258 << Init->getSourceRange();
2259 }
2260 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
2261 << 0 << PrevInit->getSourceRange();
2262
2263 return true;
2264}
2265
Sean Huntcbb67482011-01-08 20:30:50 +00002266typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00002267typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
2268
2269bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00002270 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00002271 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002272 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00002273 RecordDecl *Parent = Field->getParent();
2274 if (!Parent->isAnonymousStructOrUnion())
2275 return false;
2276
2277 NamedDecl *Child = Field;
2278 do {
2279 if (Parent->isUnion()) {
2280 UnionEntry &En = Unions[Parent];
2281 if (En.first && En.first != Child) {
2282 S.Diag(Init->getSourceLocation(),
2283 diag::err_multiple_mem_union_initialization)
2284 << Field->getDeclName()
2285 << Init->getSourceRange();
2286 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
2287 << 0 << En.second->getSourceRange();
2288 return true;
2289 } else if (!En.first) {
2290 En.first = Child;
2291 En.second = Init;
2292 }
2293 }
2294
2295 Child = Parent;
2296 Parent = cast<RecordDecl>(Parent->getDeclContext());
2297 } while (Parent->isAnonymousStructOrUnion());
2298
2299 return false;
2300}
2301}
2302
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002303/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00002304void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002305 SourceLocation ColonLoc,
2306 MemInitTy **meminits, unsigned NumMemInits,
2307 bool AnyErrors) {
2308 if (!ConstructorDecl)
2309 return;
2310
2311 AdjustDeclIfTemplate(ConstructorDecl);
2312
2313 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002314 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002315
2316 if (!Constructor) {
2317 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
2318 return;
2319 }
2320
Sean Huntcbb67482011-01-08 20:30:50 +00002321 CXXCtorInitializer **MemInits =
2322 reinterpret_cast<CXXCtorInitializer **>(meminits);
John McCall3c3ccdb2010-04-10 09:28:51 +00002323
2324 // Mapping for the duplicate initializers check.
2325 // For member initializers, this is keyed with a FieldDecl*.
2326 // For base initializers, this is keyed with a Type*.
Sean Huntcbb67482011-01-08 20:30:50 +00002327 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00002328
2329 // Mapping for the inconsistent anonymous-union initializers check.
2330 RedundantUnionMap MemberUnions;
2331
Anders Carlssonea356fb2010-04-02 05:42:15 +00002332 bool HadError = false;
2333 for (unsigned i = 0; i < NumMemInits; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00002334 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002335
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00002336 // Set the source order index.
2337 Init->setSourceOrder(i);
2338
Francois Pichet00eb3f92010-12-04 09:14:42 +00002339 if (Init->isAnyMemberInitializer()) {
2340 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00002341 if (CheckRedundantInit(*this, Init, Members[Field]) ||
2342 CheckRedundantUnionInit(*this, Init, MemberUnions))
2343 HadError = true;
2344 } else {
2345 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
2346 if (CheckRedundantInit(*this, Init, Members[Key]))
2347 HadError = true;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002348 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002349 }
2350
Anders Carlssonea356fb2010-04-02 05:42:15 +00002351 if (HadError)
2352 return;
2353
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002354 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00002355
Sean Huntcbb67482011-01-08 20:30:50 +00002356 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002357}
2358
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002359void
John McCallef027fe2010-03-16 21:39:52 +00002360Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
2361 CXXRecordDecl *ClassDecl) {
2362 // Ignore dependent contexts.
2363 if (ClassDecl->isDependentContext())
Anders Carlsson9f853df2009-11-17 04:44:12 +00002364 return;
John McCall58e6f342010-03-16 05:22:47 +00002365
2366 // FIXME: all the access-control diagnostics are positioned on the
2367 // field/base declaration. That's probably good; that said, the
2368 // user might reasonably want to know why the destructor is being
2369 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00002370
Anders Carlsson9f853df2009-11-17 04:44:12 +00002371 // Non-static data members.
2372 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
2373 E = ClassDecl->field_end(); I != E; ++I) {
2374 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00002375 if (Field->isInvalidDecl())
2376 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00002377 QualType FieldType = Context.getBaseElementType(Field->getType());
2378
2379 const RecordType* RT = FieldType->getAs<RecordType>();
2380 if (!RT)
2381 continue;
2382
2383 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
2384 if (FieldClassDecl->hasTrivialDestructor())
2385 continue;
2386
Douglas Gregordb89f282010-07-01 22:47:18 +00002387 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
John McCall58e6f342010-03-16 05:22:47 +00002388 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002389 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00002390 << Field->getDeclName()
2391 << FieldType);
2392
John McCallef027fe2010-03-16 21:39:52 +00002393 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00002394 }
2395
John McCall58e6f342010-03-16 05:22:47 +00002396 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
2397
Anders Carlsson9f853df2009-11-17 04:44:12 +00002398 // Bases.
2399 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2400 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00002401 // Bases are always records in a well-formed non-dependent class.
2402 const RecordType *RT = Base->getType()->getAs<RecordType>();
2403
2404 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00002405 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00002406 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00002407
2408 // Ignore trivial destructors.
John McCall58e6f342010-03-16 05:22:47 +00002409 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson9f853df2009-11-17 04:44:12 +00002410 if (BaseClassDecl->hasTrivialDestructor())
2411 continue;
John McCall58e6f342010-03-16 05:22:47 +00002412
Douglas Gregordb89f282010-07-01 22:47:18 +00002413 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
John McCall58e6f342010-03-16 05:22:47 +00002414
2415 // FIXME: caret should be on the start of the class name
2416 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002417 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00002418 << Base->getType()
2419 << Base->getSourceRange());
Anders Carlsson9f853df2009-11-17 04:44:12 +00002420
John McCallef027fe2010-03-16 21:39:52 +00002421 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00002422 }
2423
2424 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002425 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2426 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00002427
2428 // Bases are always records in a well-formed non-dependent class.
2429 const RecordType *RT = VBase->getType()->getAs<RecordType>();
2430
2431 // Ignore direct virtual bases.
2432 if (DirectVirtualBases.count(RT))
2433 continue;
2434
Anders Carlsson9f853df2009-11-17 04:44:12 +00002435 // Ignore trivial destructors.
John McCall58e6f342010-03-16 05:22:47 +00002436 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002437 if (BaseClassDecl->hasTrivialDestructor())
2438 continue;
John McCall58e6f342010-03-16 05:22:47 +00002439
Douglas Gregordb89f282010-07-01 22:47:18 +00002440 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
John McCall58e6f342010-03-16 05:22:47 +00002441 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002442 PDiag(diag::err_access_dtor_vbase)
John McCall58e6f342010-03-16 05:22:47 +00002443 << VBase->getType());
2444
John McCallef027fe2010-03-16 21:39:52 +00002445 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002446 }
2447}
2448
John McCalld226f652010-08-21 09:40:31 +00002449void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00002450 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00002451 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002452
Mike Stump1eb44332009-09-09 15:08:12 +00002453 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002454 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Sean Huntcbb67482011-01-08 20:30:50 +00002455 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00002456}
2457
Mike Stump1eb44332009-09-09 15:08:12 +00002458bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00002459 unsigned DiagID, AbstractDiagSelID SelID) {
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002460 if (SelID == -1)
John McCall94c3b562010-08-18 09:41:07 +00002461 return RequireNonAbstractType(Loc, T, PDiag(DiagID));
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002462 else
John McCall94c3b562010-08-18 09:41:07 +00002463 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
Mike Stump1eb44332009-09-09 15:08:12 +00002464}
2465
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002466bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00002467 const PartialDiagnostic &PD) {
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002468 if (!getLangOptions().CPlusPlus)
2469 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002470
Anders Carlsson11f21a02009-03-23 19:10:31 +00002471 if (const ArrayType *AT = Context.getAsArrayType(T))
John McCall94c3b562010-08-18 09:41:07 +00002472 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Mike Stump1eb44332009-09-09 15:08:12 +00002473
Ted Kremenek6217b802009-07-29 21:53:49 +00002474 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002475 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00002476 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002477 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00002478
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002479 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
John McCall94c3b562010-08-18 09:41:07 +00002480 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002481 }
Mike Stump1eb44332009-09-09 15:08:12 +00002482
Ted Kremenek6217b802009-07-29 21:53:49 +00002483 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002484 if (!RT)
2485 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002486
John McCall86ff3082010-02-04 22:26:26 +00002487 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002488
John McCall94c3b562010-08-18 09:41:07 +00002489 // We can't answer whether something is abstract until it has a
2490 // definition. If it's currently being defined, we'll walk back
2491 // over all the declarations when we have a full definition.
2492 const CXXRecordDecl *Def = RD->getDefinition();
2493 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00002494 return false;
2495
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002496 if (!RD->isAbstract())
2497 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002498
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002499 Diag(Loc, PD) << RD->getDeclName();
John McCall94c3b562010-08-18 09:41:07 +00002500 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00002501
John McCall94c3b562010-08-18 09:41:07 +00002502 return true;
2503}
2504
2505void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
2506 // Check if we've already emitted the list of pure virtual functions
2507 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002508 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00002509 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002510
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002511 CXXFinalOverriderMap FinalOverriders;
2512 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00002513
Anders Carlssonffdb2d22010-06-03 01:00:02 +00002514 // Keep a set of seen pure methods so we won't diagnose the same method
2515 // more than once.
2516 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
2517
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002518 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2519 MEnd = FinalOverriders.end();
2520 M != MEnd;
2521 ++M) {
2522 for (OverridingMethods::iterator SO = M->second.begin(),
2523 SOEnd = M->second.end();
2524 SO != SOEnd; ++SO) {
2525 // C++ [class.abstract]p4:
2526 // A class is abstract if it contains or inherits at least one
2527 // pure virtual function for which the final overrider is pure
2528 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00002529
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002530 //
2531 if (SO->second.size() != 1)
2532 continue;
2533
2534 if (!SO->second.front().Method->isPure())
2535 continue;
2536
Anders Carlssonffdb2d22010-06-03 01:00:02 +00002537 if (!SeenPureMethods.insert(SO->second.front().Method))
2538 continue;
2539
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002540 Diag(SO->second.front().Method->getLocation(),
2541 diag::note_pure_virtual_function)
2542 << SO->second.front().Method->getDeclName();
2543 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002544 }
2545
2546 if (!PureVirtualClassDiagSet)
2547 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2548 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002549}
2550
Anders Carlsson8211eff2009-03-24 01:19:16 +00002551namespace {
John McCall94c3b562010-08-18 09:41:07 +00002552struct AbstractUsageInfo {
2553 Sema &S;
2554 CXXRecordDecl *Record;
2555 CanQualType AbstractType;
2556 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00002557
John McCall94c3b562010-08-18 09:41:07 +00002558 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
2559 : S(S), Record(Record),
2560 AbstractType(S.Context.getCanonicalType(
2561 S.Context.getTypeDeclType(Record))),
2562 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00002563
John McCall94c3b562010-08-18 09:41:07 +00002564 void DiagnoseAbstractType() {
2565 if (Invalid) return;
2566 S.DiagnoseAbstractType(Record);
2567 Invalid = true;
2568 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00002569
John McCall94c3b562010-08-18 09:41:07 +00002570 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
2571};
2572
2573struct CheckAbstractUsage {
2574 AbstractUsageInfo &Info;
2575 const NamedDecl *Ctx;
2576
2577 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
2578 : Info(Info), Ctx(Ctx) {}
2579
2580 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2581 switch (TL.getTypeLocClass()) {
2582#define ABSTRACT_TYPELOC(CLASS, PARENT)
2583#define TYPELOC(CLASS, PARENT) \
2584 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
2585#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00002586 }
John McCall94c3b562010-08-18 09:41:07 +00002587 }
Mike Stump1eb44332009-09-09 15:08:12 +00002588
John McCall94c3b562010-08-18 09:41:07 +00002589 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2590 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
2591 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2592 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
2593 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00002594 }
John McCall94c3b562010-08-18 09:41:07 +00002595 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00002596
John McCall94c3b562010-08-18 09:41:07 +00002597 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2598 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
2599 }
Mike Stump1eb44332009-09-09 15:08:12 +00002600
John McCall94c3b562010-08-18 09:41:07 +00002601 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2602 // Visit the type parameters from a permissive context.
2603 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2604 TemplateArgumentLoc TAL = TL.getArgLoc(I);
2605 if (TAL.getArgument().getKind() == TemplateArgument::Type)
2606 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
2607 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
2608 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00002609 }
John McCall94c3b562010-08-18 09:41:07 +00002610 }
Mike Stump1eb44332009-09-09 15:08:12 +00002611
John McCall94c3b562010-08-18 09:41:07 +00002612 // Visit pointee types from a permissive context.
2613#define CheckPolymorphic(Type) \
2614 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
2615 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
2616 }
2617 CheckPolymorphic(PointerTypeLoc)
2618 CheckPolymorphic(ReferenceTypeLoc)
2619 CheckPolymorphic(MemberPointerTypeLoc)
2620 CheckPolymorphic(BlockPointerTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00002621
John McCall94c3b562010-08-18 09:41:07 +00002622 /// Handle all the types we haven't given a more specific
2623 /// implementation for above.
2624 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2625 // Every other kind of type that we haven't called out already
2626 // that has an inner type is either (1) sugar or (2) contains that
2627 // inner type in some way as a subobject.
2628 if (TypeLoc Next = TL.getNextTypeLoc())
2629 return Visit(Next, Sel);
2630
2631 // If there's no inner type and we're in a permissive context,
2632 // don't diagnose.
2633 if (Sel == Sema::AbstractNone) return;
2634
2635 // Check whether the type matches the abstract type.
2636 QualType T = TL.getType();
2637 if (T->isArrayType()) {
2638 Sel = Sema::AbstractArrayType;
2639 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00002640 }
John McCall94c3b562010-08-18 09:41:07 +00002641 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
2642 if (CT != Info.AbstractType) return;
2643
2644 // It matched; do some magic.
2645 if (Sel == Sema::AbstractArrayType) {
2646 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
2647 << T << TL.getSourceRange();
2648 } else {
2649 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
2650 << Sel << T << TL.getSourceRange();
2651 }
2652 Info.DiagnoseAbstractType();
2653 }
2654};
2655
2656void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
2657 Sema::AbstractDiagSelID Sel) {
2658 CheckAbstractUsage(*this, D).Visit(TL, Sel);
2659}
2660
2661}
2662
2663/// Check for invalid uses of an abstract type in a method declaration.
2664static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2665 CXXMethodDecl *MD) {
2666 // No need to do the check on definitions, which require that
2667 // the return/param types be complete.
2668 if (MD->isThisDeclarationADefinition())
2669 return;
2670
2671 // For safety's sake, just ignore it if we don't have type source
2672 // information. This should never happen for non-implicit methods,
2673 // but...
2674 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
2675 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
2676}
2677
2678/// Check for invalid uses of an abstract type within a class definition.
2679static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2680 CXXRecordDecl *RD) {
2681 for (CXXRecordDecl::decl_iterator
2682 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
2683 Decl *D = *I;
2684 if (D->isImplicit()) continue;
2685
2686 // Methods and method templates.
2687 if (isa<CXXMethodDecl>(D)) {
2688 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
2689 } else if (isa<FunctionTemplateDecl>(D)) {
2690 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
2691 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
2692
2693 // Fields and static variables.
2694 } else if (isa<FieldDecl>(D)) {
2695 FieldDecl *FD = cast<FieldDecl>(D);
2696 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
2697 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
2698 } else if (isa<VarDecl>(D)) {
2699 VarDecl *VD = cast<VarDecl>(D);
2700 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
2701 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
2702
2703 // Nested classes and class templates.
2704 } else if (isa<CXXRecordDecl>(D)) {
2705 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
2706 } else if (isa<ClassTemplateDecl>(D)) {
2707 CheckAbstractClassUsage(Info,
2708 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
2709 }
2710 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00002711}
2712
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002713/// \brief Perform semantic checks on a class definition that has been
2714/// completing, introducing implicitly-declared members, checking for
2715/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00002716void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00002717 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002718 return;
2719
John McCall94c3b562010-08-18 09:41:07 +00002720 if (Record->isAbstract() && !Record->isInvalidDecl()) {
2721 AbstractUsageInfo Info(*this, Record);
2722 CheckAbstractClassUsage(Info, Record);
2723 }
Douglas Gregor325e5932010-04-15 00:00:53 +00002724
2725 // If this is not an aggregate type and has no user-declared constructor,
2726 // complain about any non-static data members of reference or const scalar
2727 // type, since they will never get initializers.
2728 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
2729 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
2730 bool Complained = false;
2731 for (RecordDecl::field_iterator F = Record->field_begin(),
2732 FEnd = Record->field_end();
2733 F != FEnd; ++F) {
2734 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00002735 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00002736 if (!Complained) {
2737 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
2738 << Record->getTagKind() << Record;
2739 Complained = true;
2740 }
2741
2742 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
2743 << F->getType()->isReferenceType()
2744 << F->getDeclName();
2745 }
2746 }
2747 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002748
Anders Carlssona5c6c2a2011-01-25 18:08:22 +00002749 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002750 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00002751
2752 if (Record->getIdentifier()) {
2753 // C++ [class.mem]p13:
2754 // If T is the name of a class, then each of the following shall have a
2755 // name different from T:
2756 // - every member of every anonymous union that is a member of class T.
2757 //
2758 // C++ [class.mem]p14:
2759 // In addition, if class T has a user-declared constructor (12.1), every
2760 // non-static data member of class T shall have a name different from T.
2761 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
Francois Pichet87c2e122010-11-21 06:08:52 +00002762 R.first != R.second; ++R.first) {
2763 NamedDecl *D = *R.first;
2764 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
2765 isa<IndirectFieldDecl>(D)) {
2766 Diag(D->getLocation(), diag::err_member_name_of_class)
2767 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00002768 break;
2769 }
Francois Pichet87c2e122010-11-21 06:08:52 +00002770 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00002771 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00002772
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00002773 // Warn if the class has virtual methods but non-virtual public destructor.
Argyrios Kyrtzidis668fdd82011-02-02 18:47:41 +00002774 if (Record->isDynamicClass() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00002775 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00002776 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00002777 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
2778 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
2779 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002780}
2781
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002782void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00002783 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002784 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00002785 SourceLocation RBrac,
2786 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002787 if (!TagDecl)
2788 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002789
Douglas Gregor42af25f2009-05-11 19:58:34 +00002790 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002791
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002792 ActOnFields(S, RLoc, TagDecl,
John McCalld226f652010-08-21 09:40:31 +00002793 // strict aliasing violation!
2794 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00002795 FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00002796
Douglas Gregor23c94db2010-07-02 17:43:08 +00002797 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00002798 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002799}
2800
Douglas Gregord92ec472010-07-01 05:10:53 +00002801namespace {
2802 /// \brief Helper class that collects exception specifications for
2803 /// implicitly-declared special member functions.
2804 class ImplicitExceptionSpecification {
2805 ASTContext &Context;
2806 bool AllowsAllExceptions;
2807 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
2808 llvm::SmallVector<QualType, 4> Exceptions;
2809
2810 public:
2811 explicit ImplicitExceptionSpecification(ASTContext &Context)
2812 : Context(Context), AllowsAllExceptions(false) { }
2813
2814 /// \brief Whether the special member function should have any
2815 /// exception specification at all.
2816 bool hasExceptionSpecification() const {
2817 return !AllowsAllExceptions;
2818 }
2819
2820 /// \brief Whether the special member function should have a
2821 /// throw(...) exception specification (a Microsoft extension).
2822 bool hasAnyExceptionSpecification() const {
2823 return false;
2824 }
2825
2826 /// \brief The number of exceptions in the exception specification.
2827 unsigned size() const { return Exceptions.size(); }
2828
2829 /// \brief The set of exceptions in the exception specification.
2830 const QualType *data() const { return Exceptions.data(); }
2831
2832 /// \brief Note that
2833 void CalledDecl(CXXMethodDecl *Method) {
2834 // If we already know that we allow all exceptions, do nothing.
Douglas Gregor4681ca82010-07-01 15:29:53 +00002835 if (AllowsAllExceptions || !Method)
Douglas Gregord92ec472010-07-01 05:10:53 +00002836 return;
2837
2838 const FunctionProtoType *Proto
2839 = Method->getType()->getAs<FunctionProtoType>();
2840
2841 // If this function can throw any exceptions, make a note of that.
2842 if (!Proto->hasExceptionSpec() || Proto->hasAnyExceptionSpec()) {
2843 AllowsAllExceptions = true;
2844 ExceptionsSeen.clear();
2845 Exceptions.clear();
2846 return;
2847 }
2848
2849 // Record the exceptions in this function's exception specification.
2850 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
2851 EEnd = Proto->exception_end();
2852 E != EEnd; ++E)
2853 if (ExceptionsSeen.insert(Context.getCanonicalType(*E)))
2854 Exceptions.push_back(*E);
2855 }
2856 };
2857}
2858
2859
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002860/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
2861/// special functions, such as the default constructor, copy
2862/// constructor, or destructor, to the given C++ class (C++
2863/// [special]p1). This routine can only be executed just before the
2864/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00002865void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00002866 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00002867 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002868
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00002869 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregor22584312010-07-02 23:41:54 +00002870 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002871
Douglas Gregora376d102010-07-02 21:50:04 +00002872 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
2873 ++ASTContext::NumImplicitCopyAssignmentOperators;
2874
2875 // If we have a dynamic class, then the copy assignment operator may be
2876 // virtual, so we have to declare it immediately. This ensures that, e.g.,
2877 // it shows up in the right place in the vtable and that we diagnose
2878 // problems with the implicit exception specification.
2879 if (ClassDecl->isDynamicClass())
2880 DeclareImplicitCopyAssignment(ClassDecl);
2881 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00002882
Douglas Gregor4923aa22010-07-02 20:37:36 +00002883 if (!ClassDecl->hasUserDeclaredDestructor()) {
2884 ++ASTContext::NumImplicitDestructors;
2885
2886 // If we have a dynamic class, then the destructor may be virtual, so we
2887 // have to declare the destructor immediately. This ensures that, e.g., it
2888 // shows up in the right place in the vtable and that we diagnose problems
2889 // with the implicit exception specification.
2890 if (ClassDecl->isDynamicClass())
2891 DeclareImplicitDestructor(ClassDecl);
2892 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002893}
2894
John McCalld226f652010-08-21 09:40:31 +00002895void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00002896 if (!D)
2897 return;
2898
2899 TemplateParameterList *Params = 0;
2900 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
2901 Params = Template->getTemplateParameters();
2902 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2903 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
2904 Params = PartialSpec->getTemplateParameters();
2905 else
Douglas Gregor6569d682009-05-27 23:11:45 +00002906 return;
2907
Douglas Gregor6569d682009-05-27 23:11:45 +00002908 for (TemplateParameterList::iterator Param = Params->begin(),
2909 ParamEnd = Params->end();
2910 Param != ParamEnd; ++Param) {
2911 NamedDecl *Named = cast<NamedDecl>(*Param);
2912 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00002913 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00002914 IdResolver.AddDecl(Named);
2915 }
2916 }
2917}
2918
John McCalld226f652010-08-21 09:40:31 +00002919void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00002920 if (!RecordD) return;
2921 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00002922 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00002923 PushDeclContext(S, Record);
2924}
2925
John McCalld226f652010-08-21 09:40:31 +00002926void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00002927 if (!RecordD) return;
2928 PopDeclContext();
2929}
2930
Douglas Gregor72b505b2008-12-16 21:30:33 +00002931/// ActOnStartDelayedCXXMethodDeclaration - We have completed
2932/// parsing a top-level (non-nested) C++ class, and we are now
2933/// parsing those parts of the given Method declaration that could
2934/// not be parsed earlier (C++ [class.mem]p2), such as default
2935/// arguments. This action should enter the scope of the given
2936/// Method declaration as if we had just parsed the qualified method
2937/// name. However, it should not bring the parameters into scope;
2938/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00002939void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00002940}
2941
2942/// ActOnDelayedCXXMethodParameter - We've already started a delayed
2943/// C++ method declaration. We're (re-)introducing the given
2944/// function parameter into scope for use in parsing later parts of
2945/// the method declaration. For example, we could see an
2946/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00002947void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002948 if (!ParamD)
2949 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002950
John McCalld226f652010-08-21 09:40:31 +00002951 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00002952
2953 // If this parameter has an unparsed default argument, clear it out
2954 // to make way for the parsed default argument.
2955 if (Param->hasUnparsedDefaultArg())
2956 Param->setDefaultArg(0);
2957
John McCalld226f652010-08-21 09:40:31 +00002958 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002959 if (Param->getDeclName())
2960 IdResolver.AddDecl(Param);
2961}
2962
2963/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
2964/// processing the delayed method declaration for Method. The method
2965/// declaration is now considered finished. There may be a separate
2966/// ActOnStartOfFunctionDef action later (not necessarily
2967/// immediately!) for this method, if it was also defined inside the
2968/// class body.
John McCalld226f652010-08-21 09:40:31 +00002969void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002970 if (!MethodD)
2971 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002972
Douglas Gregorefd5bda2009-08-24 11:57:43 +00002973 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00002974
John McCalld226f652010-08-21 09:40:31 +00002975 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002976
2977 // Now that we have our default arguments, check the constructor
2978 // again. It could produce additional diagnostics or affect whether
2979 // the class has implicitly-declared destructors, among other
2980 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00002981 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
2982 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002983
2984 // Check the default arguments, which we may have added.
2985 if (!Method->isInvalidDecl())
2986 CheckCXXDefaultArguments(Method);
2987}
2988
Douglas Gregor42a552f2008-11-05 20:51:48 +00002989/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00002990/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00002991/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00002992/// emit diagnostics and set the invalid bit to true. In any case, the type
2993/// will be updated to reflect a well-formed type for the constructor and
2994/// returned.
2995QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00002996 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002997 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002998
2999 // C++ [class.ctor]p3:
3000 // A constructor shall not be virtual (10.3) or static (9.4). A
3001 // constructor can be invoked for a const, volatile or const
3002 // volatile object. A constructor shall not be declared const,
3003 // volatile, or const volatile (9.3.2).
3004 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00003005 if (!D.isInvalidType())
3006 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
3007 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
3008 << SourceRange(D.getIdentifierLoc());
3009 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00003010 }
John McCalld931b082010-08-26 03:08:43 +00003011 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00003012 if (!D.isInvalidType())
3013 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
3014 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
3015 << SourceRange(D.getIdentifierLoc());
3016 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00003017 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00003018 }
Mike Stump1eb44332009-09-09 15:08:12 +00003019
Abramo Bagnara075f8f12010-12-10 16:29:40 +00003020 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00003021 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00003022 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003023 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
3024 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00003025 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003026 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
3027 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00003028 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003029 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
3030 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00003031 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00003032 }
Mike Stump1eb44332009-09-09 15:08:12 +00003033
Douglas Gregorc938c162011-01-26 05:01:58 +00003034 // C++0x [class.ctor]p4:
3035 // A constructor shall not be declared with a ref-qualifier.
3036 if (FTI.hasRefQualifier()) {
3037 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
3038 << FTI.RefQualifierIsLValueRef
3039 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
3040 D.setInvalidType();
3041 }
3042
Douglas Gregor42a552f2008-11-05 20:51:48 +00003043 // Rebuild the function type "R" without any type qualifiers (in
3044 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00003045 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00003046 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00003047 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
3048 return R;
3049
3050 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3051 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00003052 EPI.RefQualifier = RQ_None;
3053
Chris Lattner65401802009-04-25 08:28:21 +00003054 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00003055 Proto->getNumArgs(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00003056}
3057
Douglas Gregor72b505b2008-12-16 21:30:33 +00003058/// CheckConstructor - Checks a fully-formed constructor for
3059/// well-formedness, issuing any diagnostics required. Returns true if
3060/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00003061void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00003062 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00003063 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
3064 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00003065 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00003066
3067 // C++ [class.copy]p3:
3068 // A declaration of a constructor for a class X is ill-formed if
3069 // its first parameter is of type (optionally cv-qualified) X and
3070 // either there are no other parameters or else all other
3071 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00003072 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00003073 ((Constructor->getNumParams() == 1) ||
3074 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00003075 Constructor->getParamDecl(1)->hasDefaultArg())) &&
3076 Constructor->getTemplateSpecializationKind()
3077 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00003078 QualType ParamType = Constructor->getParamDecl(0)->getType();
3079 QualType ClassTy = Context.getTagDeclType(ClassDecl);
3080 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00003081 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00003082 const char *ConstRef
3083 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
3084 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00003085 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00003086 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00003087
3088 // FIXME: Rather that making the constructor invalid, we should endeavor
3089 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00003090 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00003091 }
3092 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00003093}
3094
John McCall15442822010-08-04 01:04:25 +00003095/// CheckDestructor - Checks a fully-formed destructor definition for
3096/// well-formedness, issuing any diagnostics required. Returns true
3097/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00003098bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00003099 CXXRecordDecl *RD = Destructor->getParent();
3100
3101 if (Destructor->isVirtual()) {
3102 SourceLocation Loc;
3103
3104 if (!Destructor->isImplicit())
3105 Loc = Destructor->getLocation();
3106 else
3107 Loc = RD->getLocation();
3108
3109 // If we have a virtual destructor, look up the deallocation function
3110 FunctionDecl *OperatorDelete = 0;
3111 DeclarationName Name =
3112 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00003113 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00003114 return true;
John McCall5efd91a2010-07-03 18:33:00 +00003115
3116 MarkDeclarationReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00003117
3118 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00003119 }
Anders Carlsson37909802009-11-30 21:24:50 +00003120
3121 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00003122}
3123
Mike Stump1eb44332009-09-09 15:08:12 +00003124static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00003125FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
3126 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
3127 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00003128 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00003129}
3130
Douglas Gregor42a552f2008-11-05 20:51:48 +00003131/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
3132/// the well-formednes of the destructor declarator @p D with type @p
3133/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00003134/// emit diagnostics and set the declarator to invalid. Even if this happens,
3135/// will be updated to reflect a well-formed type for the destructor and
3136/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00003137QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00003138 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00003139 // C++ [class.dtor]p1:
3140 // [...] A typedef-name that names a class is a class-name
3141 // (7.1.3); however, a typedef-name that names a class shall not
3142 // be used as the identifier in the declarator for a destructor
3143 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00003144 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Douglas Gregord92ec472010-07-01 05:10:53 +00003145 if (isa<TypedefType>(DeclaratorType))
Chris Lattner65401802009-04-25 08:28:21 +00003146 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00003147 << DeclaratorType;
Douglas Gregor42a552f2008-11-05 20:51:48 +00003148
3149 // C++ [class.dtor]p2:
3150 // A destructor is used to destroy objects of its class type. A
3151 // destructor takes no parameters, and no return type can be
3152 // specified for it (not even void). The address of a destructor
3153 // shall not be taken. A destructor shall not be static. A
3154 // destructor can be invoked for a const, volatile or const
3155 // volatile object. A destructor shall not be declared const,
3156 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00003157 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00003158 if (!D.isInvalidType())
3159 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
3160 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00003161 << SourceRange(D.getIdentifierLoc())
3162 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
3163
John McCalld931b082010-08-26 03:08:43 +00003164 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00003165 }
Chris Lattner65401802009-04-25 08:28:21 +00003166 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00003167 // Destructors don't have return types, but the parser will
3168 // happily parse something like:
3169 //
3170 // class X {
3171 // float ~X();
3172 // };
3173 //
3174 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003175 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
3176 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3177 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00003178 }
Mike Stump1eb44332009-09-09 15:08:12 +00003179
Abramo Bagnara075f8f12010-12-10 16:29:40 +00003180 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00003181 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00003182 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003183 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3184 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00003185 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003186 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3187 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00003188 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003189 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3190 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00003191 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00003192 }
3193
Douglas Gregorc938c162011-01-26 05:01:58 +00003194 // C++0x [class.dtor]p2:
3195 // A destructor shall not be declared with a ref-qualifier.
3196 if (FTI.hasRefQualifier()) {
3197 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
3198 << FTI.RefQualifierIsLValueRef
3199 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
3200 D.setInvalidType();
3201 }
3202
Douglas Gregor42a552f2008-11-05 20:51:48 +00003203 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00003204 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00003205 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
3206
3207 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00003208 FTI.freeArgs();
3209 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00003210 }
3211
Mike Stump1eb44332009-09-09 15:08:12 +00003212 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00003213 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00003214 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00003215 D.setInvalidType();
3216 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00003217
3218 // Rebuild the function type "R" without any type qualifiers or
3219 // parameters (in case any of the errors above fired) and with
3220 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00003221 // types.
John McCalle23cf432010-12-14 08:05:40 +00003222 if (!D.isInvalidType())
3223 return R;
3224
Douglas Gregord92ec472010-07-01 05:10:53 +00003225 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00003226 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3227 EPI.Variadic = false;
3228 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00003229 EPI.RefQualifier = RQ_None;
John McCalle23cf432010-12-14 08:05:40 +00003230 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00003231}
3232
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003233/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
3234/// well-formednes of the conversion function declarator @p D with
3235/// type @p R. If there are any errors in the declarator, this routine
3236/// will emit diagnostics and return true. Otherwise, it will return
3237/// false. Either way, the type @p R will be updated to reflect a
3238/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00003239void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00003240 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003241 // C++ [class.conv.fct]p1:
3242 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00003243 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00003244 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00003245 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00003246 if (!D.isInvalidType())
3247 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
3248 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
3249 << SourceRange(D.getIdentifierLoc());
3250 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00003251 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003252 }
John McCalla3f81372010-04-13 00:04:31 +00003253
3254 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
3255
Chris Lattner6e475012009-04-25 08:35:12 +00003256 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003257 // Conversion functions don't have return types, but the parser will
3258 // happily parse something like:
3259 //
3260 // class X {
3261 // float operator bool();
3262 // };
3263 //
3264 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003265 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
3266 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3267 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00003268 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003269 }
3270
John McCalla3f81372010-04-13 00:04:31 +00003271 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
3272
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003273 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00003274 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003275 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
3276
3277 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00003278 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00003279 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00003280 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003281 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00003282 D.setInvalidType();
3283 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003284
John McCalla3f81372010-04-13 00:04:31 +00003285 // Diagnose "&operator bool()" and other such nonsense. This
3286 // is actually a gcc extension which we don't support.
3287 if (Proto->getResultType() != ConvType) {
3288 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
3289 << Proto->getResultType();
3290 D.setInvalidType();
3291 ConvType = Proto->getResultType();
3292 }
3293
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003294 // C++ [class.conv.fct]p4:
3295 // The conversion-type-id shall not represent a function type nor
3296 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003297 if (ConvType->isArrayType()) {
3298 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
3299 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00003300 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003301 } else if (ConvType->isFunctionType()) {
3302 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
3303 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00003304 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003305 }
3306
3307 // Rebuild the function type "R" without any parameters (in case any
3308 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00003309 // return type.
John McCalle23cf432010-12-14 08:05:40 +00003310 if (D.isInvalidType())
3311 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003312
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003313 // C++0x explicit conversion operators.
3314 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump1eb44332009-09-09 15:08:12 +00003315 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003316 diag::warn_explicit_conversion_functions)
3317 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003318}
3319
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003320/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
3321/// the declaration of the given C++ conversion function. This routine
3322/// is responsible for recording the conversion function in the C++
3323/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00003324Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003325 assert(Conversion && "Expected to receive a conversion function declaration");
3326
Douglas Gregor9d350972008-12-12 08:25:50 +00003327 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003328
3329 // Make sure we aren't redeclaring the conversion function.
3330 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003331
3332 // C++ [class.conv.fct]p1:
3333 // [...] A conversion function is never used to convert a
3334 // (possibly cv-qualified) object to the (possibly cv-qualified)
3335 // same object type (or a reference to it), to a (possibly
3336 // cv-qualified) base class of that type (or a reference to it),
3337 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00003338 // FIXME: Suppress this warning if the conversion function ends up being a
3339 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00003340 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003341 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00003342 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003343 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00003344 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
3345 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00003346 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00003347 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003348 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
3349 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00003350 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00003351 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003352 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00003353 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00003354 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003355 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00003356 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00003357 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003358 }
3359
Douglas Gregore80622f2010-09-29 04:25:11 +00003360 if (FunctionTemplateDecl *ConversionTemplate
3361 = Conversion->getDescribedFunctionTemplate())
3362 return ConversionTemplate;
3363
John McCalld226f652010-08-21 09:40:31 +00003364 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003365}
3366
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003367//===----------------------------------------------------------------------===//
3368// Namespace Handling
3369//===----------------------------------------------------------------------===//
3370
John McCallea318642010-08-26 09:15:37 +00003371
3372
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003373/// ActOnStartNamespaceDef - This is called at the start of a namespace
3374/// definition.
John McCalld226f652010-08-21 09:40:31 +00003375Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00003376 SourceLocation InlineLoc,
John McCallea318642010-08-26 09:15:37 +00003377 SourceLocation IdentLoc,
3378 IdentifierInfo *II,
3379 SourceLocation LBrace,
3380 AttributeList *AttrList) {
Douglas Gregor21e09b62010-08-19 20:55:47 +00003381 // anonymous namespace starts at its left brace
3382 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext,
3383 (II ? IdentLoc : LBrace) , II);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003384 Namespc->setLBracLoc(LBrace);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00003385 Namespc->setInline(InlineLoc.isValid());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003386
3387 Scope *DeclRegionScope = NamespcScope->getParent();
3388
Anders Carlsson2a3503d2010-02-07 01:09:23 +00003389 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
3390
John McCall90f14502010-12-10 02:59:44 +00003391 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
3392 PushNamespaceVisibilityAttr(Attr);
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00003393
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003394 if (II) {
3395 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00003396 // The identifier in an original-namespace-definition shall not
3397 // have been previously defined in the declarative region in
3398 // which the original-namespace-definition appears. The
3399 // identifier in an original-namespace-definition is the name of
3400 // the namespace. Subsequently in that declarative region, it is
3401 // treated as an original-namespace-name.
3402 //
3403 // Since namespace names are unique in their scope, and we don't
3404 // look through using directives, just
3405 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
3406 NamedDecl *PrevDecl = R.first == R.second? 0 : *R.first;
Mike Stump1eb44332009-09-09 15:08:12 +00003407
Douglas Gregor44b43212008-12-11 16:49:14 +00003408 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
3409 // This is an extended namespace definition.
Sebastian Redl4e4d5702010-08-31 00:36:36 +00003410 if (Namespc->isInline() != OrigNS->isInline()) {
3411 // inline-ness must match
3412 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
3413 << Namespc->isInline();
3414 Diag(OrigNS->getLocation(), diag::note_previous_definition);
3415 Namespc->setInvalidDecl();
3416 // Recover by ignoring the new namespace's inline status.
3417 Namespc->setInline(OrigNS->isInline());
3418 }
3419
Douglas Gregor44b43212008-12-11 16:49:14 +00003420 // Attach this namespace decl to the chain of extended namespace
3421 // definitions.
3422 OrigNS->setNextNamespace(Namespc);
3423 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003424
Mike Stump1eb44332009-09-09 15:08:12 +00003425 // Remove the previous declaration from the scope.
John McCalld226f652010-08-21 09:40:31 +00003426 if (DeclRegionScope->isDeclScope(OrigNS)) {
Douglas Gregore267ff32008-12-11 20:41:00 +00003427 IdResolver.RemoveDecl(OrigNS);
John McCalld226f652010-08-21 09:40:31 +00003428 DeclRegionScope->RemoveDecl(OrigNS);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003429 }
Douglas Gregor44b43212008-12-11 16:49:14 +00003430 } else if (PrevDecl) {
3431 // This is an invalid name redefinition.
3432 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
3433 << Namespc->getDeclName();
3434 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3435 Namespc->setInvalidDecl();
3436 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor7adb10f2009-09-15 22:30:29 +00003437 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00003438 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00003439 // This is the first "real" definition of the namespace "std", so update
3440 // our cache of the "std" namespace to point at this definition.
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00003441 if (NamespaceDecl *StdNS = getStdNamespace()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00003442 // We had already defined a dummy namespace "std". Link this new
3443 // namespace definition to the dummy namespace "std".
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00003444 StdNS->setNextNamespace(Namespc);
3445 StdNS->setLocation(IdentLoc);
3446 Namespc->setOriginalNamespace(StdNS->getOriginalNamespace());
Douglas Gregor7adb10f2009-09-15 22:30:29 +00003447 }
3448
3449 // Make our StdNamespace cache point at the first real definition of the
3450 // "std" namespace.
3451 StdNamespace = Namespc;
Mike Stump1eb44332009-09-09 15:08:12 +00003452 }
Douglas Gregor44b43212008-12-11 16:49:14 +00003453
3454 PushOnScopeChains(Namespc, DeclRegionScope);
3455 } else {
John McCall9aeed322009-10-01 00:25:31 +00003456 // Anonymous namespaces.
John McCall5fdd7642009-12-16 02:06:49 +00003457 assert(Namespc->isAnonymousNamespace());
John McCall5fdd7642009-12-16 02:06:49 +00003458
3459 // Link the anonymous namespace into its parent.
3460 NamespaceDecl *PrevDecl;
Sebastian Redl7a126a42010-08-31 00:36:30 +00003461 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00003462 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
3463 PrevDecl = TU->getAnonymousNamespace();
3464 TU->setAnonymousNamespace(Namespc);
3465 } else {
3466 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
3467 PrevDecl = ND->getAnonymousNamespace();
3468 ND->setAnonymousNamespace(Namespc);
3469 }
3470
3471 // Link the anonymous namespace with its previous declaration.
3472 if (PrevDecl) {
3473 assert(PrevDecl->isAnonymousNamespace());
3474 assert(!PrevDecl->getNextNamespace());
3475 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
3476 PrevDecl->setNextNamespace(Namespc);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00003477
3478 if (Namespc->isInline() != PrevDecl->isInline()) {
3479 // inline-ness must match
3480 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
3481 << Namespc->isInline();
3482 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3483 Namespc->setInvalidDecl();
3484 // Recover by ignoring the new namespace's inline status.
3485 Namespc->setInline(PrevDecl->isInline());
3486 }
John McCall5fdd7642009-12-16 02:06:49 +00003487 }
John McCall9aeed322009-10-01 00:25:31 +00003488
Douglas Gregora4181472010-03-24 00:46:35 +00003489 CurContext->addDecl(Namespc);
3490
John McCall9aeed322009-10-01 00:25:31 +00003491 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
3492 // behaves as if it were replaced by
3493 // namespace unique { /* empty body */ }
3494 // using namespace unique;
3495 // namespace unique { namespace-body }
3496 // where all occurrences of 'unique' in a translation unit are
3497 // replaced by the same identifier and this identifier differs
3498 // from all other identifiers in the entire program.
3499
3500 // We just create the namespace with an empty name and then add an
3501 // implicit using declaration, just like the standard suggests.
3502 //
3503 // CodeGen enforces the "universally unique" aspect by giving all
3504 // declarations semantically contained within an anonymous
3505 // namespace internal linkage.
3506
John McCall5fdd7642009-12-16 02:06:49 +00003507 if (!PrevDecl) {
3508 UsingDirectiveDecl* UD
3509 = UsingDirectiveDecl::Create(Context, CurContext,
3510 /* 'using' */ LBrace,
3511 /* 'namespace' */ SourceLocation(),
3512 /* qualifier */ SourceRange(),
3513 /* NNS */ NULL,
3514 /* identifier */ SourceLocation(),
3515 Namespc,
3516 /* Ancestor */ CurContext);
3517 UD->setImplicit();
3518 CurContext->addDecl(UD);
3519 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003520 }
3521
3522 // Although we could have an invalid decl (i.e. the namespace name is a
3523 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00003524 // FIXME: We should be able to push Namespc here, so that the each DeclContext
3525 // for the namespace has the declarations that showed up in that particular
3526 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00003527 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00003528 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003529}
3530
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003531/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
3532/// is a namespace alias, returns the namespace it points to.
3533static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
3534 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
3535 return AD->getNamespace();
3536 return dyn_cast_or_null<NamespaceDecl>(D);
3537}
3538
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003539/// ActOnFinishNamespaceDef - This callback is called after a namespace is
3540/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00003541void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003542 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
3543 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
3544 Namespc->setRBracLoc(RBrace);
3545 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00003546 if (Namespc->hasAttr<VisibilityAttr>())
3547 PopPragmaVisibility();
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003548}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003549
John McCall384aff82010-08-25 07:42:41 +00003550CXXRecordDecl *Sema::getStdBadAlloc() const {
3551 return cast_or_null<CXXRecordDecl>(
3552 StdBadAlloc.get(Context.getExternalSource()));
3553}
3554
3555NamespaceDecl *Sema::getStdNamespace() const {
3556 return cast_or_null<NamespaceDecl>(
3557 StdNamespace.get(Context.getExternalSource()));
3558}
3559
Douglas Gregor66992202010-06-29 17:53:46 +00003560/// \brief Retrieve the special "std" namespace, which may require us to
3561/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00003562NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00003563 if (!StdNamespace) {
3564 // The "std" namespace has not yet been defined, so build one implicitly.
3565 StdNamespace = NamespaceDecl::Create(Context,
3566 Context.getTranslationUnitDecl(),
3567 SourceLocation(),
3568 &PP.getIdentifierTable().get("std"));
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00003569 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00003570 }
3571
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00003572 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00003573}
3574
John McCalld226f652010-08-21 09:40:31 +00003575Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00003576 SourceLocation UsingLoc,
3577 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003578 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00003579 SourceLocation IdentLoc,
3580 IdentifierInfo *NamespcName,
3581 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00003582 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3583 assert(NamespcName && "Invalid NamespcName.");
3584 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00003585
3586 // This can only happen along a recovery path.
3587 while (S->getFlags() & Scope::TemplateParamScope)
3588 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003589 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00003590
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003591 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00003592 NestedNameSpecifier *Qualifier = 0;
3593 if (SS.isSet())
3594 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3595
Douglas Gregoreb11cd02009-01-14 22:20:51 +00003596 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00003597 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
3598 LookupParsedName(R, S, &SS);
3599 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00003600 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00003601
Douglas Gregor66992202010-06-29 17:53:46 +00003602 if (R.empty()) {
3603 // Allow "using namespace std;" or "using namespace ::std;" even if
3604 // "std" hasn't been defined yet, for GCC compatibility.
3605 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
3606 NamespcName->isStr("std")) {
3607 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00003608 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00003609 R.resolveKind();
3610 }
3611 // Otherwise, attempt typo correction.
3612 else if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
3613 CTC_NoKeywords, 0)) {
3614 if (R.getAsSingle<NamespaceDecl>() ||
3615 R.getAsSingle<NamespaceAliasDecl>()) {
3616 if (DeclContext *DC = computeDeclContext(SS, false))
3617 Diag(IdentLoc, diag::err_using_directive_member_suggest)
3618 << NamespcName << DC << Corrected << SS.getRange()
3619 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3620 else
3621 Diag(IdentLoc, diag::err_using_directive_suggest)
3622 << NamespcName << Corrected
3623 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3624 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
3625 << Corrected;
3626
3627 NamespcName = Corrected.getAsIdentifierInfo();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00003628 } else {
3629 R.clear();
3630 R.setLookupName(NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00003631 }
3632 }
3633 }
3634
John McCallf36e02d2009-10-09 21:13:30 +00003635 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003636 NamedDecl *Named = R.getFoundDecl();
3637 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
3638 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003639 // C++ [namespace.udir]p1:
3640 // A using-directive specifies that the names in the nominated
3641 // namespace can be used in the scope in which the
3642 // using-directive appears after the using-directive. During
3643 // unqualified name lookup (3.4.1), the names appear as if they
3644 // were declared in the nearest enclosing namespace which
3645 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00003646 // namespace. [Note: in this context, "contains" means "contains
3647 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003648
3649 // Find enclosing context containing both using-directive and
3650 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003651 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003652 DeclContext *CommonAncestor = cast<DeclContext>(NS);
3653 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
3654 CommonAncestor = CommonAncestor->getParent();
3655
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003656 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor8419fa32009-05-30 06:31:56 +00003657 SS.getRange(),
3658 (NestedNameSpecifier *)SS.getScopeRep(),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003659 IdentLoc, Named, CommonAncestor);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003660 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00003661 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00003662 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00003663 }
3664
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003665 // FIXME: We ignore attributes for now.
John McCalld226f652010-08-21 09:40:31 +00003666 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003667}
3668
3669void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
3670 // If scope has associated entity, then using directive is at namespace
3671 // or translation unit scope. We add UsingDirectiveDecls, into
3672 // it's lookup structure.
3673 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003674 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003675 else
3676 // Otherwise it is block-sope. using-directives will affect lookup
3677 // only to the end of scope.
John McCalld226f652010-08-21 09:40:31 +00003678 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00003679}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003680
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003681
John McCalld226f652010-08-21 09:40:31 +00003682Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00003683 AccessSpecifier AS,
3684 bool HasUsingKeyword,
3685 SourceLocation UsingLoc,
3686 CXXScopeSpec &SS,
3687 UnqualifiedId &Name,
3688 AttributeList *AttrList,
3689 bool IsTypeName,
3690 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003691 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00003692
Douglas Gregor12c118a2009-11-04 16:30:06 +00003693 switch (Name.getKind()) {
3694 case UnqualifiedId::IK_Identifier:
3695 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00003696 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00003697 case UnqualifiedId::IK_ConversionFunctionId:
3698 break;
3699
3700 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00003701 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall604e7f12009-12-08 07:46:18 +00003702 // C++0x inherited constructors.
3703 if (getLangOptions().CPlusPlus0x) break;
3704
Douglas Gregor12c118a2009-11-04 16:30:06 +00003705 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
3706 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00003707 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00003708
3709 case UnqualifiedId::IK_DestructorName:
3710 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
3711 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00003712 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00003713
3714 case UnqualifiedId::IK_TemplateId:
3715 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
3716 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00003717 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00003718 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003719
3720 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
3721 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00003722 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00003723 return 0;
John McCall604e7f12009-12-08 07:46:18 +00003724
John McCall60fa3cf2009-12-11 02:10:03 +00003725 // Warn about using declarations.
3726 // TODO: store that the declaration was written without 'using' and
3727 // talk about access decls instead of using decls in the
3728 // diagnostics.
3729 if (!HasUsingKeyword) {
3730 UsingLoc = Name.getSourceRange().getBegin();
3731
3732 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00003733 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00003734 }
3735
Douglas Gregor56c04582010-12-16 00:46:58 +00003736 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
3737 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
3738 return 0;
3739
John McCall9488ea12009-11-17 05:59:44 +00003740 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003741 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00003742 /* IsInstantiation */ false,
3743 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00003744 if (UD)
3745 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00003746
John McCalld226f652010-08-21 09:40:31 +00003747 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00003748}
3749
Douglas Gregor09acc982010-07-07 23:08:52 +00003750/// \brief Determine whether a using declaration considers the given
3751/// declarations as "equivalent", e.g., if they are redeclarations of
3752/// the same entity or are both typedefs of the same type.
3753static bool
3754IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
3755 bool &SuppressRedeclaration) {
3756 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
3757 SuppressRedeclaration = false;
3758 return true;
3759 }
3760
3761 if (TypedefDecl *TD1 = dyn_cast<TypedefDecl>(D1))
3762 if (TypedefDecl *TD2 = dyn_cast<TypedefDecl>(D2)) {
3763 SuppressRedeclaration = true;
3764 return Context.hasSameType(TD1->getUnderlyingType(),
3765 TD2->getUnderlyingType());
3766 }
3767
3768 return false;
3769}
3770
3771
John McCall9f54ad42009-12-10 09:41:52 +00003772/// Determines whether to create a using shadow decl for a particular
3773/// decl, given the set of decls existing prior to this using lookup.
3774bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
3775 const LookupResult &Previous) {
3776 // Diagnose finding a decl which is not from a base class of the
3777 // current class. We do this now because there are cases where this
3778 // function will silently decide not to build a shadow decl, which
3779 // will pre-empt further diagnostics.
3780 //
3781 // We don't need to do this in C++0x because we do the check once on
3782 // the qualifier.
3783 //
3784 // FIXME: diagnose the following if we care enough:
3785 // struct A { int foo; };
3786 // struct B : A { using A::foo; };
3787 // template <class T> struct C : A {};
3788 // template <class T> struct D : C<T> { using B::foo; } // <---
3789 // This is invalid (during instantiation) in C++03 because B::foo
3790 // resolves to the using decl in B, which is not a base class of D<T>.
3791 // We can't diagnose it immediately because C<T> is an unknown
3792 // specialization. The UsingShadowDecl in D<T> then points directly
3793 // to A::foo, which will look well-formed when we instantiate.
3794 // The right solution is to not collapse the shadow-decl chain.
3795 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
3796 DeclContext *OrigDC = Orig->getDeclContext();
3797
3798 // Handle enums and anonymous structs.
3799 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
3800 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
3801 while (OrigRec->isAnonymousStructOrUnion())
3802 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
3803
3804 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
3805 if (OrigDC == CurContext) {
3806 Diag(Using->getLocation(),
3807 diag::err_using_decl_nested_name_specifier_is_current_class)
3808 << Using->getNestedNameRange();
3809 Diag(Orig->getLocation(), diag::note_using_decl_target);
3810 return true;
3811 }
3812
3813 Diag(Using->getNestedNameRange().getBegin(),
3814 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3815 << Using->getTargetNestedNameDecl()
3816 << cast<CXXRecordDecl>(CurContext)
3817 << Using->getNestedNameRange();
3818 Diag(Orig->getLocation(), diag::note_using_decl_target);
3819 return true;
3820 }
3821 }
3822
3823 if (Previous.empty()) return false;
3824
3825 NamedDecl *Target = Orig;
3826 if (isa<UsingShadowDecl>(Target))
3827 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3828
John McCalld7533ec2009-12-11 02:33:26 +00003829 // If the target happens to be one of the previous declarations, we
3830 // don't have a conflict.
3831 //
3832 // FIXME: but we might be increasing its access, in which case we
3833 // should redeclare it.
3834 NamedDecl *NonTag = 0, *Tag = 0;
3835 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3836 I != E; ++I) {
3837 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00003838 bool Result;
3839 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
3840 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00003841
3842 (isa<TagDecl>(D) ? Tag : NonTag) = D;
3843 }
3844
John McCall9f54ad42009-12-10 09:41:52 +00003845 if (Target->isFunctionOrFunctionTemplate()) {
3846 FunctionDecl *FD;
3847 if (isa<FunctionTemplateDecl>(Target))
3848 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
3849 else
3850 FD = cast<FunctionDecl>(Target);
3851
3852 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00003853 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00003854 case Ovl_Overload:
3855 return false;
3856
3857 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00003858 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003859 break;
3860
3861 // We found a decl with the exact signature.
3862 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00003863 // If we're in a record, we want to hide the target, so we
3864 // return true (without a diagnostic) to tell the caller not to
3865 // build a shadow decl.
3866 if (CurContext->isRecord())
3867 return true;
3868
3869 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00003870 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003871 break;
3872 }
3873
3874 Diag(Target->getLocation(), diag::note_using_decl_target);
3875 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
3876 return true;
3877 }
3878
3879 // Target is not a function.
3880
John McCall9f54ad42009-12-10 09:41:52 +00003881 if (isa<TagDecl>(Target)) {
3882 // No conflict between a tag and a non-tag.
3883 if (!Tag) return false;
3884
John McCall41ce66f2009-12-10 19:51:03 +00003885 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003886 Diag(Target->getLocation(), diag::note_using_decl_target);
3887 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
3888 return true;
3889 }
3890
3891 // No conflict between a tag and a non-tag.
3892 if (!NonTag) return false;
3893
John McCall41ce66f2009-12-10 19:51:03 +00003894 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003895 Diag(Target->getLocation(), diag::note_using_decl_target);
3896 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
3897 return true;
3898}
3899
John McCall9488ea12009-11-17 05:59:44 +00003900/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00003901UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00003902 UsingDecl *UD,
3903 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00003904
3905 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00003906 NamedDecl *Target = Orig;
3907 if (isa<UsingShadowDecl>(Target)) {
3908 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3909 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00003910 }
3911
3912 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00003913 = UsingShadowDecl::Create(Context, CurContext,
3914 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00003915 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00003916
3917 Shadow->setAccess(UD->getAccess());
3918 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
3919 Shadow->setInvalidDecl();
3920
John McCall9488ea12009-11-17 05:59:44 +00003921 if (S)
John McCall604e7f12009-12-08 07:46:18 +00003922 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00003923 else
John McCall604e7f12009-12-08 07:46:18 +00003924 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00003925
John McCall604e7f12009-12-08 07:46:18 +00003926
John McCall9f54ad42009-12-10 09:41:52 +00003927 return Shadow;
3928}
John McCall604e7f12009-12-08 07:46:18 +00003929
John McCall9f54ad42009-12-10 09:41:52 +00003930/// Hides a using shadow declaration. This is required by the current
3931/// using-decl implementation when a resolvable using declaration in a
3932/// class is followed by a declaration which would hide or override
3933/// one or more of the using decl's targets; for example:
3934///
3935/// struct Base { void foo(int); };
3936/// struct Derived : Base {
3937/// using Base::foo;
3938/// void foo(int);
3939/// };
3940///
3941/// The governing language is C++03 [namespace.udecl]p12:
3942///
3943/// When a using-declaration brings names from a base class into a
3944/// derived class scope, member functions in the derived class
3945/// override and/or hide member functions with the same name and
3946/// parameter types in a base class (rather than conflicting).
3947///
3948/// There are two ways to implement this:
3949/// (1) optimistically create shadow decls when they're not hidden
3950/// by existing declarations, or
3951/// (2) don't create any shadow decls (or at least don't make them
3952/// visible) until we've fully parsed/instantiated the class.
3953/// The problem with (1) is that we might have to retroactively remove
3954/// a shadow decl, which requires several O(n) operations because the
3955/// decl structures are (very reasonably) not designed for removal.
3956/// (2) avoids this but is very fiddly and phase-dependent.
3957void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00003958 if (Shadow->getDeclName().getNameKind() ==
3959 DeclarationName::CXXConversionFunctionName)
3960 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
3961
John McCall9f54ad42009-12-10 09:41:52 +00003962 // Remove it from the DeclContext...
3963 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00003964
John McCall9f54ad42009-12-10 09:41:52 +00003965 // ...and the scope, if applicable...
3966 if (S) {
John McCalld226f652010-08-21 09:40:31 +00003967 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00003968 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00003969 }
3970
John McCall9f54ad42009-12-10 09:41:52 +00003971 // ...and the using decl.
3972 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
3973
3974 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00003975 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00003976}
3977
John McCall7ba107a2009-11-18 02:36:19 +00003978/// Builds a using declaration.
3979///
3980/// \param IsInstantiation - Whether this call arises from an
3981/// instantiation of an unresolved using declaration. We treat
3982/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00003983NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
3984 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003985 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003986 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00003987 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00003988 bool IsInstantiation,
3989 bool IsTypeName,
3990 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00003991 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003992 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00003993 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00003994
Anders Carlsson550b14b2009-08-28 05:49:21 +00003995 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00003996
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003997 if (SS.isEmpty()) {
3998 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00003999 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00004000 }
Mike Stump1eb44332009-09-09 15:08:12 +00004001
John McCall9f54ad42009-12-10 09:41:52 +00004002 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00004003 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00004004 ForRedeclaration);
4005 Previous.setHideTags(false);
4006 if (S) {
4007 LookupName(Previous, S);
4008
4009 // It is really dumb that we have to do this.
4010 LookupResult::Filter F = Previous.makeFilter();
4011 while (F.hasNext()) {
4012 NamedDecl *D = F.next();
4013 if (!isDeclInScope(D, CurContext, S))
4014 F.erase();
4015 }
4016 F.done();
4017 } else {
4018 assert(IsInstantiation && "no scope in non-instantiation");
4019 assert(CurContext->isRecord() && "scope not record in instantiation");
4020 LookupQualifiedName(Previous, CurContext);
4021 }
4022
Mike Stump1eb44332009-09-09 15:08:12 +00004023 NestedNameSpecifier *NNS =
Anders Carlssoncf9f9212009-08-28 03:16:11 +00004024 static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4025
John McCall9f54ad42009-12-10 09:41:52 +00004026 // Check for invalid redeclarations.
4027 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
4028 return 0;
4029
4030 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00004031 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
4032 return 0;
4033
John McCallaf8e6ed2009-11-12 03:15:40 +00004034 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00004035 NamedDecl *D;
John McCallaf8e6ed2009-11-12 03:15:40 +00004036 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00004037 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00004038 // FIXME: not all declaration name kinds are legal here
4039 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
4040 UsingLoc, TypenameLoc,
4041 SS.getRange(), NNS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00004042 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00004043 } else {
4044 D = UnresolvedUsingValueDecl::Create(Context, CurContext,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00004045 UsingLoc, SS.getRange(),
4046 NNS, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00004047 }
John McCalled976492009-12-04 22:46:56 +00004048 } else {
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00004049 D = UsingDecl::Create(Context, CurContext,
4050 SS.getRange(), UsingLoc, NNS, NameInfo,
John McCalled976492009-12-04 22:46:56 +00004051 IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00004052 }
John McCalled976492009-12-04 22:46:56 +00004053 D->setAccess(AS);
4054 CurContext->addDecl(D);
4055
4056 if (!LookupContext) return D;
4057 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00004058
John McCall77bb1aa2010-05-01 00:40:08 +00004059 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00004060 UD->setInvalidDecl();
4061 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00004062 }
4063
John McCall604e7f12009-12-08 07:46:18 +00004064 // Look up the target name.
4065
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00004066 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00004067
John McCall604e7f12009-12-08 07:46:18 +00004068 // Unlike most lookups, we don't always want to hide tag
4069 // declarations: tag names are visible through the using declaration
4070 // even if hidden by ordinary names, *except* in a dependent context
4071 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00004072 if (!IsInstantiation)
4073 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00004074
John McCalla24dc2e2009-11-17 02:14:36 +00004075 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00004076
John McCallf36e02d2009-10-09 21:13:30 +00004077 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00004078 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00004079 << NameInfo.getName() << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00004080 UD->setInvalidDecl();
4081 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00004082 }
4083
John McCalled976492009-12-04 22:46:56 +00004084 if (R.isAmbiguous()) {
4085 UD->setInvalidDecl();
4086 return UD;
4087 }
Mike Stump1eb44332009-09-09 15:08:12 +00004088
John McCall7ba107a2009-11-18 02:36:19 +00004089 if (IsTypeName) {
4090 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00004091 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00004092 Diag(IdentLoc, diag::err_using_typename_non_type);
4093 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
4094 Diag((*I)->getUnderlyingDecl()->getLocation(),
4095 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00004096 UD->setInvalidDecl();
4097 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00004098 }
4099 } else {
4100 // If we asked for a non-typename and we got a type, error out,
4101 // but only if this is an instantiation of an unresolved using
4102 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00004103 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00004104 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
4105 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00004106 UD->setInvalidDecl();
4107 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00004108 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00004109 }
4110
Anders Carlsson73b39cf2009-08-28 03:35:18 +00004111 // C++0x N2914 [namespace.udecl]p6:
4112 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00004113 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00004114 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
4115 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00004116 UD->setInvalidDecl();
4117 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00004118 }
Mike Stump1eb44332009-09-09 15:08:12 +00004119
John McCall9f54ad42009-12-10 09:41:52 +00004120 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
4121 if (!CheckUsingShadowDecl(UD, *I, Previous))
4122 BuildUsingShadowDecl(S, UD, *I);
4123 }
John McCall9488ea12009-11-17 05:59:44 +00004124
4125 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00004126}
4127
John McCall9f54ad42009-12-10 09:41:52 +00004128/// Checks that the given using declaration is not an invalid
4129/// redeclaration. Note that this is checking only for the using decl
4130/// itself, not for any ill-formedness among the UsingShadowDecls.
4131bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
4132 bool isTypeName,
4133 const CXXScopeSpec &SS,
4134 SourceLocation NameLoc,
4135 const LookupResult &Prev) {
4136 // C++03 [namespace.udecl]p8:
4137 // C++0x [namespace.udecl]p10:
4138 // A using-declaration is a declaration and can therefore be used
4139 // repeatedly where (and only where) multiple declarations are
4140 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00004141 //
John McCall8a726212010-11-29 18:01:58 +00004142 // That's in non-member contexts.
4143 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00004144 return false;
4145
4146 NestedNameSpecifier *Qual
4147 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
4148
4149 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
4150 NamedDecl *D = *I;
4151
4152 bool DTypename;
4153 NestedNameSpecifier *DQual;
4154 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
4155 DTypename = UD->isTypeName();
4156 DQual = UD->getTargetNestedNameDecl();
4157 } else if (UnresolvedUsingValueDecl *UD
4158 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
4159 DTypename = false;
4160 DQual = UD->getTargetNestedNameSpecifier();
4161 } else if (UnresolvedUsingTypenameDecl *UD
4162 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
4163 DTypename = true;
4164 DQual = UD->getTargetNestedNameSpecifier();
4165 } else continue;
4166
4167 // using decls differ if one says 'typename' and the other doesn't.
4168 // FIXME: non-dependent using decls?
4169 if (isTypeName != DTypename) continue;
4170
4171 // using decls differ if they name different scopes (but note that
4172 // template instantiation can cause this check to trigger when it
4173 // didn't before instantiation).
4174 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
4175 Context.getCanonicalNestedNameSpecifier(DQual))
4176 continue;
4177
4178 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00004179 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00004180 return true;
4181 }
4182
4183 return false;
4184}
4185
John McCall604e7f12009-12-08 07:46:18 +00004186
John McCalled976492009-12-04 22:46:56 +00004187/// Checks that the given nested-name qualifier used in a using decl
4188/// in the current context is appropriately related to the current
4189/// scope. If an error is found, diagnoses it and returns true.
4190bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
4191 const CXXScopeSpec &SS,
4192 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00004193 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00004194
John McCall604e7f12009-12-08 07:46:18 +00004195 if (!CurContext->isRecord()) {
4196 // C++03 [namespace.udecl]p3:
4197 // C++0x [namespace.udecl]p8:
4198 // A using-declaration for a class member shall be a member-declaration.
4199
4200 // If we weren't able to compute a valid scope, it must be a
4201 // dependent class scope.
4202 if (!NamedContext || NamedContext->isRecord()) {
4203 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
4204 << SS.getRange();
4205 return true;
4206 }
4207
4208 // Otherwise, everything is known to be fine.
4209 return false;
4210 }
4211
4212 // The current scope is a record.
4213
4214 // If the named context is dependent, we can't decide much.
4215 if (!NamedContext) {
4216 // FIXME: in C++0x, we can diagnose if we can prove that the
4217 // nested-name-specifier does not refer to a base class, which is
4218 // still possible in some cases.
4219
4220 // Otherwise we have to conservatively report that things might be
4221 // okay.
4222 return false;
4223 }
4224
4225 if (!NamedContext->isRecord()) {
4226 // Ideally this would point at the last name in the specifier,
4227 // but we don't have that level of source info.
4228 Diag(SS.getRange().getBegin(),
4229 diag::err_using_decl_nested_name_specifier_is_not_class)
4230 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
4231 return true;
4232 }
4233
Douglas Gregor6fb07292010-12-21 07:41:49 +00004234 if (!NamedContext->isDependentContext() &&
4235 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
4236 return true;
4237
John McCall604e7f12009-12-08 07:46:18 +00004238 if (getLangOptions().CPlusPlus0x) {
4239 // C++0x [namespace.udecl]p3:
4240 // In a using-declaration used as a member-declaration, the
4241 // nested-name-specifier shall name a base class of the class
4242 // being defined.
4243
4244 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
4245 cast<CXXRecordDecl>(NamedContext))) {
4246 if (CurContext == NamedContext) {
4247 Diag(NameLoc,
4248 diag::err_using_decl_nested_name_specifier_is_current_class)
4249 << SS.getRange();
4250 return true;
4251 }
4252
4253 Diag(SS.getRange().getBegin(),
4254 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4255 << (NestedNameSpecifier*) SS.getScopeRep()
4256 << cast<CXXRecordDecl>(CurContext)
4257 << SS.getRange();
4258 return true;
4259 }
4260
4261 return false;
4262 }
4263
4264 // C++03 [namespace.udecl]p4:
4265 // A using-declaration used as a member-declaration shall refer
4266 // to a member of a base class of the class being defined [etc.].
4267
4268 // Salient point: SS doesn't have to name a base class as long as
4269 // lookup only finds members from base classes. Therefore we can
4270 // diagnose here only if we can prove that that can't happen,
4271 // i.e. if the class hierarchies provably don't intersect.
4272
4273 // TODO: it would be nice if "definitely valid" results were cached
4274 // in the UsingDecl and UsingShadowDecl so that these checks didn't
4275 // need to be repeated.
4276
4277 struct UserData {
4278 llvm::DenseSet<const CXXRecordDecl*> Bases;
4279
4280 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
4281 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4282 Data->Bases.insert(Base);
4283 return true;
4284 }
4285
4286 bool hasDependentBases(const CXXRecordDecl *Class) {
4287 return !Class->forallBases(collect, this);
4288 }
4289
4290 /// Returns true if the base is dependent or is one of the
4291 /// accumulated base classes.
4292 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
4293 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4294 return !Data->Bases.count(Base);
4295 }
4296
4297 bool mightShareBases(const CXXRecordDecl *Class) {
4298 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
4299 }
4300 };
4301
4302 UserData Data;
4303
4304 // Returns false if we find a dependent base.
4305 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
4306 return false;
4307
4308 // Returns false if the class has a dependent base or if it or one
4309 // of its bases is present in the base set of the current context.
4310 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
4311 return false;
4312
4313 Diag(SS.getRange().getBegin(),
4314 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4315 << (NestedNameSpecifier*) SS.getScopeRep()
4316 << cast<CXXRecordDecl>(CurContext)
4317 << SS.getRange();
4318
4319 return true;
John McCalled976492009-12-04 22:46:56 +00004320}
4321
John McCalld226f652010-08-21 09:40:31 +00004322Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00004323 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00004324 SourceLocation AliasLoc,
4325 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00004326 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00004327 SourceLocation IdentLoc,
4328 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00004329
Anders Carlsson81c85c42009-03-28 23:53:49 +00004330 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00004331 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
4332 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00004333
Anders Carlsson8d7ba402009-03-28 06:23:46 +00004334 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00004335 NamedDecl *PrevDecl
4336 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
4337 ForRedeclaration);
4338 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
4339 PrevDecl = 0;
4340
4341 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00004342 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00004343 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00004344 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00004345 // FIXME: At some point, we'll want to create the (redundant)
4346 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00004347 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00004348 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00004349 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00004350 }
Mike Stump1eb44332009-09-09 15:08:12 +00004351
Anders Carlsson8d7ba402009-03-28 06:23:46 +00004352 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
4353 diag::err_redefinition_different_kind;
4354 Diag(AliasLoc, DiagID) << Alias;
4355 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00004356 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00004357 }
4358
John McCalla24dc2e2009-11-17 02:14:36 +00004359 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00004360 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004361
John McCallf36e02d2009-10-09 21:13:30 +00004362 if (R.empty()) {
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00004363 if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
4364 CTC_NoKeywords, 0)) {
4365 if (R.getAsSingle<NamespaceDecl>() ||
4366 R.getAsSingle<NamespaceAliasDecl>()) {
4367 if (DeclContext *DC = computeDeclContext(SS, false))
4368 Diag(IdentLoc, diag::err_using_directive_member_suggest)
4369 << Ident << DC << Corrected << SS.getRange()
4370 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4371 else
4372 Diag(IdentLoc, diag::err_using_directive_suggest)
4373 << Ident << Corrected
4374 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4375
4376 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
4377 << Corrected;
4378
4379 Ident = Corrected.getAsIdentifierInfo();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00004380 } else {
4381 R.clear();
4382 R.setLookupName(Ident);
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00004383 }
4384 }
4385
4386 if (R.empty()) {
4387 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00004388 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00004389 }
Anders Carlsson5721c682009-03-28 06:42:02 +00004390 }
Mike Stump1eb44332009-09-09 15:08:12 +00004391
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00004392 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00004393 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
4394 Alias, SS.getRange(),
Douglas Gregor6c9c9402009-05-30 06:48:27 +00004395 (NestedNameSpecifier *)SS.getScopeRep(),
John McCallf36e02d2009-10-09 21:13:30 +00004396 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00004397
John McCall3dbd3d52010-02-16 06:53:13 +00004398 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00004399 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00004400}
4401
Douglas Gregor39957dc2010-05-01 15:04:51 +00004402namespace {
4403 /// \brief Scoped object used to handle the state changes required in Sema
4404 /// to implicitly define the body of a C++ member function;
4405 class ImplicitlyDefinedFunctionScope {
4406 Sema &S;
4407 DeclContext *PreviousContext;
4408
4409 public:
4410 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
4411 : S(S), PreviousContext(S.CurContext)
4412 {
4413 S.CurContext = Method;
4414 S.PushFunctionScope();
4415 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
4416 }
4417
4418 ~ImplicitlyDefinedFunctionScope() {
4419 S.PopExpressionEvaluationContext();
4420 S.PopFunctionOrBlockScope();
4421 S.CurContext = PreviousContext;
4422 }
4423 };
4424}
4425
Sebastian Redl751025d2010-09-13 22:02:47 +00004426static CXXConstructorDecl *getDefaultConstructorUnsafe(Sema &Self,
4427 CXXRecordDecl *D) {
4428 ASTContext &Context = Self.Context;
4429 QualType ClassType = Context.getTypeDeclType(D);
4430 DeclarationName ConstructorName
4431 = Context.DeclarationNames.getCXXConstructorName(
4432 Context.getCanonicalType(ClassType.getUnqualifiedType()));
4433
4434 DeclContext::lookup_const_iterator Con, ConEnd;
4435 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
4436 Con != ConEnd; ++Con) {
4437 // FIXME: In C++0x, a constructor template can be a default constructor.
4438 if (isa<FunctionTemplateDecl>(*Con))
4439 continue;
4440
4441 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
4442 if (Constructor->isDefaultConstructor())
4443 return Constructor;
4444 }
4445 return 0;
4446}
4447
Douglas Gregor23c94db2010-07-02 17:43:08 +00004448CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
4449 CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00004450 // C++ [class.ctor]p5:
4451 // A default constructor for a class X is a constructor of class X
4452 // that can be called without an argument. If there is no
4453 // user-declared constructor for class X, a default constructor is
4454 // implicitly declared. An implicitly-declared default constructor
4455 // is an inline public member of its class.
Douglas Gregor18274032010-07-03 00:47:00 +00004456 assert(!ClassDecl->hasUserDeclaredConstructor() &&
4457 "Should not build implicit default constructor!");
4458
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004459 // C++ [except.spec]p14:
4460 // An implicitly declared special member function (Clause 12) shall have an
4461 // exception-specification. [...]
4462 ImplicitExceptionSpecification ExceptSpec(Context);
4463
4464 // Direct base-class destructors.
4465 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4466 BEnd = ClassDecl->bases_end();
4467 B != BEnd; ++B) {
4468 if (B->isVirtual()) // Handled below.
4469 continue;
4470
Douglas Gregor18274032010-07-03 00:47:00 +00004471 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
4472 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4473 if (!BaseClassDecl->hasDeclaredDefaultConstructor())
4474 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
Sebastian Redl751025d2010-09-13 22:02:47 +00004475 else if (CXXConstructorDecl *Constructor
4476 = getDefaultConstructorUnsafe(*this, BaseClassDecl))
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004477 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00004478 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004479 }
4480
4481 // Virtual base-class destructors.
4482 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
4483 BEnd = ClassDecl->vbases_end();
4484 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00004485 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
4486 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4487 if (!BaseClassDecl->hasDeclaredDefaultConstructor())
4488 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
4489 else if (CXXConstructorDecl *Constructor
Sebastian Redl751025d2010-09-13 22:02:47 +00004490 = getDefaultConstructorUnsafe(*this, BaseClassDecl))
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004491 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00004492 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004493 }
4494
4495 // Field destructors.
4496 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4497 FEnd = ClassDecl->field_end();
4498 F != FEnd; ++F) {
4499 if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00004500 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
4501 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4502 if (!FieldClassDecl->hasDeclaredDefaultConstructor())
4503 ExceptSpec.CalledDecl(
4504 DeclareImplicitDefaultConstructor(FieldClassDecl));
4505 else if (CXXConstructorDecl *Constructor
Sebastian Redl751025d2010-09-13 22:02:47 +00004506 = getDefaultConstructorUnsafe(*this, FieldClassDecl))
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004507 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00004508 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004509 }
John McCalle23cf432010-12-14 08:05:40 +00004510
4511 FunctionProtoType::ExtProtoInfo EPI;
4512 EPI.HasExceptionSpec = ExceptSpec.hasExceptionSpecification();
4513 EPI.HasAnyExceptionSpec = ExceptSpec.hasAnyExceptionSpecification();
4514 EPI.NumExceptions = ExceptSpec.size();
4515 EPI.Exceptions = ExceptSpec.data();
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004516
4517 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00004518 CanQualType ClassType
4519 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
4520 DeclarationName Name
4521 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnara25777432010-08-11 22:01:17 +00004522 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregor32df23e2010-07-01 22:02:46 +00004523 CXXConstructorDecl *DefaultCon
Abramo Bagnara25777432010-08-11 22:01:17 +00004524 = CXXConstructorDecl::Create(Context, ClassDecl, NameInfo,
Douglas Gregor32df23e2010-07-01 22:02:46 +00004525 Context.getFunctionType(Context.VoidTy,
John McCalle23cf432010-12-14 08:05:40 +00004526 0, 0, EPI),
Douglas Gregor32df23e2010-07-01 22:02:46 +00004527 /*TInfo=*/0,
4528 /*isExplicit=*/false,
4529 /*isInline=*/true,
4530 /*isImplicitlyDeclared=*/true);
4531 DefaultCon->setAccess(AS_public);
4532 DefaultCon->setImplicit();
4533 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Douglas Gregor18274032010-07-03 00:47:00 +00004534
4535 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00004536 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
4537
Douglas Gregor23c94db2010-07-02 17:43:08 +00004538 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00004539 PushOnScopeChains(DefaultCon, S, false);
4540 ClassDecl->addDecl(DefaultCon);
4541
Douglas Gregor32df23e2010-07-01 22:02:46 +00004542 return DefaultCon;
4543}
4544
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00004545void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
4546 CXXConstructorDecl *Constructor) {
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00004547 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
Douglas Gregorc070cc62010-06-17 23:14:26 +00004548 !Constructor->isUsed(false)) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00004549 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00004550
Anders Carlssonf6513ed2010-04-23 16:04:08 +00004551 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00004552 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00004553
Douglas Gregor39957dc2010-05-01 15:04:51 +00004554 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00004555 DiagnosticErrorTrap Trap(Diags);
Sean Huntcbb67482011-01-08 20:30:50 +00004556 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00004557 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00004558 Diag(CurrentLocation, diag::note_member_synthesized_at)
Anders Carlsson3b8c53b2010-04-22 05:40:53 +00004559 << CXXConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00004560 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00004561 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00004562 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00004563
4564 SourceLocation Loc = Constructor->getLocation();
4565 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
4566
4567 Constructor->setUsed();
4568 MarkVTableUsed(CurrentLocation, ClassDecl);
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00004569}
4570
Douglas Gregor23c94db2010-07-02 17:43:08 +00004571CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004572 // C++ [class.dtor]p2:
4573 // If a class has no user-declared destructor, a destructor is
4574 // declared implicitly. An implicitly-declared destructor is an
4575 // inline public member of its class.
4576
4577 // C++ [except.spec]p14:
4578 // An implicitly declared special member function (Clause 12) shall have
4579 // an exception-specification.
4580 ImplicitExceptionSpecification ExceptSpec(Context);
4581
4582 // Direct base-class destructors.
4583 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4584 BEnd = ClassDecl->bases_end();
4585 B != BEnd; ++B) {
4586 if (B->isVirtual()) // Handled below.
4587 continue;
4588
4589 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
4590 ExceptSpec.CalledDecl(
Douglas Gregordb89f282010-07-01 22:47:18 +00004591 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004592 }
4593
4594 // Virtual base-class destructors.
4595 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
4596 BEnd = ClassDecl->vbases_end();
4597 B != BEnd; ++B) {
4598 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
4599 ExceptSpec.CalledDecl(
Douglas Gregordb89f282010-07-01 22:47:18 +00004600 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004601 }
4602
4603 // Field destructors.
4604 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4605 FEnd = ClassDecl->field_end();
4606 F != FEnd; ++F) {
4607 if (const RecordType *RecordTy
4608 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
4609 ExceptSpec.CalledDecl(
Douglas Gregordb89f282010-07-01 22:47:18 +00004610 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004611 }
4612
Douglas Gregor4923aa22010-07-02 20:37:36 +00004613 // Create the actual destructor declaration.
John McCalle23cf432010-12-14 08:05:40 +00004614 FunctionProtoType::ExtProtoInfo EPI;
4615 EPI.HasExceptionSpec = ExceptSpec.hasExceptionSpecification();
4616 EPI.HasAnyExceptionSpec = ExceptSpec.hasAnyExceptionSpecification();
4617 EPI.NumExceptions = ExceptSpec.size();
4618 EPI.Exceptions = ExceptSpec.data();
4619 QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004620
4621 CanQualType ClassType
4622 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
4623 DeclarationName Name
4624 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnara25777432010-08-11 22:01:17 +00004625 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004626 CXXDestructorDecl *Destructor
Craig Silversteinb41d8992010-10-21 00:44:50 +00004627 = CXXDestructorDecl::Create(Context, ClassDecl, NameInfo, Ty, 0,
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004628 /*isInline=*/true,
4629 /*isImplicitlyDeclared=*/true);
4630 Destructor->setAccess(AS_public);
4631 Destructor->setImplicit();
4632 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor4923aa22010-07-02 20:37:36 +00004633
4634 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00004635 ++ASTContext::NumImplicitDestructorsDeclared;
4636
4637 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00004638 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00004639 PushOnScopeChains(Destructor, S, false);
4640 ClassDecl->addDecl(Destructor);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004641
4642 // This could be uniqued if it ever proves significant.
4643 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
4644
4645 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor4923aa22010-07-02 20:37:36 +00004646
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004647 return Destructor;
4648}
4649
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004650void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00004651 CXXDestructorDecl *Destructor) {
Douglas Gregorc070cc62010-06-17 23:14:26 +00004652 assert((Destructor->isImplicit() && !Destructor->isUsed(false)) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004653 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00004654 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004655 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004656
Douglas Gregorc63d2c82010-05-12 16:39:35 +00004657 if (Destructor->isInvalidDecl())
4658 return;
4659
Douglas Gregor39957dc2010-05-01 15:04:51 +00004660 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004661
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00004662 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00004663 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
4664 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00004665
Douglas Gregorc63d2c82010-05-12 16:39:35 +00004666 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00004667 Diag(CurrentLocation, diag::note_member_synthesized_at)
4668 << CXXDestructor << Context.getTagDeclType(ClassDecl);
4669
4670 Destructor->setInvalidDecl();
4671 return;
4672 }
4673
Douglas Gregor4ada9d32010-09-20 16:48:21 +00004674 SourceLocation Loc = Destructor->getLocation();
4675 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
4676
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004677 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004678 MarkVTableUsed(CurrentLocation, ClassDecl);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004679}
4680
Douglas Gregor06a9f362010-05-01 20:49:11 +00004681/// \brief Builds a statement that copies the given entity from \p From to
4682/// \c To.
4683///
4684/// This routine is used to copy the members of a class with an
4685/// implicitly-declared copy assignment operator. When the entities being
4686/// copied are arrays, this routine builds for loops to copy them.
4687///
4688/// \param S The Sema object used for type-checking.
4689///
4690/// \param Loc The location where the implicit copy is being generated.
4691///
4692/// \param T The type of the expressions being copied. Both expressions must
4693/// have this type.
4694///
4695/// \param To The expression we are copying to.
4696///
4697/// \param From The expression we are copying from.
4698///
Douglas Gregor6cdc1612010-05-04 15:20:55 +00004699/// \param CopyingBaseSubobject Whether we're copying a base subobject.
4700/// Otherwise, it's a non-static member subobject.
4701///
Douglas Gregor06a9f362010-05-01 20:49:11 +00004702/// \param Depth Internal parameter recording the depth of the recursion.
4703///
4704/// \returns A statement or a loop that copies the expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00004705static StmtResult
Douglas Gregor06a9f362010-05-01 20:49:11 +00004706BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCall9ae2f072010-08-23 23:25:46 +00004707 Expr *To, Expr *From,
Douglas Gregor6cdc1612010-05-04 15:20:55 +00004708 bool CopyingBaseSubobject, unsigned Depth = 0) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00004709 // C++0x [class.copy]p30:
4710 // Each subobject is assigned in the manner appropriate to its type:
4711 //
4712 // - if the subobject is of class type, the copy assignment operator
4713 // for the class is used (as if by explicit qualification; that is,
4714 // ignoring any possible virtual overriding functions in more derived
4715 // classes);
4716 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
4717 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4718
4719 // Look for operator=.
4720 DeclarationName Name
4721 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
4722 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
4723 S.LookupQualifiedName(OpLookup, ClassDecl, false);
4724
4725 // Filter out any result that isn't a copy-assignment operator.
4726 LookupResult::Filter F = OpLookup.makeFilter();
4727 while (F.hasNext()) {
4728 NamedDecl *D = F.next();
4729 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
4730 if (Method->isCopyAssignmentOperator())
4731 continue;
4732
4733 F.erase();
John McCallb0207482010-03-16 06:11:48 +00004734 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00004735 F.done();
4736
Douglas Gregor6cdc1612010-05-04 15:20:55 +00004737 // Suppress the protected check (C++ [class.protected]) for each of the
4738 // assignment operators we found. This strange dance is required when
4739 // we're assigning via a base classes's copy-assignment operator. To
4740 // ensure that we're getting the right base class subobject (without
4741 // ambiguities), we need to cast "this" to that subobject type; to
4742 // ensure that we don't go through the virtual call mechanism, we need
4743 // to qualify the operator= name with the base class (see below). However,
4744 // this means that if the base class has a protected copy assignment
4745 // operator, the protected member access check will fail. So, we
4746 // rewrite "protected" access to "public" access in this case, since we
4747 // know by construction that we're calling from a derived class.
4748 if (CopyingBaseSubobject) {
4749 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
4750 L != LEnd; ++L) {
4751 if (L.getAccess() == AS_protected)
4752 L.setAccess(AS_public);
4753 }
4754 }
4755
Douglas Gregor06a9f362010-05-01 20:49:11 +00004756 // Create the nested-name-specifier that will be used to qualify the
4757 // reference to operator=; this is required to suppress the virtual
4758 // call mechanism.
4759 CXXScopeSpec SS;
4760 SS.setRange(Loc);
4761 SS.setScopeRep(NestedNameSpecifier::Create(S.Context, 0, false,
4762 T.getTypePtr()));
4763
4764 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00004765 ExprResult OpEqualRef
John McCall9ae2f072010-08-23 23:25:46 +00004766 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Douglas Gregor06a9f362010-05-01 20:49:11 +00004767 /*FirstQualifierInScope=*/0, OpLookup,
4768 /*TemplateArgs=*/0,
4769 /*SuppressQualifierCheck=*/true);
4770 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004771 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00004772
4773 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00004774
John McCall60d7b3a2010-08-24 06:29:42 +00004775 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00004776 OpEqualRef.takeAs<Expr>(),
4777 Loc, &From, 1, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004778 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004779 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00004780
4781 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00004782 }
John McCallb0207482010-03-16 06:11:48 +00004783
Douglas Gregor06a9f362010-05-01 20:49:11 +00004784 // - if the subobject is of scalar type, the built-in assignment
4785 // operator is used.
4786 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
4787 if (!ArrayTy) {
John McCall2de56d12010-08-25 11:45:40 +00004788 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004789 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004790 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00004791
4792 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00004793 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00004794
4795 // - if the subobject is an array, each element is assigned, in the
4796 // manner appropriate to the element type;
4797
4798 // Construct a loop over the array bounds, e.g.,
4799 //
4800 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
4801 //
4802 // that will copy each of the array elements.
4803 QualType SizeType = S.Context.getSizeType();
4804
4805 // Create the iteration variable.
4806 IdentifierInfo *IterationVarName = 0;
4807 {
4808 llvm::SmallString<8> Str;
4809 llvm::raw_svector_ostream OS(Str);
4810 OS << "__i" << Depth;
4811 IterationVarName = &S.Context.Idents.get(OS.str());
4812 }
4813 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc,
4814 IterationVarName, SizeType,
4815 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00004816 SC_None, SC_None);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004817
4818 // Initialize the iteration variable to zero.
4819 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00004820 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00004821
4822 // Create a reference to the iteration variable; we'll use this several
4823 // times throughout.
4824 Expr *IterationVarRef
John McCallf89e55a2010-11-18 06:31:45 +00004825 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00004826 assert(IterationVarRef && "Reference to invented variable cannot fail!");
4827
4828 // Create the DeclStmt that holds the iteration variable.
4829 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
4830
4831 // Create the comparison against the array bound.
Jay Foad9f71a8f2010-12-07 08:25:34 +00004832 llvm::APInt Upper
4833 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCall9ae2f072010-08-23 23:25:46 +00004834 Expr *Comparison
John McCall3fa5cae2010-10-26 07:05:15 +00004835 = new (S.Context) BinaryOperator(IterationVarRef,
John McCallf89e55a2010-11-18 06:31:45 +00004836 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
4837 BO_NE, S.Context.BoolTy,
4838 VK_RValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004839
4840 // Create the pre-increment of the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00004841 Expr *Increment
John McCallf89e55a2010-11-18 06:31:45 +00004842 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
4843 VK_LValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004844
4845 // Subscript the "from" and "to" expressions with the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00004846 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
4847 IterationVarRef, Loc));
4848 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
4849 IterationVarRef, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00004850
4851 // Build the copy for an individual element of the array.
John McCallf89e55a2010-11-18 06:31:45 +00004852 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
4853 To, From, CopyingBaseSubobject,
4854 Depth + 1);
Douglas Gregorff331c12010-07-25 18:17:45 +00004855 if (Copy.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004856 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00004857
4858 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00004859 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00004860 S.MakeFullExpr(Comparison),
John McCalld226f652010-08-21 09:40:31 +00004861 0, S.MakeFullExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00004862 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00004863}
4864
Douglas Gregora376d102010-07-02 21:50:04 +00004865/// \brief Determine whether the given class has a copy assignment operator
4866/// that accepts a const-qualified argument.
4867static bool hasConstCopyAssignment(Sema &S, const CXXRecordDecl *CClass) {
4868 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(CClass);
4869
4870 if (!Class->hasDeclaredCopyAssignment())
4871 S.DeclareImplicitCopyAssignment(Class);
4872
4873 QualType ClassType = S.Context.getCanonicalType(S.Context.getTypeDeclType(Class));
4874 DeclarationName OpName
4875 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
4876
4877 DeclContext::lookup_const_iterator Op, OpEnd;
4878 for (llvm::tie(Op, OpEnd) = Class->lookup(OpName); Op != OpEnd; ++Op) {
4879 // C++ [class.copy]p9:
4880 // A user-declared copy assignment operator is a non-static non-template
4881 // member function of class X with exactly one parameter of type X, X&,
4882 // const X&, volatile X& or const volatile X&.
4883 const CXXMethodDecl* Method = dyn_cast<CXXMethodDecl>(*Op);
4884 if (!Method)
4885 continue;
4886
4887 if (Method->isStatic())
4888 continue;
4889 if (Method->getPrimaryTemplate())
4890 continue;
4891 const FunctionProtoType *FnType =
4892 Method->getType()->getAs<FunctionProtoType>();
4893 assert(FnType && "Overloaded operator has no prototype.");
4894 // Don't assert on this; an invalid decl might have been left in the AST.
4895 if (FnType->getNumArgs() != 1 || FnType->isVariadic())
4896 continue;
4897 bool AcceptsConst = true;
4898 QualType ArgType = FnType->getArgType(0);
4899 if (const LValueReferenceType *Ref = ArgType->getAs<LValueReferenceType>()){
4900 ArgType = Ref->getPointeeType();
4901 // Is it a non-const lvalue reference?
4902 if (!ArgType.isConstQualified())
4903 AcceptsConst = false;
4904 }
4905 if (!S.Context.hasSameUnqualifiedType(ArgType, ClassType))
4906 continue;
4907
4908 // We have a single argument of type cv X or cv X&, i.e. we've found the
4909 // copy assignment operator. Return whether it accepts const arguments.
4910 return AcceptsConst;
4911 }
4912 assert(Class->isInvalidDecl() &&
4913 "No copy assignment operator declared in valid code.");
4914 return false;
4915}
4916
Douglas Gregor23c94db2010-07-02 17:43:08 +00004917CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
Douglas Gregord3c35902010-07-01 16:36:15 +00004918 // Note: The following rules are largely analoguous to the copy
4919 // constructor rules. Note that virtual bases are not taken into account
4920 // for determining the argument type of the operator. Note also that
4921 // operators taking an object instead of a reference are allowed.
Douglas Gregor18274032010-07-03 00:47:00 +00004922
4923
Douglas Gregord3c35902010-07-01 16:36:15 +00004924 // C++ [class.copy]p10:
4925 // If the class definition does not explicitly declare a copy
4926 // assignment operator, one is declared implicitly.
4927 // The implicitly-defined copy assignment operator for a class X
4928 // will have the form
4929 //
4930 // X& X::operator=(const X&)
4931 //
4932 // if
4933 bool HasConstCopyAssignment = true;
4934
4935 // -- each direct base class B of X has a copy assignment operator
4936 // whose parameter is of type const B&, const volatile B& or B,
4937 // and
4938 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4939 BaseEnd = ClassDecl->bases_end();
4940 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
4941 assert(!Base->getType()->isDependentType() &&
4942 "Cannot generate implicit members for class with dependent bases.");
4943 const CXXRecordDecl *BaseClassDecl
4944 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora376d102010-07-02 21:50:04 +00004945 HasConstCopyAssignment = hasConstCopyAssignment(*this, BaseClassDecl);
Douglas Gregord3c35902010-07-01 16:36:15 +00004946 }
4947
4948 // -- for all the nonstatic data members of X that are of a class
4949 // type M (or array thereof), each such class type has a copy
4950 // assignment operator whose parameter is of type const M&,
4951 // const volatile M& or M.
4952 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4953 FieldEnd = ClassDecl->field_end();
4954 HasConstCopyAssignment && Field != FieldEnd;
4955 ++Field) {
4956 QualType FieldType = Context.getBaseElementType((*Field)->getType());
4957 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
4958 const CXXRecordDecl *FieldClassDecl
4959 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora376d102010-07-02 21:50:04 +00004960 HasConstCopyAssignment = hasConstCopyAssignment(*this, FieldClassDecl);
Douglas Gregord3c35902010-07-01 16:36:15 +00004961 }
4962 }
4963
4964 // Otherwise, the implicitly declared copy assignment operator will
4965 // have the form
4966 //
4967 // X& X::operator=(X&)
4968 QualType ArgType = Context.getTypeDeclType(ClassDecl);
4969 QualType RetType = Context.getLValueReferenceType(ArgType);
4970 if (HasConstCopyAssignment)
4971 ArgType = ArgType.withConst();
4972 ArgType = Context.getLValueReferenceType(ArgType);
4973
Douglas Gregorb87786f2010-07-01 17:48:08 +00004974 // C++ [except.spec]p14:
4975 // An implicitly declared special member function (Clause 12) shall have an
4976 // exception-specification. [...]
4977 ImplicitExceptionSpecification ExceptSpec(Context);
4978 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4979 BaseEnd = ClassDecl->bases_end();
4980 Base != BaseEnd; ++Base) {
Douglas Gregora376d102010-07-02 21:50:04 +00004981 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00004982 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora376d102010-07-02 21:50:04 +00004983
4984 if (!BaseClassDecl->hasDeclaredCopyAssignment())
4985 DeclareImplicitCopyAssignment(BaseClassDecl);
4986
Douglas Gregorb87786f2010-07-01 17:48:08 +00004987 if (CXXMethodDecl *CopyAssign
4988 = BaseClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
4989 ExceptSpec.CalledDecl(CopyAssign);
4990 }
4991 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4992 FieldEnd = ClassDecl->field_end();
4993 Field != FieldEnd;
4994 ++Field) {
4995 QualType FieldType = Context.getBaseElementType((*Field)->getType());
4996 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregora376d102010-07-02 21:50:04 +00004997 CXXRecordDecl *FieldClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00004998 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora376d102010-07-02 21:50:04 +00004999
5000 if (!FieldClassDecl->hasDeclaredCopyAssignment())
5001 DeclareImplicitCopyAssignment(FieldClassDecl);
5002
Douglas Gregorb87786f2010-07-01 17:48:08 +00005003 if (CXXMethodDecl *CopyAssign
5004 = FieldClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
5005 ExceptSpec.CalledDecl(CopyAssign);
5006 }
5007 }
5008
Douglas Gregord3c35902010-07-01 16:36:15 +00005009 // An implicitly-declared copy assignment operator is an inline public
5010 // member of its class.
John McCalle23cf432010-12-14 08:05:40 +00005011 FunctionProtoType::ExtProtoInfo EPI;
5012 EPI.HasExceptionSpec = ExceptSpec.hasExceptionSpecification();
5013 EPI.HasAnyExceptionSpec = ExceptSpec.hasAnyExceptionSpecification();
5014 EPI.NumExceptions = ExceptSpec.size();
5015 EPI.Exceptions = ExceptSpec.data();
Douglas Gregord3c35902010-07-01 16:36:15 +00005016 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnara25777432010-08-11 22:01:17 +00005017 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00005018 CXXMethodDecl *CopyAssignment
Abramo Bagnara25777432010-08-11 22:01:17 +00005019 = CXXMethodDecl::Create(Context, ClassDecl, NameInfo,
John McCalle23cf432010-12-14 08:05:40 +00005020 Context.getFunctionType(RetType, &ArgType, 1, EPI),
Douglas Gregord3c35902010-07-01 16:36:15 +00005021 /*TInfo=*/0, /*isStatic=*/false,
John McCalld931b082010-08-26 03:08:43 +00005022 /*StorageClassAsWritten=*/SC_None,
Douglas Gregord3c35902010-07-01 16:36:15 +00005023 /*isInline=*/true);
5024 CopyAssignment->setAccess(AS_public);
5025 CopyAssignment->setImplicit();
5026 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Douglas Gregord3c35902010-07-01 16:36:15 +00005027
5028 // Add the parameter to the operator.
5029 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
5030 ClassDecl->getLocation(),
5031 /*Id=*/0,
5032 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00005033 SC_None,
5034 SC_None, 0);
Douglas Gregord3c35902010-07-01 16:36:15 +00005035 CopyAssignment->setParams(&FromParam, 1);
5036
Douglas Gregora376d102010-07-02 21:50:04 +00005037 // Note that we have added this copy-assignment operator.
Douglas Gregora376d102010-07-02 21:50:04 +00005038 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
5039
Douglas Gregor23c94db2010-07-02 17:43:08 +00005040 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora376d102010-07-02 21:50:04 +00005041 PushOnScopeChains(CopyAssignment, S, false);
5042 ClassDecl->addDecl(CopyAssignment);
Douglas Gregord3c35902010-07-01 16:36:15 +00005043
5044 AddOverriddenMethods(ClassDecl, CopyAssignment);
5045 return CopyAssignment;
5046}
5047
Douglas Gregor06a9f362010-05-01 20:49:11 +00005048void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
5049 CXXMethodDecl *CopyAssignOperator) {
5050 assert((CopyAssignOperator->isImplicit() &&
5051 CopyAssignOperator->isOverloadedOperator() &&
5052 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Douglas Gregorc070cc62010-06-17 23:14:26 +00005053 !CopyAssignOperator->isUsed(false)) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00005054 "DefineImplicitCopyAssignment called for wrong function");
5055
5056 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
5057
5058 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
5059 CopyAssignOperator->setInvalidDecl();
5060 return;
5061 }
5062
5063 CopyAssignOperator->setUsed();
5064
5065 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00005066 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005067
5068 // C++0x [class.copy]p30:
5069 // The implicitly-defined or explicitly-defaulted copy assignment operator
5070 // for a non-union class X performs memberwise copy assignment of its
5071 // subobjects. The direct base classes of X are assigned first, in the
5072 // order of their declaration in the base-specifier-list, and then the
5073 // immediate non-static data members of X are assigned, in the order in
5074 // which they were declared in the class definition.
5075
5076 // The statements that form the synthesized function body.
John McCallca0408f2010-08-23 06:44:23 +00005077 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005078
5079 // The parameter for the "other" object, which we are copying from.
5080 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
5081 Qualifiers OtherQuals = Other->getType().getQualifiers();
5082 QualType OtherRefType = Other->getType();
5083 if (const LValueReferenceType *OtherRef
5084 = OtherRefType->getAs<LValueReferenceType>()) {
5085 OtherRefType = OtherRef->getPointeeType();
5086 OtherQuals = OtherRefType.getQualifiers();
5087 }
5088
5089 // Our location for everything implicitly-generated.
5090 SourceLocation Loc = CopyAssignOperator->getLocation();
5091
5092 // Construct a reference to the "other" object. We'll be using this
5093 // throughout the generated ASTs.
John McCall09431682010-11-18 19:01:18 +00005094 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00005095 assert(OtherRef && "Reference to parameter cannot fail!");
5096
5097 // Construct the "this" pointer. We'll be using this throughout the generated
5098 // ASTs.
5099 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
5100 assert(This && "Reference to this cannot fail!");
5101
5102 // Assign base classes.
5103 bool Invalid = false;
5104 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5105 E = ClassDecl->bases_end(); Base != E; ++Base) {
5106 // Form the assignment:
5107 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
5108 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00005109 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00005110 Invalid = true;
5111 continue;
5112 }
5113
John McCallf871d0c2010-08-07 06:22:56 +00005114 CXXCastPath BasePath;
5115 BasePath.push_back(Base);
5116
Douglas Gregor06a9f362010-05-01 20:49:11 +00005117 // Construct the "from" expression, which is an implicit cast to the
5118 // appropriately-qualified base type.
John McCall3fa5cae2010-10-26 07:05:15 +00005119 Expr *From = OtherRef;
Douglas Gregor06a9f362010-05-01 20:49:11 +00005120 ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
John McCall5baba9d2010-08-25 10:28:54 +00005121 CK_UncheckedDerivedToBase,
5122 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005123
5124 // Dereference "this".
John McCall5baba9d2010-08-25 10:28:54 +00005125 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005126
5127 // Implicitly cast "this" to the appropriately-qualified base type.
5128 Expr *ToE = To.takeAs<Expr>();
5129 ImpCastExprToType(ToE,
5130 Context.getCVRQualifiedType(BaseType,
5131 CopyAssignOperator->getTypeQualifiers()),
John McCall5baba9d2010-08-25 10:28:54 +00005132 CK_UncheckedDerivedToBase,
5133 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005134 To = Owned(ToE);
5135
5136 // Build the copy.
John McCall60d7b3a2010-08-24 06:29:42 +00005137 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00005138 To.get(), From,
5139 /*CopyingBaseSubobject=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005140 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00005141 Diag(CurrentLocation, diag::note_member_synthesized_at)
5142 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5143 CopyAssignOperator->setInvalidDecl();
5144 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00005145 }
5146
5147 // Success! Record the copy.
5148 Statements.push_back(Copy.takeAs<Expr>());
5149 }
5150
5151 // \brief Reference to the __builtin_memcpy function.
5152 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00005153 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00005154 Expr *CollectableMemCpyRef = 0;
Douglas Gregor06a9f362010-05-01 20:49:11 +00005155
5156 // Assign non-static members.
5157 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5158 FieldEnd = ClassDecl->field_end();
5159 Field != FieldEnd; ++Field) {
5160 // Check for members of reference type; we can't copy those.
5161 if (Field->getType()->isReferenceType()) {
5162 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
5163 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
5164 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00005165 Diag(CurrentLocation, diag::note_member_synthesized_at)
5166 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005167 Invalid = true;
5168 continue;
5169 }
5170
5171 // Check for members of const-qualified, non-class type.
5172 QualType BaseType = Context.getBaseElementType(Field->getType());
5173 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
5174 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
5175 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
5176 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00005177 Diag(CurrentLocation, diag::note_member_synthesized_at)
5178 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005179 Invalid = true;
5180 continue;
5181 }
5182
5183 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00005184 if (FieldType->isIncompleteArrayType()) {
5185 assert(ClassDecl->hasFlexibleArrayMember() &&
5186 "Incomplete array type is not valid");
5187 continue;
5188 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00005189
5190 // Build references to the field in the object we're copying from and to.
5191 CXXScopeSpec SS; // Intentionally empty
5192 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
5193 LookupMemberName);
5194 MemberLookup.addDecl(*Field);
5195 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00005196 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall09431682010-11-18 19:01:18 +00005197 Loc, /*IsArrow=*/false,
5198 SS, 0, MemberLookup, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00005199 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall09431682010-11-18 19:01:18 +00005200 Loc, /*IsArrow=*/true,
5201 SS, 0, MemberLookup, 0);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005202 assert(!From.isInvalid() && "Implicit field reference cannot fail");
5203 assert(!To.isInvalid() && "Implicit field reference cannot fail");
5204
5205 // If the field should be copied with __builtin_memcpy rather than via
5206 // explicit assignments, do so. This optimization only applies for arrays
5207 // of scalars and arrays of class type with trivial copy-assignment
5208 // operators.
5209 if (FieldType->isArrayType() &&
5210 (!BaseType->isRecordType() ||
5211 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl())
5212 ->hasTrivialCopyAssignment())) {
5213 // Compute the size of the memory buffer to be copied.
5214 QualType SizeType = Context.getSizeType();
5215 llvm::APInt Size(Context.getTypeSize(SizeType),
5216 Context.getTypeSizeInChars(BaseType).getQuantity());
5217 for (const ConstantArrayType *Array
5218 = Context.getAsConstantArrayType(FieldType);
5219 Array;
5220 Array = Context.getAsConstantArrayType(Array->getElementType())) {
Jay Foad9f71a8f2010-12-07 08:25:34 +00005221 llvm::APInt ArraySize
5222 = Array->getSize().zextOrTrunc(Size.getBitWidth());
Douglas Gregor06a9f362010-05-01 20:49:11 +00005223 Size *= ArraySize;
5224 }
5225
5226 // Take the address of the field references for "from" and "to".
John McCall2de56d12010-08-25 11:45:40 +00005227 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
5228 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00005229
5230 bool NeedsCollectableMemCpy =
5231 (BaseType->isRecordType() &&
5232 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
5233
5234 if (NeedsCollectableMemCpy) {
5235 if (!CollectableMemCpyRef) {
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00005236 // Create a reference to the __builtin_objc_memmove_collectable function.
5237 LookupResult R(*this,
5238 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00005239 Loc, LookupOrdinaryName);
5240 LookupName(R, TUScope, true);
5241
5242 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
5243 if (!CollectableMemCpy) {
5244 // Something went horribly wrong earlier, and we will have
5245 // complained about it.
5246 Invalid = true;
5247 continue;
5248 }
5249
5250 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
5251 CollectableMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00005252 VK_LValue, Loc, 0).take();
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00005253 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
5254 }
5255 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00005256 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00005257 else if (!BuiltinMemCpyRef) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00005258 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
5259 LookupOrdinaryName);
5260 LookupName(R, TUScope, true);
5261
5262 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
5263 if (!BuiltinMemCpy) {
5264 // Something went horribly wrong earlier, and we will have complained
5265 // about it.
5266 Invalid = true;
5267 continue;
5268 }
5269
5270 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
5271 BuiltinMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00005272 VK_LValue, Loc, 0).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00005273 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
5274 }
5275
John McCallca0408f2010-08-23 06:44:23 +00005276 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005277 CallArgs.push_back(To.takeAs<Expr>());
5278 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00005279 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCall60d7b3a2010-08-24 06:29:42 +00005280 ExprResult Call = ExprError();
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005281 if (NeedsCollectableMemCpy)
5282 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00005283 CollectableMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005284 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00005285 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005286 else
5287 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00005288 BuiltinMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005289 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00005290 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005291
Douglas Gregor06a9f362010-05-01 20:49:11 +00005292 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
5293 Statements.push_back(Call.takeAs<Expr>());
5294 continue;
5295 }
5296
5297 // Build the copy of this field.
John McCall60d7b3a2010-08-24 06:29:42 +00005298 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
John McCall9ae2f072010-08-23 23:25:46 +00005299 To.get(), From.get(),
Douglas Gregor6cdc1612010-05-04 15:20:55 +00005300 /*CopyingBaseSubobject=*/false);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005301 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00005302 Diag(CurrentLocation, diag::note_member_synthesized_at)
5303 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5304 CopyAssignOperator->setInvalidDecl();
5305 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00005306 }
5307
5308 // Success! Record the copy.
5309 Statements.push_back(Copy.takeAs<Stmt>());
5310 }
5311
5312 if (!Invalid) {
5313 // Add a "return *this;"
John McCall2de56d12010-08-25 11:45:40 +00005314 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005315
John McCall60d7b3a2010-08-24 06:29:42 +00005316 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00005317 if (Return.isInvalid())
5318 Invalid = true;
5319 else {
5320 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00005321
5322 if (Trap.hasErrorOccurred()) {
5323 Diag(CurrentLocation, diag::note_member_synthesized_at)
5324 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5325 Invalid = true;
5326 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00005327 }
5328 }
5329
5330 if (Invalid) {
5331 CopyAssignOperator->setInvalidDecl();
5332 return;
5333 }
5334
John McCall60d7b3a2010-08-24 06:29:42 +00005335 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
Douglas Gregor06a9f362010-05-01 20:49:11 +00005336 /*isStmtExpr=*/false);
5337 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
5338 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00005339}
5340
Douglas Gregor23c94db2010-07-02 17:43:08 +00005341CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
5342 CXXRecordDecl *ClassDecl) {
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005343 // C++ [class.copy]p4:
5344 // If the class definition does not explicitly declare a copy
5345 // constructor, one is declared implicitly.
5346
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005347 // C++ [class.copy]p5:
5348 // The implicitly-declared copy constructor for a class X will
5349 // have the form
5350 //
5351 // X::X(const X&)
5352 //
5353 // if
5354 bool HasConstCopyConstructor = true;
5355
5356 // -- each direct or virtual base class B of X has a copy
5357 // constructor whose first parameter is of type const B& or
5358 // const volatile B&, and
5359 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5360 BaseEnd = ClassDecl->bases_end();
5361 HasConstCopyConstructor && Base != BaseEnd;
5362 ++Base) {
Douglas Gregor598a8542010-07-01 18:27:03 +00005363 // Virtual bases are handled below.
5364 if (Base->isVirtual())
5365 continue;
5366
Douglas Gregor22584312010-07-02 23:41:54 +00005367 CXXRecordDecl *BaseClassDecl
Douglas Gregor598a8542010-07-01 18:27:03 +00005368 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005369 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5370 DeclareImplicitCopyConstructor(BaseClassDecl);
5371
Douglas Gregor598a8542010-07-01 18:27:03 +00005372 HasConstCopyConstructor
5373 = BaseClassDecl->hasConstCopyConstructor(Context);
5374 }
5375
5376 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
5377 BaseEnd = ClassDecl->vbases_end();
5378 HasConstCopyConstructor && Base != BaseEnd;
5379 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00005380 CXXRecordDecl *BaseClassDecl
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005381 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005382 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5383 DeclareImplicitCopyConstructor(BaseClassDecl);
5384
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005385 HasConstCopyConstructor
5386 = BaseClassDecl->hasConstCopyConstructor(Context);
5387 }
5388
5389 // -- for all the nonstatic data members of X that are of a
5390 // class type M (or array thereof), each such class type
5391 // has a copy constructor whose first parameter is of type
5392 // const M& or const volatile M&.
5393 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5394 FieldEnd = ClassDecl->field_end();
5395 HasConstCopyConstructor && Field != FieldEnd;
5396 ++Field) {
Douglas Gregor598a8542010-07-01 18:27:03 +00005397 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005398 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregor22584312010-07-02 23:41:54 +00005399 CXXRecordDecl *FieldClassDecl
Douglas Gregor598a8542010-07-01 18:27:03 +00005400 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005401 if (!FieldClassDecl->hasDeclaredCopyConstructor())
5402 DeclareImplicitCopyConstructor(FieldClassDecl);
5403
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005404 HasConstCopyConstructor
Douglas Gregor598a8542010-07-01 18:27:03 +00005405 = FieldClassDecl->hasConstCopyConstructor(Context);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005406 }
5407 }
5408
5409 // Otherwise, the implicitly declared copy constructor will have
5410 // the form
5411 //
5412 // X::X(X&)
5413 QualType ClassType = Context.getTypeDeclType(ClassDecl);
5414 QualType ArgType = ClassType;
5415 if (HasConstCopyConstructor)
5416 ArgType = ArgType.withConst();
5417 ArgType = Context.getLValueReferenceType(ArgType);
5418
Douglas Gregor0d405db2010-07-01 20:59:04 +00005419 // C++ [except.spec]p14:
5420 // An implicitly declared special member function (Clause 12) shall have an
5421 // exception-specification. [...]
5422 ImplicitExceptionSpecification ExceptSpec(Context);
5423 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
5424 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5425 BaseEnd = ClassDecl->bases_end();
5426 Base != BaseEnd;
5427 ++Base) {
5428 // Virtual bases are handled below.
5429 if (Base->isVirtual())
5430 continue;
5431
Douglas Gregor22584312010-07-02 23:41:54 +00005432 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00005433 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005434 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5435 DeclareImplicitCopyConstructor(BaseClassDecl);
5436
Douglas Gregor0d405db2010-07-01 20:59:04 +00005437 if (CXXConstructorDecl *CopyConstructor
5438 = BaseClassDecl->getCopyConstructor(Context, Quals))
5439 ExceptSpec.CalledDecl(CopyConstructor);
5440 }
5441 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
5442 BaseEnd = ClassDecl->vbases_end();
5443 Base != BaseEnd;
5444 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00005445 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00005446 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005447 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5448 DeclareImplicitCopyConstructor(BaseClassDecl);
5449
Douglas Gregor0d405db2010-07-01 20:59:04 +00005450 if (CXXConstructorDecl *CopyConstructor
5451 = BaseClassDecl->getCopyConstructor(Context, Quals))
5452 ExceptSpec.CalledDecl(CopyConstructor);
5453 }
5454 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5455 FieldEnd = ClassDecl->field_end();
5456 Field != FieldEnd;
5457 ++Field) {
5458 QualType FieldType = Context.getBaseElementType((*Field)->getType());
5459 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregor22584312010-07-02 23:41:54 +00005460 CXXRecordDecl *FieldClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00005461 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005462 if (!FieldClassDecl->hasDeclaredCopyConstructor())
5463 DeclareImplicitCopyConstructor(FieldClassDecl);
5464
Douglas Gregor0d405db2010-07-01 20:59:04 +00005465 if (CXXConstructorDecl *CopyConstructor
5466 = FieldClassDecl->getCopyConstructor(Context, Quals))
5467 ExceptSpec.CalledDecl(CopyConstructor);
5468 }
5469 }
5470
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005471 // An implicitly-declared copy constructor is an inline public
5472 // member of its class.
John McCalle23cf432010-12-14 08:05:40 +00005473 FunctionProtoType::ExtProtoInfo EPI;
5474 EPI.HasExceptionSpec = ExceptSpec.hasExceptionSpecification();
5475 EPI.HasAnyExceptionSpec = ExceptSpec.hasAnyExceptionSpecification();
5476 EPI.NumExceptions = ExceptSpec.size();
5477 EPI.Exceptions = ExceptSpec.data();
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005478 DeclarationName Name
5479 = Context.DeclarationNames.getCXXConstructorName(
5480 Context.getCanonicalType(ClassType));
Abramo Bagnara25777432010-08-11 22:01:17 +00005481 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005482 CXXConstructorDecl *CopyConstructor
Abramo Bagnara25777432010-08-11 22:01:17 +00005483 = CXXConstructorDecl::Create(Context, ClassDecl, NameInfo,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005484 Context.getFunctionType(Context.VoidTy,
John McCalle23cf432010-12-14 08:05:40 +00005485 &ArgType, 1, EPI),
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005486 /*TInfo=*/0,
5487 /*isExplicit=*/false,
5488 /*isInline=*/true,
5489 /*isImplicitlyDeclared=*/true);
5490 CopyConstructor->setAccess(AS_public);
5491 CopyConstructor->setImplicit();
5492 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
5493
Douglas Gregor22584312010-07-02 23:41:54 +00005494 // Note that we have declared this constructor.
Douglas Gregor22584312010-07-02 23:41:54 +00005495 ++ASTContext::NumImplicitCopyConstructorsDeclared;
5496
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005497 // Add the parameter to the constructor.
5498 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
5499 ClassDecl->getLocation(),
5500 /*IdentifierInfo=*/0,
5501 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00005502 SC_None,
5503 SC_None, 0);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005504 CopyConstructor->setParams(&FromParam, 1);
Douglas Gregor23c94db2010-07-02 17:43:08 +00005505 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor22584312010-07-02 23:41:54 +00005506 PushOnScopeChains(CopyConstructor, S, false);
5507 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005508
5509 return CopyConstructor;
5510}
5511
Fariborz Jahanian485f0872009-06-22 23:34:40 +00005512void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
5513 CXXConstructorDecl *CopyConstructor,
5514 unsigned TypeQuals) {
Mike Stump1eb44332009-09-09 15:08:12 +00005515 assert((CopyConstructor->isImplicit() &&
Douglas Gregor9e9199d2009-12-22 00:34:07 +00005516 CopyConstructor->isCopyConstructor(TypeQuals) &&
Douglas Gregorc070cc62010-06-17 23:14:26 +00005517 !CopyConstructor->isUsed(false)) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00005518 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00005519
Anders Carlsson63010a72010-04-23 16:24:12 +00005520 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00005521 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005522
Douglas Gregor39957dc2010-05-01 15:04:51 +00005523 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00005524 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005525
Sean Huntcbb67482011-01-08 20:30:50 +00005526 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00005527 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00005528 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00005529 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00005530 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00005531 } else {
5532 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
5533 CopyConstructor->getLocation(),
5534 MultiStmtArg(*this, 0, 0),
5535 /*isStmtExpr=*/false)
5536 .takeAs<Stmt>());
Anders Carlsson8e142cc2010-04-25 00:52:09 +00005537 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00005538
5539 CopyConstructor->setUsed();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00005540}
5541
John McCall60d7b3a2010-08-24 06:29:42 +00005542ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00005543Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00005544 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00005545 MultiExprArg ExprArgs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005546 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00005547 unsigned ConstructKind,
5548 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00005549 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00005550
Douglas Gregor2f599792010-04-02 18:24:57 +00005551 // C++0x [class.copy]p34:
5552 // When certain criteria are met, an implementation is allowed to
5553 // omit the copy/move construction of a class object, even if the
5554 // copy/move constructor and/or destructor for the object have
5555 // side effects. [...]
5556 // - when a temporary class object that has not been bound to a
5557 // reference (12.2) would be copied/moved to a class object
5558 // with the same cv-unqualified type, the copy/move operation
5559 // can be omitted by constructing the temporary object
5560 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +00005561 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregor70a21de2011-01-27 23:24:55 +00005562 Constructor->isCopyOrMoveConstructor() && ExprArgs.size() >= 1) {
Douglas Gregor2f599792010-04-02 18:24:57 +00005563 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
John McCall558d2ab2010-09-15 10:14:12 +00005564 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00005565 }
Mike Stump1eb44332009-09-09 15:08:12 +00005566
5567 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005568 Elidable, move(ExprArgs), RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00005569 ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00005570}
5571
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00005572/// BuildCXXConstructExpr - Creates a complete call to a constructor,
5573/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00005574ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00005575Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
5576 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00005577 MultiExprArg ExprArgs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005578 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00005579 unsigned ConstructKind,
5580 SourceRange ParenRange) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00005581 unsigned NumExprs = ExprArgs.size();
5582 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00005583
Douglas Gregor7edfb692009-11-23 12:27:39 +00005584 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00005585 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor16006c92009-12-16 18:50:27 +00005586 Constructor, Elidable, Exprs, NumExprs,
John McCall7a1fad32010-08-24 07:32:53 +00005587 RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00005588 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
5589 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00005590}
5591
Mike Stump1eb44332009-09-09 15:08:12 +00005592bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00005593 CXXConstructorDecl *Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00005594 MultiExprArg Exprs) {
Chandler Carruth428edaf2010-10-25 08:47:36 +00005595 // FIXME: Provide the correct paren SourceRange when available.
John McCall60d7b3a2010-08-24 06:29:42 +00005596 ExprResult TempResult =
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00005597 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Chandler Carruth428edaf2010-10-25 08:47:36 +00005598 move(Exprs), false, CXXConstructExpr::CK_Complete,
5599 SourceRange());
Anders Carlssonfe2de492009-08-25 05:18:00 +00005600 if (TempResult.isInvalid())
5601 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00005602
Anders Carlssonda3f4e22009-08-25 05:12:04 +00005603 Expr *Temp = TempResult.takeAs<Expr>();
John McCallb4eb64d2010-10-08 02:01:28 +00005604 CheckImplicitConversions(Temp, VD->getLocation());
Douglas Gregord7f37bf2009-06-22 23:06:13 +00005605 MarkDeclarationReferenced(VD->getLocation(), Constructor);
John McCall4765fa02010-12-06 08:20:24 +00005606 Temp = MaybeCreateExprWithCleanups(Temp);
Douglas Gregor838db382010-02-11 01:19:42 +00005607 VD->setInit(Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00005608
Anders Carlssonfe2de492009-08-25 05:18:00 +00005609 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00005610}
5611
John McCall68c6c9a2010-02-02 09:10:11 +00005612void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
5613 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Douglas Gregor333de062010-02-25 18:11:54 +00005614 if (!ClassDecl->isInvalidDecl() && !VD->isInvalidDecl() &&
Douglas Gregorfb2db462010-05-22 17:12:29 +00005615 !ClassDecl->hasTrivialDestructor() && !ClassDecl->isDependentContext()) {
Douglas Gregordb89f282010-07-01 22:47:18 +00005616 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
John McCall4f9506a2010-02-02 08:45:54 +00005617 MarkDeclarationReferenced(VD->getLocation(), Destructor);
John McCall58e6f342010-03-16 05:22:47 +00005618 CheckDestructorAccess(VD->getLocation(), Destructor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00005619 PDiag(diag::err_access_dtor_var)
John McCall58e6f342010-03-16 05:22:47 +00005620 << VD->getDeclName()
5621 << VD->getType());
John McCall626e96e2010-08-01 20:20:59 +00005622
John McCallae792222010-09-18 05:25:11 +00005623 // TODO: this should be re-enabled for static locals by !CXAAtExit
5624 if (!VD->isInvalidDecl() && VD->hasGlobalStorage() && !VD->isStaticLocal())
John McCall626e96e2010-08-01 20:20:59 +00005625 Diag(VD->getLocation(), diag::warn_global_destructor);
John McCall4f9506a2010-02-02 08:45:54 +00005626 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00005627}
5628
Mike Stump1eb44332009-09-09 15:08:12 +00005629/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005630/// ActOnDeclarator, when a C++ direct initializer is present.
5631/// e.g: "int x(1);"
John McCalld226f652010-08-21 09:40:31 +00005632void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005633 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +00005634 MultiExprArg Exprs,
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005635 SourceLocation RParenLoc) {
Daniel Dunbar51846262009-12-24 19:19:26 +00005636 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005637
5638 // If there is no declaration, there was an error parsing it. Just ignore
5639 // the initializer.
Chris Lattnerb28317a2009-03-28 19:18:32 +00005640 if (RealDecl == 0)
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005641 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005642
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005643 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
5644 if (!VDecl) {
5645 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
5646 RealDecl->setInvalidDecl();
5647 return;
5648 }
5649
Douglas Gregor83ddad32009-08-26 21:14:46 +00005650 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00005651 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005652 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
5653 //
5654 // Clients that want to distinguish between the two forms, can check for
5655 // direct initializer using VarDecl::hasCXXDirectInitializer().
5656 // A major benefit is that clients that don't particularly care about which
5657 // exactly form was it (like the CodeGen) can handle both cases without
5658 // special case code.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00005659
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005660 // C++ 8.5p11:
5661 // The form of initialization (using parentheses or '=') is generally
5662 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00005663 // class type.
5664
Douglas Gregor4dffad62010-02-11 22:55:30 +00005665 if (!VDecl->getType()->isDependentType() &&
5666 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor615c5d42009-03-24 16:43:20 +00005667 diag::err_typecheck_decl_incomplete_type)) {
5668 VDecl->setInvalidDecl();
5669 return;
5670 }
5671
Douglas Gregor90f93822009-12-22 22:17:25 +00005672 // The variable can not have an abstract class type.
5673 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
5674 diag::err_abstract_type_in_decl,
5675 AbstractVariableType))
5676 VDecl->setInvalidDecl();
5677
Sebastian Redl31310a22010-02-01 20:16:42 +00005678 const VarDecl *Def;
5679 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregor90f93822009-12-22 22:17:25 +00005680 Diag(VDecl->getLocation(), diag::err_redefinition)
5681 << VDecl->getDeclName();
5682 Diag(Def->getLocation(), diag::note_previous_definition);
5683 VDecl->setInvalidDecl();
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00005684 return;
5685 }
Douglas Gregor4dffad62010-02-11 22:55:30 +00005686
Douglas Gregor3a91abf2010-08-24 05:27:49 +00005687 // C++ [class.static.data]p4
5688 // If a static data member is of const integral or const
5689 // enumeration type, its declaration in the class definition can
5690 // specify a constant-initializer which shall be an integral
5691 // constant expression (5.19). In that case, the member can appear
5692 // in integral constant expressions. The member shall still be
5693 // defined in a namespace scope if it is used in the program and the
5694 // namespace scope definition shall not contain an initializer.
5695 //
5696 // We already performed a redefinition check above, but for static
5697 // data members we also need to check whether there was an in-class
5698 // declaration with an initializer.
5699 const VarDecl* PrevInit = 0;
5700 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
5701 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
5702 Diag(PrevInit->getLocation(), diag::note_previous_definition);
5703 return;
5704 }
5705
Douglas Gregora31040f2010-12-16 01:31:22 +00005706 bool IsDependent = false;
5707 for (unsigned I = 0, N = Exprs.size(); I != N; ++I) {
5708 if (DiagnoseUnexpandedParameterPack(Exprs.get()[I], UPPC_Expression)) {
5709 VDecl->setInvalidDecl();
5710 return;
5711 }
5712
5713 if (Exprs.get()[I]->isTypeDependent())
5714 IsDependent = true;
5715 }
5716
Douglas Gregor4dffad62010-02-11 22:55:30 +00005717 // If either the declaration has a dependent type or if any of the
5718 // expressions is type-dependent, we represent the initialization
5719 // via a ParenListExpr for later use during template instantiation.
Douglas Gregora31040f2010-12-16 01:31:22 +00005720 if (VDecl->getType()->isDependentType() || IsDependent) {
Douglas Gregor4dffad62010-02-11 22:55:30 +00005721 // Let clients know that initialization was done with a direct initializer.
5722 VDecl->setCXXDirectInitializer(true);
5723
5724 // Store the initialization expressions as a ParenListExpr.
5725 unsigned NumExprs = Exprs.size();
5726 VDecl->setInit(new (Context) ParenListExpr(Context, LParenLoc,
5727 (Expr **)Exprs.release(),
5728 NumExprs, RParenLoc));
5729 return;
5730 }
Douglas Gregor90f93822009-12-22 22:17:25 +00005731
5732 // Capture the variable that is being initialized and the style of
5733 // initialization.
5734 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
5735
5736 // FIXME: Poor source location information.
5737 InitializationKind Kind
5738 = InitializationKind::CreateDirect(VDecl->getLocation(),
5739 LParenLoc, RParenLoc);
5740
5741 InitializationSequence InitSeq(*this, Entity, Kind,
John McCall9ae2f072010-08-23 23:25:46 +00005742 Exprs.get(), Exprs.size());
John McCall60d7b3a2010-08-24 06:29:42 +00005743 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
Douglas Gregor90f93822009-12-22 22:17:25 +00005744 if (Result.isInvalid()) {
5745 VDecl->setInvalidDecl();
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005746 return;
5747 }
John McCallb4eb64d2010-10-08 02:01:28 +00005748
5749 CheckImplicitConversions(Result.get(), LParenLoc);
Douglas Gregor90f93822009-12-22 22:17:25 +00005750
Douglas Gregor53c374f2010-12-07 00:41:46 +00005751 Result = MaybeCreateExprWithCleanups(Result);
Douglas Gregor838db382010-02-11 01:19:42 +00005752 VDecl->setInit(Result.takeAs<Expr>());
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005753 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00005754
John McCall2998d6b2011-01-19 11:48:09 +00005755 CheckCompleteVariableDeclaration(VDecl);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005756}
Douglas Gregor27c8dc02008-10-29 00:13:59 +00005757
Douglas Gregor39da0b82009-09-09 23:08:42 +00005758/// \brief Given a constructor and the set of arguments provided for the
5759/// constructor, convert the arguments and add any required default arguments
5760/// to form a proper call to this constructor.
5761///
5762/// \returns true if an error occurred, false otherwise.
5763bool
5764Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
5765 MultiExprArg ArgsPtr,
5766 SourceLocation Loc,
John McCallca0408f2010-08-23 06:44:23 +00005767 ASTOwningVector<Expr*> &ConvertedArgs) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00005768 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
5769 unsigned NumArgs = ArgsPtr.size();
5770 Expr **Args = (Expr **)ArgsPtr.get();
5771
5772 const FunctionProtoType *Proto
5773 = Constructor->getType()->getAs<FunctionProtoType>();
5774 assert(Proto && "Constructor without a prototype?");
5775 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00005776
5777 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00005778 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00005779 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00005780 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00005781 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00005782
5783 VariadicCallType CallType =
5784 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
5785 llvm::SmallVector<Expr *, 8> AllArgs;
5786 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
5787 Proto, 0, Args, NumArgs, AllArgs,
5788 CallType);
5789 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
5790 ConvertedArgs.push_back(AllArgs[i]);
5791 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00005792}
5793
Anders Carlsson20d45d22009-12-12 00:32:00 +00005794static inline bool
5795CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
5796 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00005797 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +00005798 if (isa<NamespaceDecl>(DC)) {
5799 return SemaRef.Diag(FnDecl->getLocation(),
5800 diag::err_operator_new_delete_declared_in_namespace)
5801 << FnDecl->getDeclName();
5802 }
5803
5804 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +00005805 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00005806 return SemaRef.Diag(FnDecl->getLocation(),
5807 diag::err_operator_new_delete_declared_static)
5808 << FnDecl->getDeclName();
5809 }
5810
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00005811 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00005812}
5813
Anders Carlsson156c78e2009-12-13 17:53:43 +00005814static inline bool
5815CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
5816 CanQualType ExpectedResultType,
5817 CanQualType ExpectedFirstParamType,
5818 unsigned DependentParamTypeDiag,
5819 unsigned InvalidParamTypeDiag) {
5820 QualType ResultType =
5821 FnDecl->getType()->getAs<FunctionType>()->getResultType();
5822
5823 // Check that the result type is not dependent.
5824 if (ResultType->isDependentType())
5825 return SemaRef.Diag(FnDecl->getLocation(),
5826 diag::err_operator_new_delete_dependent_result_type)
5827 << FnDecl->getDeclName() << ExpectedResultType;
5828
5829 // Check that the result type is what we expect.
5830 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
5831 return SemaRef.Diag(FnDecl->getLocation(),
5832 diag::err_operator_new_delete_invalid_result_type)
5833 << FnDecl->getDeclName() << ExpectedResultType;
5834
5835 // A function template must have at least 2 parameters.
5836 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
5837 return SemaRef.Diag(FnDecl->getLocation(),
5838 diag::err_operator_new_delete_template_too_few_parameters)
5839 << FnDecl->getDeclName();
5840
5841 // The function decl must have at least 1 parameter.
5842 if (FnDecl->getNumParams() == 0)
5843 return SemaRef.Diag(FnDecl->getLocation(),
5844 diag::err_operator_new_delete_too_few_parameters)
5845 << FnDecl->getDeclName();
5846
5847 // Check the the first parameter type is not dependent.
5848 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
5849 if (FirstParamType->isDependentType())
5850 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
5851 << FnDecl->getDeclName() << ExpectedFirstParamType;
5852
5853 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +00005854 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +00005855 ExpectedFirstParamType)
5856 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
5857 << FnDecl->getDeclName() << ExpectedFirstParamType;
5858
5859 return false;
5860}
5861
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00005862static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +00005863CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00005864 // C++ [basic.stc.dynamic.allocation]p1:
5865 // A program is ill-formed if an allocation function is declared in a
5866 // namespace scope other than global scope or declared static in global
5867 // scope.
5868 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
5869 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +00005870
5871 CanQualType SizeTy =
5872 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
5873
5874 // C++ [basic.stc.dynamic.allocation]p1:
5875 // The return type shall be void*. The first parameter shall have type
5876 // std::size_t.
5877 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
5878 SizeTy,
5879 diag::err_operator_new_dependent_param_type,
5880 diag::err_operator_new_param_type))
5881 return true;
5882
5883 // C++ [basic.stc.dynamic.allocation]p1:
5884 // The first parameter shall not have an associated default argument.
5885 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +00005886 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +00005887 diag::err_operator_new_default_arg)
5888 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
5889
5890 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +00005891}
5892
5893static bool
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00005894CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
5895 // C++ [basic.stc.dynamic.deallocation]p1:
5896 // A program is ill-formed if deallocation functions are declared in a
5897 // namespace scope other than global scope or declared static in global
5898 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +00005899 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
5900 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00005901
5902 // C++ [basic.stc.dynamic.deallocation]p2:
5903 // Each deallocation function shall return void and its first parameter
5904 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +00005905 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
5906 SemaRef.Context.VoidPtrTy,
5907 diag::err_operator_delete_dependent_param_type,
5908 diag::err_operator_delete_param_type))
5909 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00005910
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00005911 return false;
5912}
5913
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005914/// CheckOverloadedOperatorDeclaration - Check whether the declaration
5915/// of this overloaded operator is well-formed. If so, returns false;
5916/// otherwise, emits appropriate diagnostics and returns true.
5917bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005918 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005919 "Expected an overloaded operator declaration");
5920
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005921 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
5922
Mike Stump1eb44332009-09-09 15:08:12 +00005923 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005924 // The allocation and deallocation functions, operator new,
5925 // operator new[], operator delete and operator delete[], are
5926 // described completely in 3.7.3. The attributes and restrictions
5927 // found in the rest of this subclause do not apply to them unless
5928 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +00005929 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00005930 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00005931
Anders Carlssona3ccda52009-12-12 00:26:23 +00005932 if (Op == OO_New || Op == OO_Array_New)
5933 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005934
5935 // C++ [over.oper]p6:
5936 // An operator function shall either be a non-static member
5937 // function or be a non-member function and have at least one
5938 // parameter whose type is a class, a reference to a class, an
5939 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005940 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
5941 if (MethodDecl->isStatic())
5942 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005943 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005944 } else {
5945 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005946 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
5947 ParamEnd = FnDecl->param_end();
5948 Param != ParamEnd; ++Param) {
5949 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00005950 if (ParamType->isDependentType() || ParamType->isRecordType() ||
5951 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005952 ClassOrEnumParam = true;
5953 break;
5954 }
5955 }
5956
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005957 if (!ClassOrEnumParam)
5958 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00005959 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005960 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005961 }
5962
5963 // C++ [over.oper]p8:
5964 // An operator function cannot have default arguments (8.3.6),
5965 // except where explicitly stated below.
5966 //
Mike Stump1eb44332009-09-09 15:08:12 +00005967 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005968 // (C++ [over.call]p1).
5969 if (Op != OO_Call) {
5970 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
5971 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +00005972 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00005973 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00005974 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +00005975 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005976 }
5977 }
5978
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00005979 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
5980 { false, false, false }
5981#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
5982 , { Unary, Binary, MemberOnly }
5983#include "clang/Basic/OperatorKinds.def"
5984 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005985
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00005986 bool CanBeUnaryOperator = OperatorUses[Op][0];
5987 bool CanBeBinaryOperator = OperatorUses[Op][1];
5988 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005989
5990 // C++ [over.oper]p8:
5991 // [...] Operator functions cannot have more or fewer parameters
5992 // than the number required for the corresponding operator, as
5993 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00005994 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005995 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005996 if (Op != OO_Call &&
5997 ((NumParams == 1 && !CanBeUnaryOperator) ||
5998 (NumParams == 2 && !CanBeBinaryOperator) ||
5999 (NumParams < 1) || (NumParams > 2))) {
6000 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00006001 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00006002 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00006003 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00006004 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00006005 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00006006 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00006007 assert(CanBeBinaryOperator &&
6008 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00006009 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00006010 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006011
Chris Lattner416e46f2008-11-21 07:57:12 +00006012 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00006013 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006014 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00006015
Douglas Gregor43c7bad2008-11-17 16:14:12 +00006016 // Overloaded operators other than operator() cannot be variadic.
6017 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00006018 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00006019 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00006020 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006021 }
6022
6023 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00006024 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
6025 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00006026 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00006027 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006028 }
6029
6030 // C++ [over.inc]p1:
6031 // The user-defined function called operator++ implements the
6032 // prefix and postfix ++ operator. If this function is a member
6033 // function with no parameters, or a non-member function with one
6034 // parameter of class or enumeration type, it defines the prefix
6035 // increment operator ++ for objects of that type. If the function
6036 // is a member function with one parameter (which shall be of type
6037 // int) or a non-member function with two parameters (the second
6038 // of which shall be of type int), it defines the postfix
6039 // increment operator ++ for objects of that type.
6040 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
6041 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
6042 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00006043 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006044 ParamIsInt = BT->getKind() == BuiltinType::Int;
6045
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00006046 if (!ParamIsInt)
6047 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00006048 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00006049 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006050 }
6051
Douglas Gregor43c7bad2008-11-17 16:14:12 +00006052 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006053}
Chris Lattner5a003a42008-12-17 07:09:26 +00006054
Sean Hunta6c058d2010-01-13 09:01:02 +00006055/// CheckLiteralOperatorDeclaration - Check whether the declaration
6056/// of this literal operator function is well-formed. If so, returns
6057/// false; otherwise, emits appropriate diagnostics and returns true.
6058bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
6059 DeclContext *DC = FnDecl->getDeclContext();
6060 Decl::Kind Kind = DC->getDeclKind();
6061 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
6062 Kind != Decl::LinkageSpec) {
6063 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
6064 << FnDecl->getDeclName();
6065 return true;
6066 }
6067
6068 bool Valid = false;
6069
Sean Hunt216c2782010-04-07 23:11:06 +00006070 // template <char...> type operator "" name() is the only valid template
6071 // signature, and the only valid signature with no parameters.
6072 if (FnDecl->param_size() == 0) {
6073 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
6074 // Must have only one template parameter
6075 TemplateParameterList *Params = TpDecl->getTemplateParameters();
6076 if (Params->size() == 1) {
6077 NonTypeTemplateParmDecl *PmDecl =
6078 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +00006079
Sean Hunt216c2782010-04-07 23:11:06 +00006080 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +00006081 if (PmDecl && PmDecl->isTemplateParameterPack() &&
6082 Context.hasSameType(PmDecl->getType(), Context.CharTy))
6083 Valid = true;
6084 }
6085 }
6086 } else {
Sean Hunta6c058d2010-01-13 09:01:02 +00006087 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +00006088 FunctionDecl::param_iterator Param = FnDecl->param_begin();
6089
Sean Hunta6c058d2010-01-13 09:01:02 +00006090 QualType T = (*Param)->getType();
6091
Sean Hunt30019c02010-04-07 22:57:35 +00006092 // unsigned long long int, long double, and any character type are allowed
6093 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +00006094 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
6095 Context.hasSameType(T, Context.LongDoubleTy) ||
6096 Context.hasSameType(T, Context.CharTy) ||
6097 Context.hasSameType(T, Context.WCharTy) ||
6098 Context.hasSameType(T, Context.Char16Ty) ||
6099 Context.hasSameType(T, Context.Char32Ty)) {
6100 if (++Param == FnDecl->param_end())
6101 Valid = true;
6102 goto FinishedParams;
6103 }
6104
Sean Hunt30019c02010-04-07 22:57:35 +00006105 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +00006106 const PointerType *PT = T->getAs<PointerType>();
6107 if (!PT)
6108 goto FinishedParams;
6109 T = PT->getPointeeType();
6110 if (!T.isConstQualified())
6111 goto FinishedParams;
6112 T = T.getUnqualifiedType();
6113
6114 // Move on to the second parameter;
6115 ++Param;
6116
6117 // If there is no second parameter, the first must be a const char *
6118 if (Param == FnDecl->param_end()) {
6119 if (Context.hasSameType(T, Context.CharTy))
6120 Valid = true;
6121 goto FinishedParams;
6122 }
6123
6124 // const char *, const wchar_t*, const char16_t*, and const char32_t*
6125 // are allowed as the first parameter to a two-parameter function
6126 if (!(Context.hasSameType(T, Context.CharTy) ||
6127 Context.hasSameType(T, Context.WCharTy) ||
6128 Context.hasSameType(T, Context.Char16Ty) ||
6129 Context.hasSameType(T, Context.Char32Ty)))
6130 goto FinishedParams;
6131
6132 // The second and final parameter must be an std::size_t
6133 T = (*Param)->getType().getUnqualifiedType();
6134 if (Context.hasSameType(T, Context.getSizeType()) &&
6135 ++Param == FnDecl->param_end())
6136 Valid = true;
6137 }
6138
6139 // FIXME: This diagnostic is absolutely terrible.
6140FinishedParams:
6141 if (!Valid) {
6142 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
6143 << FnDecl->getDeclName();
6144 return true;
6145 }
6146
6147 return false;
6148}
6149
Douglas Gregor074149e2009-01-05 19:45:36 +00006150/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
6151/// linkage specification, including the language and (if present)
6152/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
6153/// the location of the language string literal, which is provided
6154/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
6155/// the '{' brace. Otherwise, this linkage specification does not
6156/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +00006157Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
6158 SourceLocation LangLoc,
6159 llvm::StringRef Lang,
6160 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00006161 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +00006162 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00006163 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +00006164 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00006165 Language = LinkageSpecDecl::lang_cxx;
6166 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00006167 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +00006168 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +00006169 }
Mike Stump1eb44332009-09-09 15:08:12 +00006170
Chris Lattnercc98eac2008-12-17 07:13:27 +00006171 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +00006172
Douglas Gregor074149e2009-01-05 19:45:36 +00006173 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Mike Stump1eb44332009-09-09 15:08:12 +00006174 LangLoc, Language,
Douglas Gregor074149e2009-01-05 19:45:36 +00006175 LBraceLoc.isValid());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006176 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00006177 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +00006178 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +00006179}
6180
Abramo Bagnara35f9a192010-07-30 16:47:02 +00006181/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +00006182/// the C++ linkage specification LinkageSpec. If RBraceLoc is
6183/// valid, it's the position of the closing '}' brace in a linkage
6184/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +00006185Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
6186 Decl *LinkageSpec,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006187 SourceLocation RBraceLoc) {
Douglas Gregor074149e2009-01-05 19:45:36 +00006188 if (LinkageSpec)
6189 PopDeclContext();
6190 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00006191}
6192
Douglas Gregord308e622009-05-18 20:51:54 +00006193/// \brief Perform semantic analysis for the variable declaration that
6194/// occurs within a C++ catch clause, returning the newly-created
6195/// variable.
Douglas Gregor83cb9422010-09-09 17:09:21 +00006196VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +00006197 TypeSourceInfo *TInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00006198 IdentifierInfo *Name,
Douglas Gregor83cb9422010-09-09 17:09:21 +00006199 SourceLocation Loc) {
Douglas Gregord308e622009-05-18 20:51:54 +00006200 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +00006201 QualType ExDeclType = TInfo->getType();
6202
Sebastian Redl4b07b292008-12-22 19:15:10 +00006203 // Arrays and functions decay.
6204 if (ExDeclType->isArrayType())
6205 ExDeclType = Context.getArrayDecayedType(ExDeclType);
6206 else if (ExDeclType->isFunctionType())
6207 ExDeclType = Context.getPointerType(ExDeclType);
6208
6209 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
6210 // The exception-declaration shall not denote a pointer or reference to an
6211 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00006212 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +00006213 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +00006214 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +00006215 Invalid = true;
6216 }
Douglas Gregord308e622009-05-18 20:51:54 +00006217
Douglas Gregora2762912010-03-08 01:47:36 +00006218 // GCC allows catching pointers and references to incomplete types
6219 // as an extension; so do we, but we warn by default.
6220
Sebastian Redl4b07b292008-12-22 19:15:10 +00006221 QualType BaseType = ExDeclType;
6222 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00006223 unsigned DK = diag::err_catch_incomplete;
Douglas Gregora2762912010-03-08 01:47:36 +00006224 bool IncompleteCatchIsInvalid = true;
Ted Kremenek6217b802009-07-29 21:53:49 +00006225 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00006226 BaseType = Ptr->getPointeeType();
6227 Mode = 1;
Douglas Gregora2762912010-03-08 01:47:36 +00006228 DK = diag::ext_catch_incomplete_ptr;
6229 IncompleteCatchIsInvalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +00006230 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00006231 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00006232 BaseType = Ref->getPointeeType();
6233 Mode = 2;
Douglas Gregora2762912010-03-08 01:47:36 +00006234 DK = diag::ext_catch_incomplete_ref;
6235 IncompleteCatchIsInvalid = false;
Sebastian Redl4b07b292008-12-22 19:15:10 +00006236 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00006237 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregora2762912010-03-08 01:47:36 +00006238 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
6239 IncompleteCatchIsInvalid)
Sebastian Redl4b07b292008-12-22 19:15:10 +00006240 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00006241
Mike Stump1eb44332009-09-09 15:08:12 +00006242 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +00006243 RequireNonAbstractType(Loc, ExDeclType,
6244 diag::err_abstract_type_in_decl,
6245 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00006246 Invalid = true;
6247
John McCall5a180392010-07-24 00:37:23 +00006248 // Only the non-fragile NeXT runtime currently supports C++ catches
6249 // of ObjC types, and no runtime supports catching ObjC types by value.
6250 if (!Invalid && getLangOptions().ObjC1) {
6251 QualType T = ExDeclType;
6252 if (const ReferenceType *RT = T->getAs<ReferenceType>())
6253 T = RT->getPointeeType();
6254
6255 if (T->isObjCObjectType()) {
6256 Diag(Loc, diag::err_objc_object_catch);
6257 Invalid = true;
6258 } else if (T->isObjCObjectPointerType()) {
6259 if (!getLangOptions().NeXTRuntime) {
6260 Diag(Loc, diag::err_objc_pointer_cxx_catch_gnu);
6261 Invalid = true;
6262 } else if (!getLangOptions().ObjCNonFragileABI) {
6263 Diag(Loc, diag::err_objc_pointer_cxx_catch_fragile);
6264 Invalid = true;
6265 }
6266 }
6267 }
6268
Mike Stump1eb44332009-09-09 15:08:12 +00006269 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
John McCalld931b082010-08-26 03:08:43 +00006270 Name, ExDeclType, TInfo, SC_None,
6271 SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +00006272 ExDecl->setExceptionVariable(true);
6273
Douglas Gregor6d182892010-03-05 23:38:39 +00006274 if (!Invalid) {
6275 if (const RecordType *RecordTy = ExDeclType->getAs<RecordType>()) {
6276 // C++ [except.handle]p16:
6277 // The object declared in an exception-declaration or, if the
6278 // exception-declaration does not specify a name, a temporary (12.2) is
6279 // copy-initialized (8.5) from the exception object. [...]
6280 // The object is destroyed when the handler exits, after the destruction
6281 // of any automatic objects initialized within the handler.
6282 //
6283 // We just pretend to initialize the object with itself, then make sure
6284 // it can be destroyed later.
6285 InitializedEntity Entity = InitializedEntity::InitializeVariable(ExDecl);
6286 Expr *ExDeclRef = DeclRefExpr::Create(Context, 0, SourceRange(), ExDecl,
John McCallf89e55a2010-11-18 06:31:45 +00006287 Loc, ExDeclType, VK_LValue, 0);
Douglas Gregor6d182892010-03-05 23:38:39 +00006288 InitializationKind Kind = InitializationKind::CreateCopy(Loc,
6289 SourceLocation());
6290 InitializationSequence InitSeq(*this, Entity, Kind, &ExDeclRef, 1);
John McCall60d7b3a2010-08-24 06:29:42 +00006291 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCallca0408f2010-08-23 06:44:23 +00006292 MultiExprArg(*this, &ExDeclRef, 1));
Douglas Gregor6d182892010-03-05 23:38:39 +00006293 if (Result.isInvalid())
6294 Invalid = true;
6295 else
6296 FinalizeVarWithDestructor(ExDecl, RecordTy);
6297 }
6298 }
6299
Douglas Gregord308e622009-05-18 20:51:54 +00006300 if (Invalid)
6301 ExDecl->setInvalidDecl();
6302
6303 return ExDecl;
6304}
6305
6306/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
6307/// handler.
John McCalld226f652010-08-21 09:40:31 +00006308Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +00006309 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +00006310 bool Invalid = D.isInvalidType();
6311
6312 // Check for unexpanded parameter packs.
6313 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
6314 UPPC_ExceptionType)) {
6315 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
6316 D.getIdentifierLoc());
6317 Invalid = true;
6318 }
6319
Sebastian Redl4b07b292008-12-22 19:15:10 +00006320 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +00006321 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +00006322 LookupOrdinaryName,
6323 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00006324 // The scope should be freshly made just for us. There is just no way
6325 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +00006326 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +00006327 if (PrevDecl->isTemplateParameter()) {
6328 // Maybe we will complain about the shadowed template parameter.
6329 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00006330 }
6331 }
6332
Chris Lattnereaaebc72009-04-25 08:06:05 +00006333 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00006334 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
6335 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00006336 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00006337 }
6338
Douglas Gregor83cb9422010-09-09 17:09:21 +00006339 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00006340 D.getIdentifier(),
Douglas Gregor83cb9422010-09-09 17:09:21 +00006341 D.getIdentifierLoc());
Douglas Gregord308e622009-05-18 20:51:54 +00006342
Chris Lattnereaaebc72009-04-25 08:06:05 +00006343 if (Invalid)
6344 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00006345
Sebastian Redl4b07b292008-12-22 19:15:10 +00006346 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00006347 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00006348 PushOnScopeChains(ExDecl, S);
6349 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006350 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00006351
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00006352 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +00006353 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +00006354}
Anders Carlssonfb311762009-03-14 00:25:26 +00006355
John McCalld226f652010-08-21 09:40:31 +00006356Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +00006357 Expr *AssertExpr,
6358 Expr *AssertMessageExpr_) {
6359 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
Anders Carlssonfb311762009-03-14 00:25:26 +00006360
Anders Carlssonc3082412009-03-14 00:33:21 +00006361 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
6362 llvm::APSInt Value(32);
6363 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
6364 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
6365 AssertExpr->getSourceRange();
John McCalld226f652010-08-21 09:40:31 +00006366 return 0;
Anders Carlssonc3082412009-03-14 00:33:21 +00006367 }
Anders Carlssonfb311762009-03-14 00:25:26 +00006368
Anders Carlssonc3082412009-03-14 00:33:21 +00006369 if (Value == 0) {
Mike Stump1eb44332009-09-09 15:08:12 +00006370 Diag(AssertLoc, diag::err_static_assert_failed)
Benjamin Kramer8d042582009-12-11 13:33:18 +00006371 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlssonc3082412009-03-14 00:33:21 +00006372 }
6373 }
Mike Stump1eb44332009-09-09 15:08:12 +00006374
Douglas Gregor399ad972010-12-15 23:55:21 +00006375 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
6376 return 0;
6377
Mike Stump1eb44332009-09-09 15:08:12 +00006378 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
Anders Carlssonfb311762009-03-14 00:25:26 +00006379 AssertExpr, AssertMessage);
Mike Stump1eb44332009-09-09 15:08:12 +00006380
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006381 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +00006382 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +00006383}
Sebastian Redl50de12f2009-03-24 22:27:57 +00006384
Douglas Gregor1d869352010-04-07 16:53:43 +00006385/// \brief Perform semantic analysis of the given friend type declaration.
6386///
6387/// \returns A friend declaration that.
6388FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc,
6389 TypeSourceInfo *TSInfo) {
6390 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
6391
6392 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00006393 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +00006394
Douglas Gregor06245bf2010-04-07 17:57:12 +00006395 if (!getLangOptions().CPlusPlus0x) {
6396 // C++03 [class.friend]p2:
6397 // An elaborated-type-specifier shall be used in a friend declaration
6398 // for a class.*
6399 //
6400 // * The class-key of the elaborated-type-specifier is required.
6401 if (!ActiveTemplateInstantiations.empty()) {
6402 // Do not complain about the form of friend template types during
6403 // template instantiation; we will already have complained when the
6404 // template was declared.
6405 } else if (!T->isElaboratedTypeSpecifier()) {
6406 // If we evaluated the type to a record type, suggest putting
6407 // a tag in front.
6408 if (const RecordType *RT = T->getAs<RecordType>()) {
6409 RecordDecl *RD = RT->getDecl();
6410
6411 std::string InsertionText = std::string(" ") + RD->getKindName();
6412
6413 Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type)
6414 << (unsigned) RD->getTagKind()
6415 << T
6416 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
6417 InsertionText);
6418 } else {
6419 Diag(FriendLoc, diag::ext_nonclass_type_friend)
6420 << T
6421 << SourceRange(FriendLoc, TypeRange.getEnd());
6422 }
6423 } else if (T->getAs<EnumType>()) {
6424 Diag(FriendLoc, diag::ext_enum_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +00006425 << T
Douglas Gregor1d869352010-04-07 16:53:43 +00006426 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregor1d869352010-04-07 16:53:43 +00006427 }
6428 }
6429
Douglas Gregor06245bf2010-04-07 17:57:12 +00006430 // C++0x [class.friend]p3:
6431 // If the type specifier in a friend declaration designates a (possibly
6432 // cv-qualified) class type, that class is declared as a friend; otherwise,
6433 // the friend declaration is ignored.
6434
6435 // FIXME: C++0x has some syntactic restrictions on friend type declarations
6436 // in [class.friend]p3 that we do not implement.
Douglas Gregor1d869352010-04-07 16:53:43 +00006437
6438 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc);
6439}
6440
John McCall9a34edb2010-10-19 01:40:49 +00006441/// Handle a friend tag declaration where the scope specifier was
6442/// templated.
6443Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
6444 unsigned TagSpec, SourceLocation TagLoc,
6445 CXXScopeSpec &SS,
6446 IdentifierInfo *Name, SourceLocation NameLoc,
6447 AttributeList *Attr,
6448 MultiTemplateParamsArg TempParamLists) {
6449 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
6450
6451 bool isExplicitSpecialization = false;
6452 unsigned NumMatchedTemplateParamLists = TempParamLists.size();
6453 bool Invalid = false;
6454
6455 if (TemplateParameterList *TemplateParams
6456 = MatchTemplateParametersToScopeSpecifier(TagLoc, SS,
6457 TempParamLists.get(),
6458 TempParamLists.size(),
6459 /*friend*/ true,
6460 isExplicitSpecialization,
6461 Invalid)) {
6462 --NumMatchedTemplateParamLists;
6463
6464 if (TemplateParams->size() > 0) {
6465 // This is a declaration of a class template.
6466 if (Invalid)
6467 return 0;
6468
6469 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
6470 SS, Name, NameLoc, Attr,
6471 TemplateParams, AS_public).take();
6472 } else {
6473 // The "template<>" header is extraneous.
6474 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
6475 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
6476 isExplicitSpecialization = true;
6477 }
6478 }
6479
6480 if (Invalid) return 0;
6481
6482 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
6483
6484 bool isAllExplicitSpecializations = true;
6485 for (unsigned I = 0; I != NumMatchedTemplateParamLists; ++I) {
6486 if (TempParamLists.get()[I]->size()) {
6487 isAllExplicitSpecializations = false;
6488 break;
6489 }
6490 }
6491
6492 // FIXME: don't ignore attributes.
6493
6494 // If it's explicit specializations all the way down, just forget
6495 // about the template header and build an appropriate non-templated
6496 // friend. TODO: for source fidelity, remember the headers.
6497 if (isAllExplicitSpecializations) {
6498 ElaboratedTypeKeyword Keyword
6499 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
6500 QualType T = CheckTypenameType(Keyword, SS.getScopeRep(), *Name,
6501 TagLoc, SS.getRange(), NameLoc);
6502 if (T.isNull())
6503 return 0;
6504
6505 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
6506 if (isa<DependentNameType>(T)) {
6507 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
6508 TL.setKeywordLoc(TagLoc);
6509 TL.setQualifierRange(SS.getRange());
6510 TL.setNameLoc(NameLoc);
6511 } else {
6512 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
6513 TL.setKeywordLoc(TagLoc);
6514 TL.setQualifierRange(SS.getRange());
6515 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
6516 }
6517
6518 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
6519 TSI, FriendLoc);
6520 Friend->setAccess(AS_public);
6521 CurContext->addDecl(Friend);
6522 return Friend;
6523 }
6524
6525 // Handle the case of a templated-scope friend class. e.g.
6526 // template <class T> class A<T>::B;
6527 // FIXME: we don't support these right now.
6528 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
6529 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
6530 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
6531 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
6532 TL.setKeywordLoc(TagLoc);
6533 TL.setQualifierRange(SS.getRange());
6534 TL.setNameLoc(NameLoc);
6535
6536 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
6537 TSI, FriendLoc);
6538 Friend->setAccess(AS_public);
6539 Friend->setUnsupportedFriend(true);
6540 CurContext->addDecl(Friend);
6541 return Friend;
6542}
6543
6544
John McCalldd4a3b02009-09-16 22:47:08 +00006545/// Handle a friend type declaration. This works in tandem with
6546/// ActOnTag.
6547///
6548/// Notes on friend class templates:
6549///
6550/// We generally treat friend class declarations as if they were
6551/// declaring a class. So, for example, the elaborated type specifier
6552/// in a friend declaration is required to obey the restrictions of a
6553/// class-head (i.e. no typedefs in the scope chain), template
6554/// parameters are required to match up with simple template-ids, &c.
6555/// However, unlike when declaring a template specialization, it's
6556/// okay to refer to a template specialization without an empty
6557/// template parameter declaration, e.g.
6558/// friend class A<T>::B<unsigned>;
6559/// We permit this as a special case; if there are any template
6560/// parameters present at all, require proper matching, i.e.
6561/// template <> template <class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +00006562Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +00006563 MultiTemplateParamsArg TempParams) {
John McCall02cace72009-08-28 07:59:38 +00006564 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall67d1a672009-08-06 02:15:43 +00006565
6566 assert(DS.isFriendSpecified());
6567 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
6568
John McCalldd4a3b02009-09-16 22:47:08 +00006569 // Try to convert the decl specifier to a type. This works for
6570 // friend templates because ActOnTag never produces a ClassTemplateDecl
6571 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +00006572 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +00006573 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
6574 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +00006575 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +00006576 return 0;
John McCall67d1a672009-08-06 02:15:43 +00006577
Douglas Gregor6ccab972010-12-16 01:14:37 +00006578 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
6579 return 0;
6580
John McCalldd4a3b02009-09-16 22:47:08 +00006581 // This is definitely an error in C++98. It's probably meant to
6582 // be forbidden in C++0x, too, but the specification is just
6583 // poorly written.
6584 //
6585 // The problem is with declarations like the following:
6586 // template <T> friend A<T>::foo;
6587 // where deciding whether a class C is a friend or not now hinges
6588 // on whether there exists an instantiation of A that causes
6589 // 'foo' to equal C. There are restrictions on class-heads
6590 // (which we declare (by fiat) elaborated friend declarations to
6591 // be) that makes this tractable.
6592 //
6593 // FIXME: handle "template <> friend class A<T>;", which
6594 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +00006595 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +00006596 Diag(Loc, diag::err_tagless_friend_type_template)
6597 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +00006598 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +00006599 }
Douglas Gregor1d869352010-04-07 16:53:43 +00006600
John McCall02cace72009-08-28 07:59:38 +00006601 // C++98 [class.friend]p1: A friend of a class is a function
6602 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +00006603 // This is fixed in DR77, which just barely didn't make the C++03
6604 // deadline. It's also a very silly restriction that seriously
6605 // affects inner classes and which nobody else seems to implement;
6606 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +00006607 //
6608 // But note that we could warn about it: it's always useless to
6609 // friend one of your own members (it's not, however, worthless to
6610 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +00006611
John McCalldd4a3b02009-09-16 22:47:08 +00006612 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +00006613 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +00006614 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +00006615 NumTempParamLists,
John McCallbe04b6d2010-10-16 07:23:36 +00006616 TempParams.release(),
John McCall32f2fb52010-03-25 18:04:51 +00006617 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +00006618 DS.getFriendSpecLoc());
6619 else
Douglas Gregor1d869352010-04-07 16:53:43 +00006620 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
6621
6622 if (!D)
John McCalld226f652010-08-21 09:40:31 +00006623 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +00006624
John McCalldd4a3b02009-09-16 22:47:08 +00006625 D->setAccess(AS_public);
6626 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +00006627
John McCalld226f652010-08-21 09:40:31 +00006628 return D;
John McCall02cace72009-08-28 07:59:38 +00006629}
6630
John McCall337ec3d2010-10-12 23:13:28 +00006631Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, bool IsDefinition,
6632 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +00006633 const DeclSpec &DS = D.getDeclSpec();
6634
6635 assert(DS.isFriendSpecified());
6636 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
6637
6638 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +00006639 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6640 QualType T = TInfo->getType();
John McCall67d1a672009-08-06 02:15:43 +00006641
6642 // C++ [class.friend]p1
6643 // A friend of a class is a function or class....
6644 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +00006645 // It *doesn't* see through dependent types, which is correct
6646 // according to [temp.arg.type]p3:
6647 // If a declaration acquires a function type through a
6648 // type dependent on a template-parameter and this causes
6649 // a declaration that does not use the syntactic form of a
6650 // function declarator to have a function type, the program
6651 // is ill-formed.
John McCall67d1a672009-08-06 02:15:43 +00006652 if (!T->isFunctionType()) {
6653 Diag(Loc, diag::err_unexpected_friend);
6654
6655 // It might be worthwhile to try to recover by creating an
6656 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +00006657 return 0;
John McCall67d1a672009-08-06 02:15:43 +00006658 }
6659
6660 // C++ [namespace.memdef]p3
6661 // - If a friend declaration in a non-local class first declares a
6662 // class or function, the friend class or function is a member
6663 // of the innermost enclosing namespace.
6664 // - The name of the friend is not found by simple name lookup
6665 // until a matching declaration is provided in that namespace
6666 // scope (either before or after the class declaration granting
6667 // friendship).
6668 // - If a friend function is called, its name may be found by the
6669 // name lookup that considers functions from namespaces and
6670 // classes associated with the types of the function arguments.
6671 // - When looking for a prior declaration of a class or a function
6672 // declared as a friend, scopes outside the innermost enclosing
6673 // namespace scope are not considered.
6674
John McCall337ec3d2010-10-12 23:13:28 +00006675 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00006676 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6677 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +00006678 assert(Name);
6679
Douglas Gregor6ccab972010-12-16 01:14:37 +00006680 // Check for unexpanded parameter packs.
6681 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
6682 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
6683 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
6684 return 0;
6685
John McCall67d1a672009-08-06 02:15:43 +00006686 // The context we found the declaration in, or in which we should
6687 // create the declaration.
6688 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +00006689 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +00006690 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +00006691 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +00006692
John McCall337ec3d2010-10-12 23:13:28 +00006693 // FIXME: there are different rules in local classes
John McCall67d1a672009-08-06 02:15:43 +00006694
John McCall337ec3d2010-10-12 23:13:28 +00006695 // There are four cases here.
6696 // - There's no scope specifier, in which case we just go to the
John McCall29ae6e52010-10-13 05:45:15 +00006697 // appropriate scope and look for a function or function template
John McCall337ec3d2010-10-12 23:13:28 +00006698 // there as appropriate.
6699 // Recover from invalid scope qualifiers as if they just weren't there.
6700 if (SS.isInvalid() || !SS.isSet()) {
John McCall29ae6e52010-10-13 05:45:15 +00006701 // C++0x [namespace.memdef]p3:
6702 // If the name in a friend declaration is neither qualified nor
6703 // a template-id and the declaration is a function or an
6704 // elaborated-type-specifier, the lookup to determine whether
6705 // the entity has been previously declared shall not consider
6706 // any scopes outside the innermost enclosing namespace.
6707 // C++0x [class.friend]p11:
6708 // If a friend declaration appears in a local class and the name
6709 // specified is an unqualified name, a prior declaration is
6710 // looked up without considering scopes that are outside the
6711 // innermost enclosing non-class scope. For a friend function
6712 // declaration, if there is no prior declaration, the program is
6713 // ill-formed.
6714 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCall8a407372010-10-14 22:22:28 +00006715 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +00006716
John McCall29ae6e52010-10-13 05:45:15 +00006717 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +00006718 DC = CurContext;
6719 while (true) {
6720 // Skip class contexts. If someone can cite chapter and verse
6721 // for this behavior, that would be nice --- it's what GCC and
6722 // EDG do, and it seems like a reasonable intent, but the spec
6723 // really only says that checks for unqualified existing
6724 // declarations should stop at the nearest enclosing namespace,
6725 // not that they should only consider the nearest enclosing
6726 // namespace.
Douglas Gregor182ddf02009-09-28 00:08:27 +00006727 while (DC->isRecord())
6728 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +00006729
John McCall68263142009-11-18 22:49:29 +00006730 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +00006731
6732 // TODO: decide what we think about using declarations.
John McCall29ae6e52010-10-13 05:45:15 +00006733 if (isLocal || !Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +00006734 break;
John McCall29ae6e52010-10-13 05:45:15 +00006735
John McCall8a407372010-10-14 22:22:28 +00006736 if (isTemplateId) {
6737 if (isa<TranslationUnitDecl>(DC)) break;
6738 } else {
6739 if (DC->isFileContext()) break;
6740 }
John McCall67d1a672009-08-06 02:15:43 +00006741 DC = DC->getParent();
6742 }
6743
6744 // C++ [class.friend]p1: A friend of a class is a function or
6745 // class that is not a member of the class . . .
John McCall7f27d922009-08-06 20:49:32 +00006746 // C++0x changes this for both friend types and functions.
6747 // Most C++ 98 compilers do seem to give an error here, so
6748 // we do, too.
John McCall68263142009-11-18 22:49:29 +00006749 if (!Previous.empty() && DC->Equals(CurContext)
6750 && !getLangOptions().CPlusPlus0x)
John McCall67d1a672009-08-06 02:15:43 +00006751 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
John McCall337ec3d2010-10-12 23:13:28 +00006752
John McCall380aaa42010-10-13 06:22:15 +00006753 DCScope = getScopeForDeclContext(S, DC);
John McCall29ae6e52010-10-13 05:45:15 +00006754
John McCall337ec3d2010-10-12 23:13:28 +00006755 // - There's a non-dependent scope specifier, in which case we
6756 // compute it and do a previous lookup there for a function
6757 // or function template.
6758 } else if (!SS.getScopeRep()->isDependent()) {
6759 DC = computeDeclContext(SS);
6760 if (!DC) return 0;
6761
6762 if (RequireCompleteDeclContext(SS, DC)) return 0;
6763
6764 LookupQualifiedName(Previous, DC);
6765
6766 // Ignore things found implicitly in the wrong scope.
6767 // TODO: better diagnostics for this case. Suggesting the right
6768 // qualified scope would be nice...
6769 LookupResult::Filter F = Previous.makeFilter();
6770 while (F.hasNext()) {
6771 NamedDecl *D = F.next();
6772 if (!DC->InEnclosingNamespaceSetOf(
6773 D->getDeclContext()->getRedeclContext()))
6774 F.erase();
6775 }
6776 F.done();
6777
6778 if (Previous.empty()) {
6779 D.setInvalidType();
6780 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
6781 return 0;
6782 }
6783
6784 // C++ [class.friend]p1: A friend of a class is a function or
6785 // class that is not a member of the class . . .
6786 if (DC->Equals(CurContext))
6787 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
6788
6789 // - There's a scope specifier that does not match any template
6790 // parameter lists, in which case we use some arbitrary context,
6791 // create a method or method template, and wait for instantiation.
6792 // - There's a scope specifier that does match some template
6793 // parameter lists, which we don't handle right now.
6794 } else {
6795 DC = CurContext;
6796 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +00006797 }
6798
John McCall29ae6e52010-10-13 05:45:15 +00006799 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +00006800 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00006801 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
6802 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
6803 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +00006804 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +00006805 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
6806 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +00006807 return 0;
John McCall67d1a672009-08-06 02:15:43 +00006808 }
John McCall67d1a672009-08-06 02:15:43 +00006809 }
6810
Douglas Gregor182ddf02009-09-28 00:08:27 +00006811 bool Redeclaration = false;
John McCall380aaa42010-10-13 06:22:15 +00006812 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, T, TInfo, Previous,
Douglas Gregora735b202009-10-13 14:39:41 +00006813 move(TemplateParams),
John McCall3f9a8a62009-08-11 06:59:38 +00006814 IsDefinition,
6815 Redeclaration);
John McCalld226f652010-08-21 09:40:31 +00006816 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +00006817
Douglas Gregor182ddf02009-09-28 00:08:27 +00006818 assert(ND->getDeclContext() == DC);
6819 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +00006820
John McCallab88d972009-08-31 22:39:49 +00006821 // Add the function declaration to the appropriate lookup tables,
6822 // adjusting the redeclarations list as necessary. We don't
6823 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +00006824 //
John McCallab88d972009-08-31 22:39:49 +00006825 // Also update the scope-based lookup if the target context's
6826 // lookup context is in lexical scope.
6827 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00006828 DC = DC->getRedeclContext();
Douglas Gregor182ddf02009-09-28 00:08:27 +00006829 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCallab88d972009-08-31 22:39:49 +00006830 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +00006831 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +00006832 }
John McCall02cace72009-08-28 07:59:38 +00006833
6834 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +00006835 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +00006836 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +00006837 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +00006838 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +00006839
John McCall337ec3d2010-10-12 23:13:28 +00006840 if (ND->isInvalidDecl())
6841 FrD->setInvalidDecl();
John McCall6102ca12010-10-16 06:59:13 +00006842 else {
6843 FunctionDecl *FD;
6844 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
6845 FD = FTD->getTemplatedDecl();
6846 else
6847 FD = cast<FunctionDecl>(ND);
6848
6849 // Mark templated-scope function declarations as unsupported.
6850 if (FD->getNumTemplateParameterLists())
6851 FrD->setUnsupportedFriend(true);
6852 }
John McCall337ec3d2010-10-12 23:13:28 +00006853
John McCalld226f652010-08-21 09:40:31 +00006854 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +00006855}
6856
John McCalld226f652010-08-21 09:40:31 +00006857void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
6858 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +00006859
Sebastian Redl50de12f2009-03-24 22:27:57 +00006860 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
6861 if (!Fn) {
6862 Diag(DelLoc, diag::err_deleted_non_function);
6863 return;
6864 }
6865 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
6866 Diag(DelLoc, diag::err_deleted_decl_not_first);
6867 Diag(Prev->getLocation(), diag::note_previous_declaration);
6868 // If the declaration wasn't the first, we delete the function anyway for
6869 // recovery.
6870 }
6871 Fn->setDeleted();
6872}
Sebastian Redl13e88542009-04-27 21:33:24 +00006873
6874static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
6875 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
6876 ++CI) {
6877 Stmt *SubStmt = *CI;
6878 if (!SubStmt)
6879 continue;
6880 if (isa<ReturnStmt>(SubStmt))
6881 Self.Diag(SubStmt->getSourceRange().getBegin(),
6882 diag::err_return_in_constructor_handler);
6883 if (!isa<Expr>(SubStmt))
6884 SearchForReturnInStmt(Self, SubStmt);
6885 }
6886}
6887
6888void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
6889 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
6890 CXXCatchStmt *Handler = TryBlock->getHandler(I);
6891 SearchForReturnInStmt(*this, Handler);
6892 }
6893}
Anders Carlssond7ba27d2009-05-14 01:09:04 +00006894
Mike Stump1eb44332009-09-09 15:08:12 +00006895bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +00006896 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +00006897 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
6898 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +00006899
Chandler Carruth73857792010-02-15 11:53:20 +00006900 if (Context.hasSameType(NewTy, OldTy) ||
6901 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +00006902 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00006903
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006904 // Check if the return types are covariant
6905 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +00006906
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006907 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00006908 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
6909 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006910 NewClassTy = NewPT->getPointeeType();
6911 OldClassTy = OldPT->getPointeeType();
6912 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00006913 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
6914 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
6915 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
6916 NewClassTy = NewRT->getPointeeType();
6917 OldClassTy = OldRT->getPointeeType();
6918 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006919 }
6920 }
Mike Stump1eb44332009-09-09 15:08:12 +00006921
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006922 // The return types aren't either both pointers or references to a class type.
6923 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +00006924 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006925 diag::err_different_return_type_for_overriding_virtual_function)
6926 << New->getDeclName() << NewTy << OldTy;
6927 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +00006928
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006929 return true;
6930 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +00006931
Anders Carlssonbe2e2052009-12-31 18:34:24 +00006932 // C++ [class.virtual]p6:
6933 // If the return type of D::f differs from the return type of B::f, the
6934 // class type in the return type of D::f shall be complete at the point of
6935 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +00006936 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
6937 if (!RT->isBeingDefined() &&
6938 RequireCompleteType(New->getLocation(), NewClassTy,
6939 PDiag(diag::err_covariant_return_incomplete)
6940 << New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +00006941 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +00006942 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +00006943
Douglas Gregora4923eb2009-11-16 21:35:15 +00006944 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006945 // Check if the new class derives from the old class.
6946 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
6947 Diag(New->getLocation(),
6948 diag::err_covariant_return_not_derived)
6949 << New->getDeclName() << NewTy << OldTy;
6950 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6951 return true;
6952 }
Mike Stump1eb44332009-09-09 15:08:12 +00006953
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006954 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +00006955 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +00006956 diag::err_covariant_return_inaccessible_base,
6957 diag::err_covariant_return_ambiguous_derived_to_base_conv,
6958 // FIXME: Should this point to the return type?
6959 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006960 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6961 return true;
6962 }
6963 }
Mike Stump1eb44332009-09-09 15:08:12 +00006964
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006965 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00006966 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006967 Diag(New->getLocation(),
6968 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +00006969 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006970 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6971 return true;
6972 };
Mike Stump1eb44332009-09-09 15:08:12 +00006973
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006974
6975 // The new class type must have the same or less qualifiers as the old type.
6976 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
6977 Diag(New->getLocation(),
6978 diag::err_covariant_return_type_class_type_more_qualified)
6979 << New->getDeclName() << NewTy << OldTy;
6980 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6981 return true;
6982 };
Mike Stump1eb44332009-09-09 15:08:12 +00006983
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006984 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +00006985}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00006986
Douglas Gregor4ba31362009-12-01 17:24:26 +00006987/// \brief Mark the given method pure.
6988///
6989/// \param Method the method to be marked pure.
6990///
6991/// \param InitRange the source range that covers the "0" initializer.
6992bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
6993 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
6994 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +00006995 return false;
6996 }
6997
6998 if (!Method->isInvalidDecl())
6999 Diag(Method->getLocation(), diag::err_non_virtual_pure)
7000 << Method->getDeclName() << InitRange;
7001 return true;
7002}
7003
John McCall731ad842009-12-19 09:28:58 +00007004/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
7005/// an initializer for the out-of-line declaration 'Dcl'. The scope
7006/// is a fresh scope pushed for just this purpose.
7007///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00007008/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
7009/// static data member of class X, names should be looked up in the scope of
7010/// class X.
John McCalld226f652010-08-21 09:40:31 +00007011void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00007012 // If there is no declaration, there was an error parsing it.
John McCall731ad842009-12-19 09:28:58 +00007013 if (D == 0) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00007014
John McCall731ad842009-12-19 09:28:58 +00007015 // We should only get called for declarations with scope specifiers, like:
7016 // int foo::bar;
7017 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +00007018 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00007019}
7020
7021/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +00007022/// initializer for the out-of-line declaration 'D'.
7023void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00007024 // If there is no declaration, there was an error parsing it.
John McCall731ad842009-12-19 09:28:58 +00007025 if (D == 0) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00007026
John McCall731ad842009-12-19 09:28:58 +00007027 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +00007028 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00007029}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00007030
7031/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
7032/// C++ if/switch/while/for statement.
7033/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +00007034DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00007035 // C++ 6.4p2:
7036 // The declarator shall not specify a function or an array.
7037 // The type-specifier-seq shall not contain typedef and shall not declare a
7038 // new class or enumeration.
7039 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
7040 "Parser allowed 'typedef' as storage class of condition decl.");
7041
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00007042 TagDecl *OwnedTag = 0;
John McCallbf1a0282010-06-04 23:28:52 +00007043 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S, &OwnedTag);
7044 QualType Ty = TInfo->getType();
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00007045
7046 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
7047 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
7048 // would be created and CXXConditionDeclExpr wants a VarDecl.
7049 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
7050 << D.getSourceRange();
7051 return DeclResult();
7052 } else if (OwnedTag && OwnedTag->isDefinition()) {
7053 // The type-specifier-seq shall not declare a new class or enumeration.
7054 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
7055 }
7056
John McCalld226f652010-08-21 09:40:31 +00007057 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00007058 if (!Dcl)
7059 return DeclResult();
7060
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00007061 return Dcl;
7062}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00007063
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007064void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
7065 bool DefinitionRequired) {
7066 // Ignore any vtable uses in unevaluated operands or for classes that do
7067 // not have a vtable.
7068 if (!Class->isDynamicClass() || Class->isDependentContext() ||
7069 CurContext->isDependentContext() ||
7070 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolabbf58bb2010-03-10 02:19:29 +00007071 return;
7072
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007073 // Try to insert this class into the map.
7074 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
7075 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
7076 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
7077 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +00007078 // If we already had an entry, check to see if we are promoting this vtable
7079 // to required a definition. If so, we need to reappend to the VTableUses
7080 // list, since we may have already processed the first entry.
7081 if (DefinitionRequired && !Pos.first->second) {
7082 Pos.first->second = true;
7083 } else {
7084 // Otherwise, we can early exit.
7085 return;
7086 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007087 }
7088
7089 // Local classes need to have their virtual members marked
7090 // immediately. For all other classes, we mark their virtual members
7091 // at the end of the translation unit.
7092 if (Class->isLocalClass())
7093 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +00007094 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007095 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +00007096}
7097
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007098bool Sema::DefineUsedVTables() {
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007099 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +00007100 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +00007101
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007102 // Note: The VTableUses vector could grow as a result of marking
7103 // the members of a class as "used", so we check the size each
7104 // time through the loop and prefer indices (with are stable) to
7105 // iterators (which are not).
7106 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +00007107 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007108 if (!Class)
7109 continue;
7110
7111 SourceLocation Loc = VTableUses[I].second;
7112
7113 // If this class has a key function, but that key function is
7114 // defined in another translation unit, we don't need to emit the
7115 // vtable even though we're using it.
7116 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00007117 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007118 switch (KeyFunction->getTemplateSpecializationKind()) {
7119 case TSK_Undeclared:
7120 case TSK_ExplicitSpecialization:
7121 case TSK_ExplicitInstantiationDeclaration:
7122 // The key function is in another translation unit.
7123 continue;
7124
7125 case TSK_ExplicitInstantiationDefinition:
7126 case TSK_ImplicitInstantiation:
7127 // We will be instantiating the key function.
7128 break;
7129 }
7130 } else if (!KeyFunction) {
7131 // If we have a class with no key function that is the subject
7132 // of an explicit instantiation declaration, suppress the
7133 // vtable; it will live with the explicit instantiation
7134 // definition.
7135 bool IsExplicitInstantiationDeclaration
7136 = Class->getTemplateSpecializationKind()
7137 == TSK_ExplicitInstantiationDeclaration;
7138 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
7139 REnd = Class->redecls_end();
7140 R != REnd; ++R) {
7141 TemplateSpecializationKind TSK
7142 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
7143 if (TSK == TSK_ExplicitInstantiationDeclaration)
7144 IsExplicitInstantiationDeclaration = true;
7145 else if (TSK == TSK_ExplicitInstantiationDefinition) {
7146 IsExplicitInstantiationDeclaration = false;
7147 break;
7148 }
7149 }
7150
7151 if (IsExplicitInstantiationDeclaration)
7152 continue;
7153 }
7154
7155 // Mark all of the virtual members of this class as referenced, so
7156 // that we can build a vtable. Then, tell the AST consumer that a
7157 // vtable for this class is required.
7158 MarkVirtualMembersReferenced(Loc, Class);
7159 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
7160 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
7161
7162 // Optionally warn if we're emitting a weak vtable.
7163 if (Class->getLinkage() == ExternalLinkage &&
7164 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00007165 if (!KeyFunction || (KeyFunction->hasBody() && KeyFunction->isInlined()))
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007166 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
7167 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00007168 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007169 VTableUses.clear();
7170
Anders Carlssond6a637f2009-12-07 08:24:59 +00007171 return true;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00007172}
Anders Carlssond6a637f2009-12-07 08:24:59 +00007173
Rafael Espindola3e1ae932010-03-26 00:36:59 +00007174void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
7175 const CXXRecordDecl *RD) {
Anders Carlssond6a637f2009-12-07 08:24:59 +00007176 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
7177 e = RD->method_end(); i != e; ++i) {
7178 CXXMethodDecl *MD = *i;
7179
7180 // C++ [basic.def.odr]p2:
7181 // [...] A virtual member function is used if it is not pure. [...]
7182 if (MD->isVirtual() && !MD->isPure())
7183 MarkDeclarationReferenced(Loc, MD);
7184 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +00007185
7186 // Only classes that have virtual bases need a VTT.
7187 if (RD->getNumVBases() == 0)
7188 return;
7189
7190 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
7191 e = RD->bases_end(); i != e; ++i) {
7192 const CXXRecordDecl *Base =
7193 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +00007194 if (Base->getNumVBases() == 0)
7195 continue;
7196 MarkVirtualMembersReferenced(Loc, Base);
7197 }
Anders Carlssond6a637f2009-12-07 08:24:59 +00007198}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007199
7200/// SetIvarInitializers - This routine builds initialization ASTs for the
7201/// Objective-C implementation whose ivars need be initialized.
7202void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
7203 if (!getLangOptions().CPlusPlus)
7204 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00007205 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007206 llvm::SmallVector<ObjCIvarDecl*, 8> ivars;
7207 CollectIvarsToConstructOrDestruct(OID, ivars);
7208 if (ivars.empty())
7209 return;
Sean Huntcbb67482011-01-08 20:30:50 +00007210 llvm::SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007211 for (unsigned i = 0; i < ivars.size(); i++) {
7212 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +00007213 if (Field->isInvalidDecl())
7214 continue;
7215
Sean Huntcbb67482011-01-08 20:30:50 +00007216 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007217 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
7218 InitializationKind InitKind =
7219 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
7220
7221 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00007222 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00007223 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregor53c374f2010-12-07 00:41:46 +00007224 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007225 // Note, MemberInit could actually come back empty if no initialization
7226 // is required (e.g., because it would call a trivial default constructor)
7227 if (!MemberInit.get() || MemberInit.isInvalid())
7228 continue;
John McCallb4eb64d2010-10-08 02:01:28 +00007229
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007230 Member =
Sean Huntcbb67482011-01-08 20:30:50 +00007231 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
7232 SourceLocation(),
7233 MemberInit.takeAs<Expr>(),
7234 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007235 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +00007236
7237 // Be sure that the destructor is accessible and is marked as referenced.
7238 if (const RecordType *RecordTy
7239 = Context.getBaseElementType(Field->getType())
7240 ->getAs<RecordType>()) {
7241 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +00007242 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Douglas Gregor68dd3ee2010-05-20 02:24:22 +00007243 MarkDeclarationReferenced(Field->getLocation(), Destructor);
7244 CheckDestructorAccess(Field->getLocation(), Destructor,
7245 PDiag(diag::err_access_dtor_ivar)
7246 << Context.getBaseElementType(Field->getType()));
7247 }
7248 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007249 }
7250 ObjCImplementation->setIvarInitializers(Context,
7251 AllToInit.data(), AllToInit.size());
7252 }
7253}