blob: bc6584bc736efc1e92c70a8850fbe96760147c8c [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"
Sebastian Redl58a2cd82011-04-24 16:28:06 +000021#include "clang/AST/ASTMutationListener.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000022#include "clang/AST/CharUnits.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000023#include "clang/AST/CXXInheritance.h"
Anders Carlsson8211eff2009-03-24 01:19:16 +000024#include "clang/AST/DeclVisitor.h"
Sean Hunt41717662011-02-26 19:13:13 +000025#include "clang/AST/ExprCXX.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000026#include "clang/AST/RecordLayout.h"
27#include "clang/AST/StmtVisitor.h"
Douglas Gregor802ab452009-12-02 22:36:29 +000028#include "clang/AST/TypeLoc.h"
Douglas Gregor02189362008-10-22 21:13:31 +000029#include "clang/AST/TypeOrdering.h"
John McCall19510852010-08-20 18:27:03 +000030#include "clang/Sema/DeclSpec.h"
31#include "clang/Sema/ParsedTemplate.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000032#include "clang/Basic/PartialDiagnostic.h"
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +000033#include "clang/Lex/Preprocessor.h"
John McCall50df6ae2010-08-25 07:03:20 +000034#include "llvm/ADT/DenseSet.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000035#include "llvm/ADT/STLExtras.h"
Douglas Gregorf8268ae2008-10-22 17:49:05 +000036#include <map>
Douglas Gregora8f32e02009-10-06 17:59:45 +000037#include <set>
Chris Lattner3d1cee32008-04-08 05:04:30 +000038
39using namespace clang;
40
Chris Lattner8123a952008-04-10 02:22:51 +000041//===----------------------------------------------------------------------===//
42// CheckDefaultArgumentVisitor
43//===----------------------------------------------------------------------===//
44
Chris Lattner9e979552008-04-12 23:52:44 +000045namespace {
46 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
47 /// the default argument of a parameter to determine whether it
48 /// contains any ill-formed subexpressions. For example, this will
49 /// diagnose the use of local variables or parameters within the
50 /// default argument expression.
Benjamin Kramer85b45212009-11-28 19:45:26 +000051 class CheckDefaultArgumentVisitor
Chris Lattnerb77792e2008-07-26 22:17:49 +000052 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattner9e979552008-04-12 23:52:44 +000053 Expr *DefaultArg;
54 Sema *S;
Chris Lattner8123a952008-04-10 02:22:51 +000055
Chris Lattner9e979552008-04-12 23:52:44 +000056 public:
Mike Stump1eb44332009-09-09 15:08:12 +000057 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattner9e979552008-04-12 23:52:44 +000058 : DefaultArg(defarg), S(s) {}
Chris Lattner8123a952008-04-10 02:22:51 +000059
Chris Lattner9e979552008-04-12 23:52:44 +000060 bool VisitExpr(Expr *Node);
61 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor796da182008-11-04 14:32:21 +000062 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattner9e979552008-04-12 23:52:44 +000063 };
Chris Lattner8123a952008-04-10 02:22:51 +000064
Chris Lattner9e979552008-04-12 23:52:44 +000065 /// VisitExpr - Visit all of the children of this expression.
66 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
67 bool IsInvalid = false;
John McCall7502c1d2011-02-13 04:07:26 +000068 for (Stmt::child_range I = Node->children(); I; ++I)
Chris Lattnerb77792e2008-07-26 22:17:49 +000069 IsInvalid |= Visit(*I);
Chris Lattner9e979552008-04-12 23:52:44 +000070 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000071 }
72
Chris Lattner9e979552008-04-12 23:52:44 +000073 /// VisitDeclRefExpr - Visit a reference to a declaration, to
74 /// determine whether this declaration can be used in the default
75 /// argument expression.
76 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000077 NamedDecl *Decl = DRE->getDecl();
Chris Lattner9e979552008-04-12 23:52:44 +000078 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
79 // C++ [dcl.fct.default]p9
80 // Default arguments are evaluated each time the function is
81 // called. The order of evaluation of function arguments is
82 // unspecified. Consequently, parameters of a function shall not
83 // be used in default argument expressions, even if they are not
84 // evaluated. Parameters of a function declared before a default
85 // argument expression are in scope and can hide namespace and
86 // class member names.
Mike Stump1eb44332009-09-09 15:08:12 +000087 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000088 diag::err_param_default_argument_references_param)
Chris Lattner08631c52008-11-23 21:45:46 +000089 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff248a7532008-04-15 22:42:06 +000090 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000091 // C++ [dcl.fct.default]p7
92 // Local variables shall not be used in default argument
93 // expressions.
John McCallb6bbcc92010-10-15 04:57:14 +000094 if (VDecl->isLocalVarDecl())
Mike Stump1eb44332009-09-09 15:08:12 +000095 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000096 diag::err_param_default_argument_references_local)
Chris Lattner08631c52008-11-23 21:45:46 +000097 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +000098 }
Chris Lattner8123a952008-04-10 02:22:51 +000099
Douglas Gregor3996f232008-11-04 13:41:56 +0000100 return false;
101 }
Chris Lattner9e979552008-04-12 23:52:44 +0000102
Douglas Gregor796da182008-11-04 14:32:21 +0000103 /// VisitCXXThisExpr - Visit a C++ "this" expression.
104 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
105 // C++ [dcl.fct.default]p8:
106 // The keyword this shall not be used in a default argument of a
107 // member function.
108 return S->Diag(ThisE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000109 diag::err_param_default_argument_references_this)
110 << ThisE->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000111 }
Chris Lattner8123a952008-04-10 02:22:51 +0000112}
113
Anders Carlssoned961f92009-08-25 02:29:20 +0000114bool
John McCall9ae2f072010-08-23 23:25:46 +0000115Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump1eb44332009-09-09 15:08:12 +0000116 SourceLocation EqualLoc) {
Anders Carlsson5653ca52009-08-25 13:46:13 +0000117 if (RequireCompleteType(Param->getLocation(), Param->getType(),
118 diag::err_typecheck_decl_incomplete_type)) {
119 Param->setInvalidDecl();
120 return true;
121 }
122
Anders Carlssoned961f92009-08-25 02:29:20 +0000123 // C++ [dcl.fct.default]p5
124 // A default argument expression is implicitly converted (clause
125 // 4) to the parameter type. The default argument expression has
126 // the same semantic constraints as the initializer expression in
127 // a declaration of a variable of the parameter type, using the
128 // copy-initialization semantics (8.5).
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000129 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
130 Param);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000131 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
132 EqualLoc);
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000133 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
John McCall60d7b3a2010-08-24 06:29:42 +0000134 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
Nico Weber6bb4dcb2010-11-28 22:53:37 +0000135 MultiExprArg(*this, &Arg, 1));
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000136 if (Result.isInvalid())
Anders Carlsson9351c172009-08-25 03:18:48 +0000137 return true;
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000138 Arg = Result.takeAs<Expr>();
Anders Carlssoned961f92009-08-25 02:29:20 +0000139
John McCallb4eb64d2010-10-08 02:01:28 +0000140 CheckImplicitConversions(Arg, EqualLoc);
John McCall4765fa02010-12-06 08:20:24 +0000141 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000142
Anders Carlssoned961f92009-08-25 02:29:20 +0000143 // Okay: add the default argument to the parameter
144 Param->setDefaultArg(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000145
Douglas Gregor8cfb7a32010-10-12 18:23:32 +0000146 // We have already instantiated this parameter; provide each of the
147 // instantiations with the uninstantiated default argument.
148 UnparsedDefaultArgInstantiationsMap::iterator InstPos
149 = UnparsedDefaultArgInstantiations.find(Param);
150 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
151 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
152 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
153
154 // We're done tracking this parameter's instantiations.
155 UnparsedDefaultArgInstantiations.erase(InstPos);
156 }
157
Anders Carlsson9351c172009-08-25 03:18:48 +0000158 return false;
Anders Carlssoned961f92009-08-25 02:29:20 +0000159}
160
Chris Lattner8123a952008-04-10 02:22:51 +0000161/// ActOnParamDefaultArgument - Check whether the default argument
162/// provided for a function parameter is well-formed. If so, attach it
163/// to the parameter declaration.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000164void
John McCalld226f652010-08-21 09:40:31 +0000165Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000166 Expr *DefaultArg) {
167 if (!param || !DefaultArg)
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000168 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000169
John McCalld226f652010-08-21 09:40:31 +0000170 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000171 UnparsedDefaultArgLocs.erase(Param);
172
Chris Lattner3d1cee32008-04-08 05:04:30 +0000173 // Default arguments are only permitted in C++
174 if (!getLangOptions().CPlusPlus) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000175 Diag(EqualLoc, diag::err_param_default_argument)
176 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000177 Param->setInvalidDecl();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000178 return;
179 }
180
Douglas Gregor6f526752010-12-16 08:48:57 +0000181 // Check for unexpanded parameter packs.
182 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
183 Param->setInvalidDecl();
184 return;
185 }
186
Anders Carlsson66e30672009-08-25 01:02:06 +0000187 // Check that the default argument is well-formed
John McCall9ae2f072010-08-23 23:25:46 +0000188 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
189 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlsson66e30672009-08-25 01:02:06 +0000190 Param->setInvalidDecl();
191 return;
192 }
Mike Stump1eb44332009-09-09 15:08:12 +0000193
John McCall9ae2f072010-08-23 23:25:46 +0000194 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000195}
196
Douglas Gregor61366e92008-12-24 00:01:03 +0000197/// ActOnParamUnparsedDefaultArgument - We've seen a default
198/// argument for a function parameter, but we can't parse it yet
199/// because we're inside a class definition. Note that this default
200/// argument will be parsed later.
John McCalld226f652010-08-21 09:40:31 +0000201void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson5e300d12009-06-12 16:51:40 +0000202 SourceLocation EqualLoc,
203 SourceLocation ArgLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000204 if (!param)
205 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000206
John McCalld226f652010-08-21 09:40:31 +0000207 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000208 if (Param)
209 Param->setUnparsedDefaultArg();
Mike Stump1eb44332009-09-09 15:08:12 +0000210
Anders Carlsson5e300d12009-06-12 16:51:40 +0000211 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor61366e92008-12-24 00:01:03 +0000212}
213
Douglas Gregor72b505b2008-12-16 21:30:33 +0000214/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
215/// the default argument for the parameter param failed.
John McCalld226f652010-08-21 09:40:31 +0000216void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000217 if (!param)
218 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000219
John McCalld226f652010-08-21 09:40:31 +0000220 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Mike Stump1eb44332009-09-09 15:08:12 +0000221
Anders Carlsson5e300d12009-06-12 16:51:40 +0000222 Param->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000223
Anders Carlsson5e300d12009-06-12 16:51:40 +0000224 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000225}
226
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000227/// CheckExtraCXXDefaultArguments - Check for any extra default
228/// arguments in the declarator, which is not a function declaration
229/// or definition and therefore is not permitted to have default
230/// arguments. This routine should be invoked for every declarator
231/// that is not a function declaration or definition.
232void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
233 // C++ [dcl.fct.default]p3
234 // A default argument expression shall be specified only in the
235 // parameter-declaration-clause of a function declaration or in a
236 // template-parameter (14.1). It shall not be specified for a
237 // parameter pack. If it is specified in a
238 // parameter-declaration-clause, it shall not occur within a
239 // declarator or abstract-declarator of a parameter-declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000240 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000241 DeclaratorChunk &chunk = D.getTypeObject(i);
242 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000243 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
244 ParmVarDecl *Param =
John McCalld226f652010-08-21 09:40:31 +0000245 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000246 if (Param->hasUnparsedDefaultArg()) {
247 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000248 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
249 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
250 delete Toks;
251 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor61366e92008-12-24 00:01:03 +0000252 } else if (Param->getDefaultArg()) {
253 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
254 << Param->getDefaultArg()->getSourceRange();
255 Param->setDefaultArg(0);
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000256 }
257 }
258 }
259 }
260}
261
Chris Lattner3d1cee32008-04-08 05:04:30 +0000262// MergeCXXFunctionDecl - Merge two declarations of the same C++
263// function, once we already know that they have the same
Douglas Gregorcda9c672009-02-16 17:45:42 +0000264// type. Subroutine of MergeFunctionDecl. Returns true if there was an
265// error, false otherwise.
266bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
267 bool Invalid = false;
268
Chris Lattner3d1cee32008-04-08 05:04:30 +0000269 // C++ [dcl.fct.default]p4:
Chris Lattner3d1cee32008-04-08 05:04:30 +0000270 // For non-template functions, default arguments can be added in
271 // later declarations of a function in the same
272 // scope. Declarations in different scopes have completely
273 // distinct sets of default arguments. That is, declarations in
274 // inner scopes do not acquire default arguments from
275 // declarations in outer scopes, and vice versa. In a given
276 // function declaration, all parameters subsequent to a
277 // parameter with a default argument shall have default
278 // arguments supplied in this or previous declarations. A
279 // default argument shall not be redefined by a later
280 // declaration (not even to the same value).
Douglas Gregor6cc15182009-09-11 18:44:32 +0000281 //
282 // C++ [dcl.fct.default]p6:
283 // Except for member functions of class templates, the default arguments
284 // in a member function definition that appears outside of the class
285 // definition are added to the set of default arguments provided by the
286 // member function declaration in the class definition.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000287 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
288 ParmVarDecl *OldParam = Old->getParamDecl(p);
289 ParmVarDecl *NewParam = New->getParamDecl(p);
290
Douglas Gregor6cc15182009-09-11 18:44:32 +0000291 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000292
Francois Pichet8d051e02011-04-10 03:03:52 +0000293 unsigned DiagDefaultParamID =
294 diag::err_param_default_argument_redefinition;
295
296 // MSVC accepts that default parameters be redefined for member functions
297 // of template class. The new default parameter's value is ignored.
298 Invalid = true;
299 if (getLangOptions().Microsoft) {
300 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
301 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000302 // Merge the old default argument into the new parameter.
303 NewParam->setHasInheritedDefaultArg();
304 if (OldParam->hasUninstantiatedDefaultArg())
305 NewParam->setUninstantiatedDefaultArg(
306 OldParam->getUninstantiatedDefaultArg());
307 else
308 NewParam->setDefaultArg(OldParam->getInit());
Francois Pichetcf320c62011-04-22 08:25:24 +0000309 DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
Francois Pichet8d051e02011-04-10 03:03:52 +0000310 Invalid = false;
311 }
312 }
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000313
Francois Pichet8cf90492011-04-10 04:58:30 +0000314 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
315 // hint here. Alternatively, we could walk the type-source information
316 // for NewParam to find the last source location in the type... but it
317 // isn't worth the effort right now. This is the kind of test case that
318 // is hard to get right:
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000319 // int f(int);
320 // void g(int (*fp)(int) = f);
321 // void g(int (*fp)(int) = &f);
Francois Pichet8d051e02011-04-10 03:03:52 +0000322 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000323 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000324
325 // Look for the function declaration where the default argument was
326 // actually written, which may be a declaration prior to Old.
327 for (FunctionDecl *Older = Old->getPreviousDeclaration();
328 Older; Older = Older->getPreviousDeclaration()) {
329 if (!Older->getParamDecl(p)->hasDefaultArg())
330 break;
331
332 OldParam = Older->getParamDecl(p);
333 }
334
335 Diag(OldParam->getLocation(), diag::note_previous_definition)
336 << OldParam->getDefaultArgRange();
Douglas Gregord85cef52009-09-17 19:51:30 +0000337 } else if (OldParam->hasDefaultArg()) {
John McCall3d6c1782010-05-04 01:53:42 +0000338 // Merge the old default argument into the new parameter.
339 // It's important to use getInit() here; getDefaultArg()
John McCall4765fa02010-12-06 08:20:24 +0000340 // strips off any top-level ExprWithCleanups.
John McCallbf73b352010-03-12 18:31:32 +0000341 NewParam->setHasInheritedDefaultArg();
Douglas Gregord85cef52009-09-17 19:51:30 +0000342 if (OldParam->hasUninstantiatedDefaultArg())
343 NewParam->setUninstantiatedDefaultArg(
344 OldParam->getUninstantiatedDefaultArg());
345 else
John McCall3d6c1782010-05-04 01:53:42 +0000346 NewParam->setDefaultArg(OldParam->getInit());
Douglas Gregor6cc15182009-09-11 18:44:32 +0000347 } else if (NewParam->hasDefaultArg()) {
348 if (New->getDescribedFunctionTemplate()) {
349 // Paragraph 4, quoted above, only applies to non-template functions.
350 Diag(NewParam->getLocation(),
351 diag::err_param_default_argument_template_redecl)
352 << NewParam->getDefaultArgRange();
353 Diag(Old->getLocation(), diag::note_template_prev_declaration)
354 << false;
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000355 } else if (New->getTemplateSpecializationKind()
356 != TSK_ImplicitInstantiation &&
357 New->getTemplateSpecializationKind() != TSK_Undeclared) {
358 // C++ [temp.expr.spec]p21:
359 // Default function arguments shall not be specified in a declaration
360 // or a definition for one of the following explicit specializations:
361 // - the explicit specialization of a function template;
Douglas Gregor8c638ab2009-10-13 23:52:38 +0000362 // - the explicit specialization of a member function template;
363 // - the explicit specialization of a member function of a class
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000364 // template where the class template specialization to which the
365 // member function specialization belongs is implicitly
366 // instantiated.
367 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
368 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
369 << New->getDeclName()
370 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000371 } else if (New->getDeclContext()->isDependentContext()) {
372 // C++ [dcl.fct.default]p6 (DR217):
373 // Default arguments for a member function of a class template shall
374 // be specified on the initial declaration of the member function
375 // within the class template.
376 //
377 // Reading the tea leaves a bit in DR217 and its reference to DR205
378 // leads me to the conclusion that one cannot add default function
379 // arguments for an out-of-line definition of a member function of a
380 // dependent type.
381 int WhichKind = 2;
382 if (CXXRecordDecl *Record
383 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
384 if (Record->getDescribedClassTemplate())
385 WhichKind = 0;
386 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
387 WhichKind = 1;
388 else
389 WhichKind = 2;
390 }
391
392 Diag(NewParam->getLocation(),
393 diag::err_param_default_argument_member_template_redecl)
394 << WhichKind
395 << NewParam->getDefaultArgRange();
396 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000397 }
398 }
399
Douglas Gregore13ad832010-02-12 07:32:17 +0000400 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000401 Invalid = true;
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000402
Douglas Gregorcda9c672009-02-16 17:45:42 +0000403 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000404}
405
Sebastian Redl60618fa2011-03-12 11:50:43 +0000406/// \brief Merge the exception specifications of two variable declarations.
407///
408/// This is called when there's a redeclaration of a VarDecl. The function
409/// checks if the redeclaration might have an exception specification and
410/// validates compatibility and merges the specs if necessary.
411void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
412 // Shortcut if exceptions are disabled.
413 if (!getLangOptions().CXXExceptions)
414 return;
415
416 assert(Context.hasSameType(New->getType(), Old->getType()) &&
417 "Should only be called if types are otherwise the same.");
418
419 QualType NewType = New->getType();
420 QualType OldType = Old->getType();
421
422 // We're only interested in pointers and references to functions, as well
423 // as pointers to member functions.
424 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
425 NewType = R->getPointeeType();
426 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
427 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
428 NewType = P->getPointeeType();
429 OldType = OldType->getAs<PointerType>()->getPointeeType();
430 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
431 NewType = M->getPointeeType();
432 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
433 }
434
435 if (!NewType->isFunctionProtoType())
436 return;
437
438 // There's lots of special cases for functions. For function pointers, system
439 // libraries are hopefully not as broken so that we don't need these
440 // workarounds.
441 if (CheckEquivalentExceptionSpec(
442 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
443 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
444 New->setInvalidDecl();
445 }
446}
447
Chris Lattner3d1cee32008-04-08 05:04:30 +0000448/// CheckCXXDefaultArguments - Verify that the default arguments for a
449/// function declaration are well-formed according to C++
450/// [dcl.fct.default].
451void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
452 unsigned NumParams = FD->getNumParams();
453 unsigned p;
454
455 // Find first parameter with a default argument
456 for (p = 0; p < NumParams; ++p) {
457 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000458 if (Param->hasDefaultArg())
Chris Lattner3d1cee32008-04-08 05:04:30 +0000459 break;
460 }
461
462 // C++ [dcl.fct.default]p4:
463 // In a given function declaration, all parameters
464 // subsequent to a parameter with a default argument shall
465 // have default arguments supplied in this or previous
466 // declarations. A default argument shall not be redefined
467 // by a later declaration (not even to the same value).
468 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000469 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000470 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000471 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000472 if (Param->isInvalidDecl())
473 /* We already complained about this parameter. */;
474 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000475 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000476 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000477 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000478 else
Mike Stump1eb44332009-09-09 15:08:12 +0000479 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000480 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000481
Chris Lattner3d1cee32008-04-08 05:04:30 +0000482 LastMissingDefaultArg = p;
483 }
484 }
485
486 if (LastMissingDefaultArg > 0) {
487 // Some default arguments were missing. Clear out all of the
488 // default arguments up to (and including) the last missing
489 // default argument, so that we leave the function parameters
490 // in a semantically valid state.
491 for (p = 0; p <= LastMissingDefaultArg; ++p) {
492 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000493 if (Param->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000494 Param->setDefaultArg(0);
495 }
496 }
497 }
498}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000499
Douglas Gregorb48fe382008-10-31 09:07:45 +0000500/// isCurrentClassName - Determine whether the identifier II is the
501/// name of the class type currently being defined. In the case of
502/// nested classes, this will only return true if II is the name of
503/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000504bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
505 const CXXScopeSpec *SS) {
Douglas Gregorb862b8f2010-01-11 23:29:10 +0000506 assert(getLangOptions().CPlusPlus && "No class names in C!");
507
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000508 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +0000509 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +0000510 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000511 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
512 } else
513 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
514
Douglas Gregor6f7a17b2010-02-05 06:12:42 +0000515 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregorb48fe382008-10-31 09:07:45 +0000516 return &II == CurDecl->getIdentifier();
517 else
518 return false;
519}
520
Mike Stump1eb44332009-09-09 15:08:12 +0000521/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000522///
523/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
524/// and returns NULL otherwise.
525CXXBaseSpecifier *
526Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
527 SourceRange SpecifierRange,
528 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000529 TypeSourceInfo *TInfo,
530 SourceLocation EllipsisLoc) {
Nick Lewycky56062202010-07-26 16:56:01 +0000531 QualType BaseType = TInfo->getType();
532
Douglas Gregor2943aed2009-03-03 04:44:36 +0000533 // C++ [class.union]p1:
534 // A union shall not have base classes.
535 if (Class->isUnion()) {
536 Diag(Class->getLocation(), diag::err_base_clause_on_union)
537 << SpecifierRange;
538 return 0;
539 }
540
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000541 if (EllipsisLoc.isValid() &&
542 !TInfo->getType()->containsUnexpandedParameterPack()) {
543 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
544 << TInfo->getTypeLoc().getSourceRange();
545 EllipsisLoc = SourceLocation();
546 }
547
Douglas Gregor2943aed2009-03-03 04:44:36 +0000548 if (BaseType->isDependentType())
Mike Stump1eb44332009-09-09 15:08:12 +0000549 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +0000550 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000551 Access, TInfo, EllipsisLoc);
Nick Lewycky56062202010-07-26 16:56:01 +0000552
553 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000554
555 // Base specifiers must be record types.
556 if (!BaseType->isRecordType()) {
557 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
558 return 0;
559 }
560
561 // C++ [class.union]p1:
562 // A union shall not be used as a base class.
563 if (BaseType->isUnionType()) {
564 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
565 return 0;
566 }
567
568 // C++ [class.derived]p2:
569 // The class-name in a base-specifier shall not be an incompletely
570 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +0000571 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000572 PDiag(diag::err_incomplete_base_class)
John McCall572fc622010-08-17 07:23:57 +0000573 << SpecifierRange)) {
574 Class->setInvalidDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000575 return 0;
John McCall572fc622010-08-17 07:23:57 +0000576 }
Douglas Gregor2943aed2009-03-03 04:44:36 +0000577
Eli Friedman1d954f62009-08-15 21:55:26 +0000578 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +0000579 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000580 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor952b0172010-02-11 01:04:33 +0000581 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000582 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedman1d954f62009-08-15 21:55:26 +0000583 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
584 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +0000585
Anders Carlsson1d209272011-03-25 14:55:14 +0000586 // C++ [class]p3:
587 // If a class is marked final and it appears as a base-type-specifier in
588 // base-clause, the program is ill-formed.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +0000589 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
Anders Carlssondfc2f102011-01-22 17:51:53 +0000590 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
591 << CXXBaseDecl->getDeclName();
592 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
593 << CXXBaseDecl->getDeclName();
594 return 0;
595 }
596
John McCall572fc622010-08-17 07:23:57 +0000597 if (BaseDecl->isInvalidDecl())
598 Class->setInvalidDecl();
Anders Carlsson51f94042009-12-03 17:49:57 +0000599
600 // Create the base specifier.
Anders Carlsson51f94042009-12-03 17:49:57 +0000601 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +0000602 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000603 Access, TInfo, EllipsisLoc);
Anders Carlsson51f94042009-12-03 17:49:57 +0000604}
605
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000606/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
607/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +0000608/// example:
609/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000610/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallf312b1e2010-08-26 23:41:50 +0000611BaseResult
John McCalld226f652010-08-21 09:40:31 +0000612Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000613 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000614 ParsedType basetype, SourceLocation BaseLoc,
615 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000616 if (!classdecl)
617 return true;
618
Douglas Gregor40808ce2009-03-09 23:48:35 +0000619 AdjustDeclIfTemplate(classdecl);
John McCalld226f652010-08-21 09:40:31 +0000620 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregor5fe8c042010-02-27 00:25:28 +0000621 if (!Class)
622 return true;
623
Nick Lewycky56062202010-07-26 16:56:01 +0000624 TypeSourceInfo *TInfo = 0;
625 GetTypeFromParser(basetype, &TInfo);
Douglas Gregord0937222010-12-13 22:49:22 +0000626
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000627 if (EllipsisLoc.isInvalid() &&
628 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregord0937222010-12-13 22:49:22 +0000629 UPPC_BaseType))
630 return true;
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000631
Douglas Gregor2943aed2009-03-03 04:44:36 +0000632 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000633 Virtual, Access, TInfo,
634 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +0000635 return BaseSpec;
Mike Stump1eb44332009-09-09 15:08:12 +0000636
Douglas Gregor2943aed2009-03-03 04:44:36 +0000637 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000638}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000639
Douglas Gregor2943aed2009-03-03 04:44:36 +0000640/// \brief Performs the actual work of attaching the given base class
641/// specifiers to a C++ class.
642bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
643 unsigned NumBases) {
644 if (NumBases == 0)
645 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000646
647 // Used to keep track of which base types we have already seen, so
648 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +0000649 // that the key is always the unqualified canonical type of the base
650 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000651 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
652
653 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +0000654 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +0000655 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +0000656 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +0000657 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +0000658 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +0000659 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Fariborz Jahanian0ed5c5d2010-05-20 23:34:56 +0000660 if (!Class->hasObjectMember()) {
661 if (const RecordType *FDTTy =
662 NewBaseType.getTypePtr()->getAs<RecordType>())
663 if (FDTTy->getDecl()->hasObjectMember())
664 Class->setHasObjectMember(true);
665 }
666
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000667 if (KnownBaseTypes[NewBaseType]) {
668 // C++ [class.mi]p3:
669 // A class shall not be specified as a direct base class of a
670 // derived class more than once.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000671 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000672 diag::err_duplicate_base_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000673 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +0000674 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +0000675
676 // Delete the duplicate base class specifier; we're going to
677 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000678 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000679
680 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000681 } else {
682 // Okay, add this new base class.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000683 KnownBaseTypes[NewBaseType] = Bases[idx];
684 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000685 }
686 }
687
688 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +0000689 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +0000690
691 // Delete the remaining (good) base class specifiers, since their
692 // data has been copied into the CXXRecordDecl.
693 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000694 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000695
696 return Invalid;
697}
698
699/// ActOnBaseSpecifiers - Attach the given base specifiers to the
700/// class, after checking whether there are any duplicate base
701/// classes.
John McCalld226f652010-08-21 09:40:31 +0000702void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, BaseTy **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000703 unsigned NumBases) {
704 if (!ClassDecl || !Bases || !NumBases)
705 return;
706
707 AdjustDeclIfTemplate(ClassDecl);
John McCalld226f652010-08-21 09:40:31 +0000708 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor2943aed2009-03-03 04:44:36 +0000709 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000710}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000711
John McCall3cb0ebd2010-03-10 03:28:59 +0000712static CXXRecordDecl *GetClassForType(QualType T) {
713 if (const RecordType *RT = T->getAs<RecordType>())
714 return cast<CXXRecordDecl>(RT->getDecl());
715 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
716 return ICT->getDecl();
717 else
718 return 0;
719}
720
Douglas Gregora8f32e02009-10-06 17:59:45 +0000721/// \brief Determine whether the type \p Derived is a C++ class that is
722/// derived from the type \p Base.
723bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
724 if (!getLangOptions().CPlusPlus)
725 return false;
John McCall3cb0ebd2010-03-10 03:28:59 +0000726
727 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
728 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000729 return false;
730
John McCall3cb0ebd2010-03-10 03:28:59 +0000731 CXXRecordDecl *BaseRD = GetClassForType(Base);
732 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000733 return false;
734
John McCall86ff3082010-02-04 22:26:26 +0000735 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
736 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +0000737}
738
739/// \brief Determine whether the type \p Derived is a C++ class that is
740/// derived from the type \p Base.
741bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
742 if (!getLangOptions().CPlusPlus)
743 return false;
744
John McCall3cb0ebd2010-03-10 03:28:59 +0000745 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
746 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000747 return false;
748
John McCall3cb0ebd2010-03-10 03:28:59 +0000749 CXXRecordDecl *BaseRD = GetClassForType(Base);
750 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000751 return false;
752
Douglas Gregora8f32e02009-10-06 17:59:45 +0000753 return DerivedRD->isDerivedFrom(BaseRD, Paths);
754}
755
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000756void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallf871d0c2010-08-07 06:22:56 +0000757 CXXCastPath &BasePathArray) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000758 assert(BasePathArray.empty() && "Base path array must be empty!");
759 assert(Paths.isRecordingPaths() && "Must record paths!");
760
761 const CXXBasePath &Path = Paths.front();
762
763 // We first go backward and check if we have a virtual base.
764 // FIXME: It would be better if CXXBasePath had the base specifier for
765 // the nearest virtual base.
766 unsigned Start = 0;
767 for (unsigned I = Path.size(); I != 0; --I) {
768 if (Path[I - 1].Base->isVirtual()) {
769 Start = I - 1;
770 break;
771 }
772 }
773
774 // Now add all bases.
775 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallf871d0c2010-08-07 06:22:56 +0000776 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000777}
778
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000779/// \brief Determine whether the given base path includes a virtual
780/// base class.
John McCallf871d0c2010-08-07 06:22:56 +0000781bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
782 for (CXXCastPath::const_iterator B = BasePath.begin(),
783 BEnd = BasePath.end();
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000784 B != BEnd; ++B)
785 if ((*B)->isVirtual())
786 return true;
787
788 return false;
789}
790
Douglas Gregora8f32e02009-10-06 17:59:45 +0000791/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
792/// conversion (where Derived and Base are class types) is
793/// well-formed, meaning that the conversion is unambiguous (and
794/// that all of the base classes are accessible). Returns true
795/// and emits a diagnostic if the code is ill-formed, returns false
796/// otherwise. Loc is the location where this routine should point to
797/// if there is an error, and Range is the source range to highlight
798/// if there is an error.
799bool
800Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall58e6f342010-03-16 05:22:47 +0000801 unsigned InaccessibleBaseID,
Douglas Gregora8f32e02009-10-06 17:59:45 +0000802 unsigned AmbigiousBaseConvID,
803 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +0000804 DeclarationName Name,
John McCallf871d0c2010-08-07 06:22:56 +0000805 CXXCastPath *BasePath) {
Douglas Gregora8f32e02009-10-06 17:59:45 +0000806 // First, determine whether the path from Derived to Base is
807 // ambiguous. This is slightly more expensive than checking whether
808 // the Derived to Base conversion exists, because here we need to
809 // explore multiple paths to determine if there is an ambiguity.
810 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
811 /*DetectVirtual=*/false);
812 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
813 assert(DerivationOkay &&
814 "Can only be used with a derived-to-base conversion");
815 (void)DerivationOkay;
816
817 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000818 if (InaccessibleBaseID) {
819 // Check that the base class can be accessed.
820 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
821 InaccessibleBaseID)) {
822 case AR_inaccessible:
823 return true;
824 case AR_accessible:
825 case AR_dependent:
826 case AR_delayed:
827 break;
Anders Carlssone25a96c2010-04-24 17:11:09 +0000828 }
John McCall6b2accb2010-02-10 09:31:12 +0000829 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000830
831 // Build a base path if necessary.
832 if (BasePath)
833 BuildBasePathArray(Paths, *BasePath);
834 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +0000835 }
836
837 // We know that the derived-to-base conversion is ambiguous, and
838 // we're going to produce a diagnostic. Perform the derived-to-base
839 // search just one more time to compute all of the possible paths so
840 // that we can print them out. This is more expensive than any of
841 // the previous derived-to-base checks we've done, but at this point
842 // performance isn't as much of an issue.
843 Paths.clear();
844 Paths.setRecordingPaths(true);
845 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
846 assert(StillOkay && "Can only be used with a derived-to-base conversion");
847 (void)StillOkay;
848
849 // Build up a textual representation of the ambiguous paths, e.g.,
850 // D -> B -> A, that will be used to illustrate the ambiguous
851 // conversions in the diagnostic. We only print one of the paths
852 // to each base class subobject.
853 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
854
855 Diag(Loc, AmbigiousBaseConvID)
856 << Derived << Base << PathDisplayStr << Range << Name;
857 return true;
858}
859
860bool
861Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000862 SourceLocation Loc, SourceRange Range,
John McCallf871d0c2010-08-07 06:22:56 +0000863 CXXCastPath *BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000864 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +0000865 return CheckDerivedToBaseConversion(Derived, Base,
John McCall58e6f342010-03-16 05:22:47 +0000866 IgnoreAccess ? 0
867 : diag::err_upcast_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +0000868 diag::err_ambiguous_derived_to_base_conv,
Anders Carlssone25a96c2010-04-24 17:11:09 +0000869 Loc, Range, DeclarationName(),
870 BasePath);
Douglas Gregora8f32e02009-10-06 17:59:45 +0000871}
872
873
874/// @brief Builds a string representing ambiguous paths from a
875/// specific derived class to different subobjects of the same base
876/// class.
877///
878/// This function builds a string that can be used in error messages
879/// to show the different paths that one can take through the
880/// inheritance hierarchy to go from the derived class to different
881/// subobjects of a base class. The result looks something like this:
882/// @code
883/// struct D -> struct B -> struct A
884/// struct D -> struct C -> struct A
885/// @endcode
886std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
887 std::string PathDisplayStr;
888 std::set<unsigned> DisplayedPaths;
889 for (CXXBasePaths::paths_iterator Path = Paths.begin();
890 Path != Paths.end(); ++Path) {
891 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
892 // We haven't displayed a path to this particular base
893 // class subobject yet.
894 PathDisplayStr += "\n ";
895 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
896 for (CXXBasePath::const_iterator Element = Path->begin();
897 Element != Path->end(); ++Element)
898 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
899 }
900 }
901
902 return PathDisplayStr;
903}
904
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000905//===----------------------------------------------------------------------===//
906// C++ class member Handling
907//===----------------------------------------------------------------------===//
908
Abramo Bagnara6206d532010-06-05 05:09:32 +0000909/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
John McCalld226f652010-08-21 09:40:31 +0000910Decl *Sema::ActOnAccessSpecifier(AccessSpecifier Access,
911 SourceLocation ASLoc,
912 SourceLocation ColonLoc) {
Abramo Bagnara6206d532010-06-05 05:09:32 +0000913 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCalld226f652010-08-21 09:40:31 +0000914 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnara6206d532010-06-05 05:09:32 +0000915 ASLoc, ColonLoc);
916 CurContext->addHiddenDecl(ASDecl);
John McCalld226f652010-08-21 09:40:31 +0000917 return ASDecl;
Abramo Bagnara6206d532010-06-05 05:09:32 +0000918}
919
Anders Carlsson9e682d92011-01-20 05:57:14 +0000920/// CheckOverrideControl - Check C++0x override control semantics.
Anders Carlsson4ebf1602011-01-20 06:29:02 +0000921void Sema::CheckOverrideControl(const Decl *D) {
Anders Carlsson9e682d92011-01-20 05:57:14 +0000922 const CXXMethodDecl *MD = llvm::dyn_cast<CXXMethodDecl>(D);
923 if (!MD || !MD->isVirtual())
924 return;
925
Anders Carlsson3ffe1832011-01-20 06:33:26 +0000926 if (MD->isDependentContext())
927 return;
928
Anders Carlsson9e682d92011-01-20 05:57:14 +0000929 // C++0x [class.virtual]p3:
930 // If a virtual function is marked with the virt-specifier override and does
931 // not override a member function of a base class,
932 // the program is ill-formed.
933 bool HasOverriddenMethods =
934 MD->begin_overridden_methods() != MD->end_overridden_methods();
Anders Carlssoncb88a1f2011-01-24 16:26:15 +0000935 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) {
Anders Carlsson4ebf1602011-01-20 06:29:02 +0000936 Diag(MD->getLocation(),
Anders Carlsson9e682d92011-01-20 05:57:14 +0000937 diag::err_function_marked_override_not_overriding)
938 << MD->getDeclName();
939 return;
940 }
941}
942
Anders Carlsson2e1c7302011-01-20 16:25:36 +0000943/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
944/// function overrides a virtual member function marked 'final', according to
945/// C++0x [class.virtual]p3.
946bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
947 const CXXMethodDecl *Old) {
Anders Carlssoncb88a1f2011-01-24 16:26:15 +0000948 if (!Old->hasAttr<FinalAttr>())
Anders Carlssonf89e0422011-01-23 21:07:30 +0000949 return false;
950
951 Diag(New->getLocation(), diag::err_final_function_overridden)
952 << New->getDeclName();
953 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
954 return true;
Anders Carlsson2e1c7302011-01-20 16:25:36 +0000955}
956
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000957/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
958/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
959/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnerb6688e02009-04-12 22:37:57 +0000960/// any.
John McCalld226f652010-08-21 09:40:31 +0000961Decl *
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000962Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +0000963 MultiTemplateParamsArg TemplateParameterLists,
Anders Carlsson69a87352011-01-20 03:57:25 +0000964 ExprTy *BW, const VirtSpecifiers &VS,
965 ExprTy *InitExpr, bool IsDefinition,
Sean Huntbb85f8e2011-05-06 21:24:28 +0000966 bool Deleted, SourceLocation DefaultLoc) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000967 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +0000968 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
969 DeclarationName Name = NameInfo.getName();
970 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor90ba6d52010-11-09 03:31:16 +0000971
972 // For anonymous bitfields, the location should point to the type.
973 if (Loc.isInvalid())
974 Loc = D.getSourceRange().getBegin();
975
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000976 Expr *BitWidth = static_cast<Expr*>(BW);
977 Expr *Init = static_cast<Expr*>(InitExpr);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000978
John McCall4bde1e12010-06-04 08:34:12 +0000979 assert(isa<CXXRecordDecl>(CurContext));
John McCall67d1a672009-08-06 02:15:43 +0000980 assert(!DS.isFriendSpecified());
981
John McCall4bde1e12010-06-04 08:34:12 +0000982 bool isFunc = false;
983 if (D.isFunctionDeclarator())
984 isFunc = true;
985 else if (D.getNumTypeObjects() == 0 &&
986 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename) {
John McCallb3d87482010-08-24 05:47:05 +0000987 QualType TDType = GetTypeFromParser(DS.getRepAsType());
John McCall4bde1e12010-06-04 08:34:12 +0000988 isFunc = TDType->isFunctionType();
989 }
990
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000991 // C++ 9.2p6: A member shall not be declared to have automatic storage
992 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000993 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
994 // data members and cannot be applied to names declared const or static,
995 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000996 switch (DS.getStorageClassSpec()) {
997 case DeclSpec::SCS_unspecified:
998 case DeclSpec::SCS_typedef:
999 case DeclSpec::SCS_static:
1000 // FALL THROUGH.
1001 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +00001002 case DeclSpec::SCS_mutable:
1003 if (isFunc) {
1004 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001005 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +00001006 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001007 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +00001008
Sebastian Redla11f42f2008-11-17 23:24:37 +00001009 // FIXME: It would be nicer if the keyword was ignored only for this
1010 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001011 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redl669d5d72008-11-14 23:42:31 +00001012 }
1013 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001014 default:
1015 if (DS.getStorageClassSpecLoc().isValid())
1016 Diag(DS.getStorageClassSpecLoc(),
1017 diag::err_storageclass_invalid_for_member);
1018 else
1019 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
1020 D.getMutableDeclSpec().ClearStorageClassSpecs();
1021 }
1022
Sebastian Redl669d5d72008-11-14 23:42:31 +00001023 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1024 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +00001025 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001026
1027 Decl *Member;
Chris Lattner24793662009-03-05 22:45:59 +00001028 if (isInstField) {
Douglas Gregor922fff22010-10-13 22:19:53 +00001029 CXXScopeSpec &SS = D.getCXXScopeSpec();
1030
Sean Huntbb85f8e2011-05-06 21:24:28 +00001031 if (DefaultLoc.isValid())
1032 Diag(DefaultLoc, diag::err_default_special_members);
Douglas Gregor922fff22010-10-13 22:19:53 +00001033
1034 if (SS.isSet() && !SS.isInvalid()) {
1035 // The user provided a superfluous scope specifier inside a class
1036 // definition:
1037 //
1038 // class X {
1039 // int X::member;
1040 // };
1041 DeclContext *DC = 0;
1042 if ((DC = computeDeclContext(SS, false)) && DC->Equals(CurContext))
1043 Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification)
1044 << Name << FixItHint::CreateRemoval(SS.getRange());
1045 else
1046 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1047 << Name << SS.getRange();
1048
1049 SS.clear();
1050 }
1051
Douglas Gregor37b372b2009-08-20 22:52:58 +00001052 // FIXME: Check for template parameters!
Douglas Gregor56c04582010-12-16 00:46:58 +00001053 // FIXME: Check that the name is an identifier!
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001054 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
1055 AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001056 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +00001057 } else {
Sean Huntfe2695e2011-05-06 01:42:00 +00001058 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition,
Sean Huntbb85f8e2011-05-06 21:24:28 +00001059 DefaultLoc);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001060 if (!Member) {
John McCalld226f652010-08-21 09:40:31 +00001061 return 0;
Chris Lattner6f8ce142009-03-05 23:03:49 +00001062 }
Chris Lattner8b963ef2009-03-05 23:01:03 +00001063
1064 // Non-instance-fields can't have a bitfield.
1065 if (BitWidth) {
1066 if (Member->isInvalidDecl()) {
1067 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00001068 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00001069 // C++ 9.6p3: A bit-field shall not be a static member.
1070 // "static member 'A' cannot be a bit-field"
1071 Diag(Loc, diag::err_static_not_bitfield)
1072 << Name << BitWidth->getSourceRange();
1073 } else if (isa<TypedefDecl>(Member)) {
1074 // "typedef member 'x' cannot be a bit-field"
1075 Diag(Loc, diag::err_typedef_not_bitfield)
1076 << Name << BitWidth->getSourceRange();
1077 } else {
1078 // A function typedef ("typedef int f(); f a;").
1079 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1080 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +00001081 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +00001082 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +00001083 }
Mike Stump1eb44332009-09-09 15:08:12 +00001084
Chris Lattner8b963ef2009-03-05 23:01:03 +00001085 BitWidth = 0;
1086 Member->setInvalidDecl();
1087 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001088
1089 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +00001090
Douglas Gregor37b372b2009-08-20 22:52:58 +00001091 // If we have declared a member function template, set the access of the
1092 // templated declaration as well.
1093 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1094 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +00001095 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001096
Anders Carlssonaae5af22011-01-20 04:34:22 +00001097 if (VS.isOverrideSpecified()) {
1098 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1099 if (!MD || !MD->isVirtual()) {
1100 Diag(Member->getLocStart(),
1101 diag::override_keyword_only_allowed_on_virtual_member_functions)
1102 << "override" << FixItHint::CreateRemoval(VS.getOverrideLoc());
Anders Carlsson9e682d92011-01-20 05:57:14 +00001103 } else
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001104 MD->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
Anders Carlssonaae5af22011-01-20 04:34:22 +00001105 }
1106 if (VS.isFinalSpecified()) {
1107 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1108 if (!MD || !MD->isVirtual()) {
1109 Diag(Member->getLocStart(),
1110 diag::override_keyword_only_allowed_on_virtual_member_functions)
1111 << "final" << FixItHint::CreateRemoval(VS.getFinalLoc());
Anders Carlsson9e682d92011-01-20 05:57:14 +00001112 } else
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001113 MD->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlssonaae5af22011-01-20 04:34:22 +00001114 }
Anders Carlsson9e682d92011-01-20 05:57:14 +00001115
Douglas Gregorf5251602011-03-08 17:10:18 +00001116 if (VS.getLastLocation().isValid()) {
1117 // Update the end location of a method that has a virt-specifiers.
1118 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1119 MD->setRangeEnd(VS.getLastLocation());
1120 }
1121
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001122 CheckOverrideControl(Member);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001123
Douglas Gregor10bd3682008-11-17 22:58:34 +00001124 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001125
Douglas Gregor021c3b32009-03-11 23:00:04 +00001126 if (Init)
Richard Smith34b41d92011-02-20 03:19:35 +00001127 AddInitializerToDecl(Member, Init, false,
1128 DS.getTypeSpecType() == DeclSpec::TST_auto);
Sebastian Redle2b68332009-04-12 17:16:29 +00001129 if (Deleted) // FIXME: Source location is not very good.
John McCalld226f652010-08-21 09:40:31 +00001130 SetDeclDeleted(Member, D.getSourceRange().getBegin());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001131
Richard Smith483b9f32011-02-21 20:05:19 +00001132 FinalizeDeclaration(Member);
1133
John McCallb25b2952011-02-15 07:12:36 +00001134 if (isInstField)
Douglas Gregor44b43212008-12-11 16:49:14 +00001135 FieldCollector->Add(cast<FieldDecl>(Member));
John McCalld226f652010-08-21 09:40:31 +00001136 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001137}
1138
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001139/// \brief Find the direct and/or virtual base specifiers that
1140/// correspond to the given base type, for use in base initialization
1141/// within a constructor.
1142static bool FindBaseInitializer(Sema &SemaRef,
1143 CXXRecordDecl *ClassDecl,
1144 QualType BaseType,
1145 const CXXBaseSpecifier *&DirectBaseSpec,
1146 const CXXBaseSpecifier *&VirtualBaseSpec) {
1147 // First, check for a direct base class.
1148 DirectBaseSpec = 0;
1149 for (CXXRecordDecl::base_class_const_iterator Base
1150 = ClassDecl->bases_begin();
1151 Base != ClassDecl->bases_end(); ++Base) {
1152 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1153 // We found a direct base of this type. That's what we're
1154 // initializing.
1155 DirectBaseSpec = &*Base;
1156 break;
1157 }
1158 }
1159
1160 // Check for a virtual base class.
1161 // FIXME: We might be able to short-circuit this if we know in advance that
1162 // there are no virtual bases.
1163 VirtualBaseSpec = 0;
1164 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1165 // We haven't found a base yet; search the class hierarchy for a
1166 // virtual base class.
1167 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1168 /*DetectVirtual=*/false);
1169 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1170 BaseType, Paths)) {
1171 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1172 Path != Paths.end(); ++Path) {
1173 if (Path->back().Base->isVirtual()) {
1174 VirtualBaseSpec = Path->back().Base;
1175 break;
1176 }
1177 }
1178 }
1179 }
1180
1181 return DirectBaseSpec || VirtualBaseSpec;
1182}
1183
Douglas Gregor7ad83902008-11-05 04:29:56 +00001184/// ActOnMemInitializer - Handle a C++ member initializer.
John McCallf312b1e2010-08-26 23:41:50 +00001185MemInitResult
John McCalld226f652010-08-21 09:40:31 +00001186Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001187 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001188 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001189 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00001190 ParsedType TemplateTypeTy,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001191 SourceLocation IdLoc,
1192 SourceLocation LParenLoc,
1193 ExprTy **Args, unsigned NumArgs,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001194 SourceLocation RParenLoc,
1195 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001196 if (!ConstructorD)
1197 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001198
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001199 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00001200
1201 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00001202 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001203 if (!Constructor) {
1204 // The user wrote a constructor initializer on a function that is
1205 // not a C++ constructor. Ignore the error for now, because we may
1206 // have more member initializers coming; we'll diagnose it just
1207 // once in ActOnMemInitializers.
1208 return true;
1209 }
1210
1211 CXXRecordDecl *ClassDecl = Constructor->getParent();
1212
1213 // C++ [class.base.init]p2:
1214 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky7663f392010-11-20 01:29:55 +00001215 // constructor's class and, if not found in that scope, are looked
1216 // up in the scope containing the constructor's definition.
1217 // [Note: if the constructor's class contains a member with the
1218 // same name as a direct or virtual base class of the class, a
1219 // mem-initializer-id naming the member or base class and composed
1220 // of a single identifier refers to the class member. A
Douglas Gregor7ad83902008-11-05 04:29:56 +00001221 // mem-initializer-id for the hidden base class may be specified
1222 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00001223 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001224 // Look for a member, first.
1225 FieldDecl *Member = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001226 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001227 = ClassDecl->lookup(MemberOrBase);
Francois Pichet87c2e122010-11-21 06:08:52 +00001228 if (Result.first != Result.second) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001229 Member = dyn_cast<FieldDecl>(*Result.first);
Francois Pichet87c2e122010-11-21 06:08:52 +00001230
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001231 if (Member) {
1232 if (EllipsisLoc.isValid())
1233 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1234 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1235
Francois Pichet00eb3f92010-12-04 09:14:42 +00001236 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
Douglas Gregor802ab452009-12-02 22:36:29 +00001237 LParenLoc, RParenLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001238 }
1239
Francois Pichet00eb3f92010-12-04 09:14:42 +00001240 // Handle anonymous union case.
1241 if (IndirectFieldDecl* IndirectField
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001242 = dyn_cast<IndirectFieldDecl>(*Result.first)) {
1243 if (EllipsisLoc.isValid())
1244 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1245 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1246
Francois Pichet00eb3f92010-12-04 09:14:42 +00001247 return BuildMemberInitializer(IndirectField, (Expr**)Args,
1248 NumArgs, IdLoc,
1249 LParenLoc, RParenLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001250 }
Francois Pichet00eb3f92010-12-04 09:14:42 +00001251 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001252 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001253 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00001254 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00001255 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00001256
1257 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00001258 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
John McCall2b194412009-12-21 10:41:20 +00001259 } else {
1260 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1261 LookupParsedName(R, S, &SS);
1262
1263 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1264 if (!TyD) {
1265 if (R.isAmbiguous()) return true;
1266
John McCallfd225442010-04-09 19:01:14 +00001267 // We don't want access-control diagnostics here.
1268 R.suppressDiagnostics();
1269
Douglas Gregor7a886e12010-01-19 06:46:48 +00001270 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1271 bool NotUnknownSpecialization = false;
1272 DeclContext *DC = computeDeclContext(SS, false);
1273 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1274 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1275
1276 if (!NotUnknownSpecialization) {
1277 // When the scope specifier can refer to a member of an unknown
1278 // specialization, we take it as a type name.
Douglas Gregore29425b2011-02-28 22:42:13 +00001279 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
1280 SS.getWithLocInContext(Context),
1281 *MemberOrBase, IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00001282 if (BaseType.isNull())
1283 return true;
1284
Douglas Gregor7a886e12010-01-19 06:46:48 +00001285 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00001286 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001287 }
1288 }
1289
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001290 // If no results were found, try to correct typos.
Douglas Gregor7a886e12010-01-19 06:46:48 +00001291 if (R.empty() && BaseType.isNull() &&
Douglas Gregoraaf87162010-04-14 20:04:41 +00001292 CorrectTypo(R, S, &SS, ClassDecl, 0, CTC_NoKeywords) &&
1293 R.isSingleResult()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001294 if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00001295 if (Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl)) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001296 // We have found a non-static data member with a similar
1297 // name to what was typed; complain and initialize that
1298 // member.
1299 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1300 << MemberOrBase << true << R.getLookupName()
Douglas Gregor849b2432010-03-31 17:46:05 +00001301 << FixItHint::CreateReplacement(R.getNameLoc(),
1302 R.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +00001303 Diag(Member->getLocation(), diag::note_previous_decl)
1304 << Member->getDeclName();
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001305
1306 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1307 LParenLoc, RParenLoc);
1308 }
1309 } else if (TypeDecl *Type = R.getAsSingle<TypeDecl>()) {
1310 const CXXBaseSpecifier *DirectBaseSpec;
1311 const CXXBaseSpecifier *VirtualBaseSpec;
1312 if (FindBaseInitializer(*this, ClassDecl,
1313 Context.getTypeDeclType(Type),
1314 DirectBaseSpec, VirtualBaseSpec)) {
1315 // We have found a direct or virtual base class with a
1316 // similar name to what was typed; complain and initialize
1317 // that base class.
1318 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1319 << MemberOrBase << false << R.getLookupName()
Douglas Gregor849b2432010-03-31 17:46:05 +00001320 << FixItHint::CreateReplacement(R.getNameLoc(),
1321 R.getLookupName().getAsString());
Douglas Gregor0d535c82010-01-07 00:26:25 +00001322
1323 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1324 : VirtualBaseSpec;
1325 Diag(BaseSpec->getSourceRange().getBegin(),
1326 diag::note_base_class_specified_here)
1327 << BaseSpec->getType()
1328 << BaseSpec->getSourceRange();
1329
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001330 TyD = Type;
1331 }
1332 }
1333 }
1334
Douglas Gregor7a886e12010-01-19 06:46:48 +00001335 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001336 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1337 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1338 return true;
1339 }
John McCall2b194412009-12-21 10:41:20 +00001340 }
1341
Douglas Gregor7a886e12010-01-19 06:46:48 +00001342 if (BaseType.isNull()) {
1343 BaseType = Context.getTypeDeclType(TyD);
1344 if (SS.isSet()) {
1345 NestedNameSpecifier *Qualifier =
1346 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00001347
Douglas Gregor7a886e12010-01-19 06:46:48 +00001348 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001349 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001350 }
John McCall2b194412009-12-21 10:41:20 +00001351 }
1352 }
Mike Stump1eb44332009-09-09 15:08:12 +00001353
John McCalla93c9342009-12-07 02:54:59 +00001354 if (!TInfo)
1355 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001356
John McCalla93c9342009-12-07 02:54:59 +00001357 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001358 LParenLoc, RParenLoc, ClassDecl, EllipsisLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00001359}
1360
John McCallb4190042009-11-04 23:02:40 +00001361/// Checks an initializer expression for use of uninitialized fields, such as
1362/// containing the field that is being initialized. Returns true if there is an
1363/// uninitialized field was used an updates the SourceLocation parameter; false
1364/// otherwise.
Nick Lewycky43ad1822010-06-15 07:32:55 +00001365static bool InitExprContainsUninitializedFields(const Stmt *S,
Francois Pichet00eb3f92010-12-04 09:14:42 +00001366 const ValueDecl *LhsField,
Nick Lewycky43ad1822010-06-15 07:32:55 +00001367 SourceLocation *L) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00001368 assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField));
1369
Nick Lewycky43ad1822010-06-15 07:32:55 +00001370 if (isa<CallExpr>(S)) {
1371 // Do not descend into function calls or constructors, as the use
1372 // of an uninitialized field may be valid. One would have to inspect
1373 // the contents of the function/ctor to determine if it is safe or not.
1374 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1375 // may be safe, depending on what the function/ctor does.
1376 return false;
1377 }
1378 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
1379 const NamedDecl *RhsField = ME->getMemberDecl();
Anders Carlsson175ffbf2010-10-06 02:43:25 +00001380
1381 if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) {
1382 // The member expression points to a static data member.
1383 assert(VD->isStaticDataMember() &&
1384 "Member points to non-static data member!");
Nick Lewyckyedd59112010-10-06 18:37:39 +00001385 (void)VD;
Anders Carlsson175ffbf2010-10-06 02:43:25 +00001386 return false;
1387 }
1388
1389 if (isa<EnumConstantDecl>(RhsField)) {
1390 // The member expression points to an enum.
1391 return false;
1392 }
1393
John McCallb4190042009-11-04 23:02:40 +00001394 if (RhsField == LhsField) {
1395 // Initializing a field with itself. Throw a warning.
1396 // But wait; there are exceptions!
1397 // Exception #1: The field may not belong to this record.
1398 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
Nick Lewycky43ad1822010-06-15 07:32:55 +00001399 const Expr *base = ME->getBase();
John McCallb4190042009-11-04 23:02:40 +00001400 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1401 // Even though the field matches, it does not belong to this record.
1402 return false;
1403 }
1404 // None of the exceptions triggered; return true to indicate an
1405 // uninitialized field was used.
1406 *L = ME->getMemberLoc();
1407 return true;
1408 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001409 } else if (isa<UnaryExprOrTypeTraitExpr>(S)) {
Argyrios Kyrtzidisff8819b2010-09-21 10:47:20 +00001410 // sizeof/alignof doesn't reference contents, do not warn.
1411 return false;
1412 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) {
1413 // address-of doesn't reference contents (the pointer may be dereferenced
1414 // in the same expression but it would be rare; and weird).
1415 if (UOE->getOpcode() == UO_AddrOf)
1416 return false;
John McCallb4190042009-11-04 23:02:40 +00001417 }
John McCall7502c1d2011-02-13 04:07:26 +00001418 for (Stmt::const_child_range it = S->children(); it; ++it) {
Nick Lewycky43ad1822010-06-15 07:32:55 +00001419 if (!*it) {
1420 // An expression such as 'member(arg ?: "")' may trigger this.
John McCallb4190042009-11-04 23:02:40 +00001421 continue;
1422 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00001423 if (InitExprContainsUninitializedFields(*it, LhsField, L))
1424 return true;
John McCallb4190042009-11-04 23:02:40 +00001425 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00001426 return false;
John McCallb4190042009-11-04 23:02:40 +00001427}
1428
John McCallf312b1e2010-08-26 23:41:50 +00001429MemInitResult
Chandler Carruth894aed92010-12-06 09:23:57 +00001430Sema::BuildMemberInitializer(ValueDecl *Member, Expr **Args,
Eli Friedman59c04372009-07-29 19:44:27 +00001431 unsigned NumArgs, SourceLocation IdLoc,
Douglas Gregor802ab452009-12-02 22:36:29 +00001432 SourceLocation LParenLoc,
Eli Friedman59c04372009-07-29 19:44:27 +00001433 SourceLocation RParenLoc) {
Chandler Carruth894aed92010-12-06 09:23:57 +00001434 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
1435 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
1436 assert((DirectMember || IndirectMember) &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00001437 "Member must be a FieldDecl or IndirectFieldDecl");
1438
Douglas Gregor464b2f02010-11-05 22:21:31 +00001439 if (Member->isInvalidDecl())
1440 return true;
Chandler Carruth894aed92010-12-06 09:23:57 +00001441
John McCallb4190042009-11-04 23:02:40 +00001442 // Diagnose value-uses of fields to initialize themselves, e.g.
1443 // foo(foo)
1444 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00001445 // TODO: implement -Wuninitialized and fold this into that framework.
John McCallb4190042009-11-04 23:02:40 +00001446 for (unsigned i = 0; i < NumArgs; ++i) {
1447 SourceLocation L;
1448 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1449 // FIXME: Return true in the case when other fields are used before being
1450 // uninitialized. For example, let this field be the i'th field. When
1451 // initializing the i'th field, throw a warning if any of the >= i'th
1452 // fields are used, as they are not yet initialized.
1453 // Right now we are only handling the case where the i'th field uses
1454 // itself in its initializer.
1455 Diag(L, diag::warn_field_is_uninit);
1456 }
1457 }
1458
Eli Friedman59c04372009-07-29 19:44:27 +00001459 bool HasDependentArg = false;
1460 for (unsigned i = 0; i < NumArgs; i++)
1461 HasDependentArg |= Args[i]->isTypeDependent();
1462
Chandler Carruth894aed92010-12-06 09:23:57 +00001463 Expr *Init;
Eli Friedman0f2b97d2010-07-24 21:19:15 +00001464 if (Member->getType()->isDependentType() || HasDependentArg) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001465 // Can't check initialization for a member of dependent type or when
1466 // any of the arguments are type-dependent expressions.
Chandler Carruth894aed92010-12-06 09:23:57 +00001467 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1468 RParenLoc);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001469
1470 // Erase any temporaries within this evaluation context; we're not
1471 // going to track them in the AST, since we'll be rebuilding the
1472 // ASTs during template instantiation.
1473 ExprTemporaries.erase(
1474 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1475 ExprTemporaries.end());
Chandler Carruth894aed92010-12-06 09:23:57 +00001476 } else {
1477 // Initialize the member.
1478 InitializedEntity MemberEntity =
1479 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
1480 : InitializedEntity::InitializeMember(IndirectMember, 0);
1481 InitializationKind Kind =
1482 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc);
John McCallb4eb64d2010-10-08 02:01:28 +00001483
Chandler Carruth894aed92010-12-06 09:23:57 +00001484 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
1485
1486 ExprResult MemberInit =
1487 InitSeq.Perform(*this, MemberEntity, Kind,
1488 MultiExprArg(*this, Args, NumArgs), 0);
1489 if (MemberInit.isInvalid())
1490 return true;
1491
1492 CheckImplicitConversions(MemberInit.get(), LParenLoc);
1493
1494 // C++0x [class.base.init]p7:
1495 // The initialization of each base and member constitutes a
1496 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00001497 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Chandler Carruth894aed92010-12-06 09:23:57 +00001498 if (MemberInit.isInvalid())
1499 return true;
1500
1501 // If we are in a dependent context, template instantiation will
1502 // perform this type-checking again. Just save the arguments that we
1503 // received in a ParenListExpr.
1504 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1505 // of the information that we have about the member
1506 // initializer. However, deconstructing the ASTs is a dicey process,
1507 // and this approach is far more likely to get the corner cases right.
1508 if (CurContext->isDependentContext())
1509 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1510 RParenLoc);
1511 else
1512 Init = MemberInit.get();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001513 }
1514
Chandler Carruth894aed92010-12-06 09:23:57 +00001515 if (DirectMember) {
Sean Huntcbb67482011-01-08 20:30:50 +00001516 return new (Context) CXXCtorInitializer(Context, DirectMember,
Chandler Carruth894aed92010-12-06 09:23:57 +00001517 IdLoc, LParenLoc, Init,
1518 RParenLoc);
1519 } else {
Sean Huntcbb67482011-01-08 20:30:50 +00001520 return new (Context) CXXCtorInitializer(Context, IndirectMember,
Chandler Carruth894aed92010-12-06 09:23:57 +00001521 IdLoc, LParenLoc, Init,
1522 RParenLoc);
1523 }
Eli Friedman59c04372009-07-29 19:44:27 +00001524}
1525
John McCallf312b1e2010-08-26 23:41:50 +00001526MemInitResult
Sean Hunt97fcc492011-01-08 19:20:43 +00001527Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo,
1528 Expr **Args, unsigned NumArgs,
Sean Hunt41717662011-02-26 19:13:13 +00001529 SourceLocation NameLoc,
Sean Hunt97fcc492011-01-08 19:20:43 +00001530 SourceLocation LParenLoc,
1531 SourceLocation RParenLoc,
Sean Hunt41717662011-02-26 19:13:13 +00001532 CXXRecordDecl *ClassDecl) {
Sean Hunt97fcc492011-01-08 19:20:43 +00001533 SourceLocation Loc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
1534 if (!LangOpts.CPlusPlus0x)
1535 return Diag(Loc, diag::err_delegation_0x_only)
1536 << TInfo->getTypeLoc().getLocalSourceRange();
Sebastian Redlf9c32eb2011-03-12 13:53:51 +00001537
Sean Hunt41717662011-02-26 19:13:13 +00001538 // Initialize the object.
1539 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
1540 QualType(ClassDecl->getTypeForDecl(), 0));
1541 InitializationKind Kind =
1542 InitializationKind::CreateDirect(NameLoc, LParenLoc, RParenLoc);
1543
1544 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs);
1545
1546 ExprResult DelegationInit =
1547 InitSeq.Perform(*this, DelegationEntity, Kind,
1548 MultiExprArg(*this, Args, NumArgs), 0);
1549 if (DelegationInit.isInvalid())
1550 return true;
1551
1552 CXXConstructExpr *ConExpr = cast<CXXConstructExpr>(DelegationInit.get());
Sean Huntfe57eef2011-05-04 05:57:24 +00001553 CXXConstructorDecl *Constructor
1554 = ConExpr->getConstructor();
Sean Hunt41717662011-02-26 19:13:13 +00001555 assert(Constructor && "Delegating constructor with no target?");
1556
1557 CheckImplicitConversions(DelegationInit.get(), LParenLoc);
1558
1559 // C++0x [class.base.init]p7:
1560 // The initialization of each base and member constitutes a
1561 // full-expression.
1562 DelegationInit = MaybeCreateExprWithCleanups(DelegationInit);
1563 if (DelegationInit.isInvalid())
1564 return true;
1565
1566 // If we are in a dependent context, template instantiation will
1567 // perform this type-checking again. Just save the arguments that we
1568 // received in a ParenListExpr.
1569 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1570 // of the information that we have about the base
1571 // initializer. However, deconstructing the ASTs is a dicey process,
1572 // and this approach is far more likely to get the corner cases right.
1573 if (CurContext->isDependentContext()) {
1574 ExprResult Init
1575 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args,
1576 NumArgs, RParenLoc));
1577 return new (Context) CXXCtorInitializer(Context, Loc, LParenLoc,
1578 Constructor, Init.takeAs<Expr>(),
1579 RParenLoc);
1580 }
1581
1582 return new (Context) CXXCtorInitializer(Context, Loc, LParenLoc, Constructor,
1583 DelegationInit.takeAs<Expr>(),
1584 RParenLoc);
Sean Hunt97fcc492011-01-08 19:20:43 +00001585}
1586
1587MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00001588Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Douglas Gregor802ab452009-12-02 22:36:29 +00001589 Expr **Args, unsigned NumArgs,
1590 SourceLocation LParenLoc, SourceLocation RParenLoc,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001591 CXXRecordDecl *ClassDecl,
1592 SourceLocation EllipsisLoc) {
Eli Friedman59c04372009-07-29 19:44:27 +00001593 bool HasDependentArg = false;
1594 for (unsigned i = 0; i < NumArgs; i++)
1595 HasDependentArg |= Args[i]->isTypeDependent();
1596
Douglas Gregor3956b1a2010-06-16 16:03:14 +00001597 SourceLocation BaseLoc
1598 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
1599
1600 if (!BaseType->isDependentType() && !BaseType->isRecordType())
1601 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1602 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
1603
1604 // C++ [class.base.init]p2:
1605 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00001606 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00001607 // of that class, the mem-initializer is ill-formed. A
1608 // mem-initializer-list can initialize a base class using any
1609 // name that denotes that base class type.
1610 bool Dependent = BaseType->isDependentType() || HasDependentArg;
1611
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001612 if (EllipsisLoc.isValid()) {
1613 // This is a pack expansion.
1614 if (!BaseType->containsUnexpandedParameterPack()) {
1615 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1616 << SourceRange(BaseLoc, RParenLoc);
1617
1618 EllipsisLoc = SourceLocation();
1619 }
1620 } else {
1621 // Check for any unexpanded parameter packs.
1622 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
1623 return true;
1624
1625 for (unsigned I = 0; I != NumArgs; ++I)
1626 if (DiagnoseUnexpandedParameterPack(Args[I]))
1627 return true;
1628 }
1629
Douglas Gregor3956b1a2010-06-16 16:03:14 +00001630 // Check for direct and virtual base classes.
1631 const CXXBaseSpecifier *DirectBaseSpec = 0;
1632 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1633 if (!Dependent) {
Sean Hunt97fcc492011-01-08 19:20:43 +00001634 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
1635 BaseType))
Sean Hunt41717662011-02-26 19:13:13 +00001636 return BuildDelegatingInitializer(BaseTInfo, Args, NumArgs, BaseLoc,
1637 LParenLoc, RParenLoc, ClassDecl);
Sean Hunt97fcc492011-01-08 19:20:43 +00001638
Douglas Gregor3956b1a2010-06-16 16:03:14 +00001639 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1640 VirtualBaseSpec);
1641
1642 // C++ [base.class.init]p2:
1643 // Unless the mem-initializer-id names a nonstatic data member of the
1644 // constructor's class or a direct or virtual base of that class, the
1645 // mem-initializer is ill-formed.
1646 if (!DirectBaseSpec && !VirtualBaseSpec) {
1647 // If the class has any dependent bases, then it's possible that
1648 // one of those types will resolve to the same type as
1649 // BaseType. Therefore, just treat this as a dependent base
1650 // class initialization. FIXME: Should we try to check the
1651 // initialization anyway? It seems odd.
1652 if (ClassDecl->hasAnyDependentBases())
1653 Dependent = true;
1654 else
1655 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1656 << BaseType << Context.getTypeDeclType(ClassDecl)
1657 << BaseTInfo->getTypeLoc().getLocalSourceRange();
1658 }
1659 }
1660
1661 if (Dependent) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001662 // Can't check initialization for a base of dependent type or when
1663 // any of the arguments are type-dependent expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00001664 ExprResult BaseInit
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001665 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1666 RParenLoc));
Eli Friedman59c04372009-07-29 19:44:27 +00001667
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001668 // Erase any temporaries within this evaluation context; we're not
1669 // going to track them in the AST, since we'll be rebuilding the
1670 // ASTs during template instantiation.
1671 ExprTemporaries.erase(
1672 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1673 ExprTemporaries.end());
Mike Stump1eb44332009-09-09 15:08:12 +00001674
Sean Huntcbb67482011-01-08 20:30:50 +00001675 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001676 /*IsVirtual=*/false,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001677 LParenLoc,
1678 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001679 RParenLoc,
1680 EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001681 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001682
1683 // C++ [base.class.init]p2:
1684 // If a mem-initializer-id is ambiguous because it designates both
1685 // a direct non-virtual base class and an inherited virtual base
1686 // class, the mem-initializer is ill-formed.
1687 if (DirectBaseSpec && VirtualBaseSpec)
1688 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00001689 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001690
1691 CXXBaseSpecifier *BaseSpec
1692 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
1693 if (!BaseSpec)
1694 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1695
1696 // Initialize the base.
1697 InitializedEntity BaseEntity =
Anders Carlsson711f34a2010-04-21 19:52:01 +00001698 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001699 InitializationKind Kind =
1700 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc);
1701
1702 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
1703
John McCall60d7b3a2010-08-24 06:29:42 +00001704 ExprResult BaseInit =
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001705 InitSeq.Perform(*this, BaseEntity, Kind,
John McCallca0408f2010-08-23 06:44:23 +00001706 MultiExprArg(*this, Args, NumArgs), 0);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001707 if (BaseInit.isInvalid())
1708 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00001709
1710 CheckImplicitConversions(BaseInit.get(), LParenLoc);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001711
1712 // C++0x [class.base.init]p7:
1713 // The initialization of each base and member constitutes a
1714 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00001715 BaseInit = MaybeCreateExprWithCleanups(BaseInit);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001716 if (BaseInit.isInvalid())
1717 return true;
1718
1719 // If we are in a dependent context, template instantiation will
1720 // perform this type-checking again. Just save the arguments that we
1721 // received in a ParenListExpr.
1722 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1723 // of the information that we have about the base
1724 // initializer. However, deconstructing the ASTs is a dicey process,
1725 // and this approach is far more likely to get the corner cases right.
1726 if (CurContext->isDependentContext()) {
John McCall60d7b3a2010-08-24 06:29:42 +00001727 ExprResult Init
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001728 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1729 RParenLoc));
Sean Huntcbb67482011-01-08 20:30:50 +00001730 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001731 BaseSpec->isVirtual(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001732 LParenLoc,
1733 Init.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001734 RParenLoc,
1735 EllipsisLoc);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001736 }
1737
Sean Huntcbb67482011-01-08 20:30:50 +00001738 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001739 BaseSpec->isVirtual(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001740 LParenLoc,
1741 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001742 RParenLoc,
1743 EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001744}
1745
Anders Carlssone5ef7402010-04-23 03:10:23 +00001746/// ImplicitInitializerKind - How an implicit base or member initializer should
1747/// initialize its base or member.
1748enum ImplicitInitializerKind {
1749 IIK_Default,
1750 IIK_Copy,
1751 IIK_Move
1752};
1753
Anders Carlssondefefd22010-04-23 02:00:02 +00001754static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001755BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00001756 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00001757 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00001758 bool IsInheritedVirtualBase,
Sean Huntcbb67482011-01-08 20:30:50 +00001759 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00001760 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00001761 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
1762 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00001763
John McCall60d7b3a2010-08-24 06:29:42 +00001764 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00001765
1766 switch (ImplicitInitKind) {
1767 case IIK_Default: {
1768 InitializationKind InitKind
1769 = InitializationKind::CreateDefault(Constructor->getLocation());
1770 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
1771 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00001772 MultiExprArg(SemaRef, 0, 0));
Anders Carlssone5ef7402010-04-23 03:10:23 +00001773 break;
1774 }
Anders Carlsson84688f22010-04-20 23:11:20 +00001775
Anders Carlssone5ef7402010-04-23 03:10:23 +00001776 case IIK_Copy: {
1777 ParmVarDecl *Param = Constructor->getParamDecl(0);
1778 QualType ParamType = Param->getType().getNonReferenceType();
1779
1780 Expr *CopyCtorArg =
Douglas Gregor40d96a62011-02-28 21:54:11 +00001781 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param,
John McCallf89e55a2010-11-18 06:31:45 +00001782 Constructor->getLocation(), ParamType,
1783 VK_LValue, 0);
Anders Carlssone5ef7402010-04-23 03:10:23 +00001784
Anders Carlssonc7957502010-04-24 22:02:54 +00001785 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00001786 QualType ArgTy =
1787 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
1788 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00001789
1790 CXXCastPath BasePath;
1791 BasePath.push_back(BaseSpec);
John Wiegley429bb272011-04-08 18:41:53 +00001792 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
1793 CK_UncheckedDerivedToBase,
1794 VK_LValue, &BasePath).take();
Anders Carlssonc7957502010-04-24 22:02:54 +00001795
Anders Carlssone5ef7402010-04-23 03:10:23 +00001796 InitializationKind InitKind
1797 = InitializationKind::CreateDirect(Constructor->getLocation(),
1798 SourceLocation(), SourceLocation());
1799 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
1800 &CopyCtorArg, 1);
1801 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00001802 MultiExprArg(&CopyCtorArg, 1));
Anders Carlssone5ef7402010-04-23 03:10:23 +00001803 break;
1804 }
Anders Carlsson84688f22010-04-20 23:11:20 +00001805
Anders Carlssone5ef7402010-04-23 03:10:23 +00001806 case IIK_Move:
1807 assert(false && "Unhandled initializer kind!");
1808 }
John McCall9ae2f072010-08-23 23:25:46 +00001809
Douglas Gregor53c374f2010-12-07 00:41:46 +00001810 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00001811 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00001812 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00001813
Anders Carlssondefefd22010-04-23 02:00:02 +00001814 CXXBaseInit =
Sean Huntcbb67482011-01-08 20:30:50 +00001815 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlsson84688f22010-04-20 23:11:20 +00001816 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
1817 SourceLocation()),
1818 BaseSpec->isVirtual(),
1819 SourceLocation(),
1820 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001821 SourceLocation(),
Anders Carlsson84688f22010-04-20 23:11:20 +00001822 SourceLocation());
1823
Anders Carlssondefefd22010-04-23 02:00:02 +00001824 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00001825}
1826
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001827static bool
1828BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00001829 ImplicitInitializerKind ImplicitInitKind,
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001830 FieldDecl *Field,
Sean Huntcbb67482011-01-08 20:30:50 +00001831 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00001832 if (Field->isInvalidDecl())
1833 return true;
1834
Chandler Carruthf186b542010-06-29 23:50:44 +00001835 SourceLocation Loc = Constructor->getLocation();
1836
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001837 if (ImplicitInitKind == IIK_Copy) {
1838 ParmVarDecl *Param = Constructor->getParamDecl(0);
1839 QualType ParamType = Param->getType().getNonReferenceType();
1840
1841 Expr *MemberExprBase =
Douglas Gregor40d96a62011-02-28 21:54:11 +00001842 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param,
John McCallf89e55a2010-11-18 06:31:45 +00001843 Loc, ParamType, VK_LValue, 0);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001844
1845 // Build a reference to this field within the parameter.
1846 CXXScopeSpec SS;
1847 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
1848 Sema::LookupMemberName);
1849 MemberLookup.addDecl(Field, AS_public);
1850 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00001851 ExprResult CopyCtorArg
John McCall9ae2f072010-08-23 23:25:46 +00001852 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001853 ParamType, Loc,
1854 /*IsArrow=*/false,
1855 SS,
1856 /*FirstQualifierInScope=*/0,
1857 MemberLookup,
1858 /*TemplateArgs=*/0);
1859 if (CopyCtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001860 return true;
1861
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001862 // When the field we are copying is an array, create index variables for
1863 // each dimension of the array. We use these index variables to subscript
1864 // the source array, and other clients (e.g., CodeGen) will perform the
1865 // necessary iteration with these index variables.
1866 llvm::SmallVector<VarDecl *, 4> IndexVariables;
1867 QualType BaseType = Field->getType();
1868 QualType SizeType = SemaRef.Context.getSizeType();
1869 while (const ConstantArrayType *Array
1870 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
1871 // Create the iteration variable for this array index.
1872 IdentifierInfo *IterationVarName = 0;
1873 {
1874 llvm::SmallString<8> Str;
1875 llvm::raw_svector_ostream OS(Str);
1876 OS << "__i" << IndexVariables.size();
1877 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
1878 }
1879 VarDecl *IterationVar
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001880 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001881 IterationVarName, SizeType,
1882 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00001883 SC_None, SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001884 IndexVariables.push_back(IterationVar);
1885
1886 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00001887 ExprResult IterationVarRef
John McCallf89e55a2010-11-18 06:31:45 +00001888 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001889 assert(!IterationVarRef.isInvalid() &&
1890 "Reference to invented variable cannot fail!");
1891
1892 // Subscript the array with this iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00001893 CopyCtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CopyCtorArg.take(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001894 Loc,
John McCall9ae2f072010-08-23 23:25:46 +00001895 IterationVarRef.take(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001896 Loc);
1897 if (CopyCtorArg.isInvalid())
1898 return true;
1899
1900 BaseType = Array->getElementType();
1901 }
1902
1903 // Construct the entity that we will be initializing. For an array, this
1904 // will be first element in the array, which may require several levels
1905 // of array-subscript entities.
1906 llvm::SmallVector<InitializedEntity, 4> Entities;
1907 Entities.reserve(1 + IndexVariables.size());
1908 Entities.push_back(InitializedEntity::InitializeMember(Field));
1909 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
1910 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
1911 0,
1912 Entities.back()));
1913
1914 // Direct-initialize to use the copy constructor.
1915 InitializationKind InitKind =
1916 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
1917
1918 Expr *CopyCtorArgE = CopyCtorArg.takeAs<Expr>();
1919 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
1920 &CopyCtorArgE, 1);
1921
John McCall60d7b3a2010-08-24 06:29:42 +00001922 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001923 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00001924 MultiExprArg(&CopyCtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00001925 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001926 if (MemberInit.isInvalid())
1927 return true;
1928
1929 CXXMemberInit
Sean Huntcbb67482011-01-08 20:30:50 +00001930 = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001931 MemberInit.takeAs<Expr>(), Loc,
1932 IndexVariables.data(),
1933 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00001934 return false;
1935 }
1936
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001937 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
1938
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001939 QualType FieldBaseElementType =
1940 SemaRef.Context.getBaseElementType(Field->getType());
1941
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001942 if (FieldBaseElementType->isRecordType()) {
1943 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001944 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00001945 InitializationKind::CreateDefault(Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001946
1947 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00001948 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00001949 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCall9ae2f072010-08-23 23:25:46 +00001950
Douglas Gregor53c374f2010-12-07 00:41:46 +00001951 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001952 if (MemberInit.isInvalid())
1953 return true;
1954
1955 CXXMemberInit =
Sean Huntcbb67482011-01-08 20:30:50 +00001956 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Chandler Carruthf186b542010-06-29 23:50:44 +00001957 Field, Loc, Loc,
John McCall9ae2f072010-08-23 23:25:46 +00001958 MemberInit.get(),
Chandler Carruthf186b542010-06-29 23:50:44 +00001959 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001960 return false;
1961 }
Anders Carlsson114a2972010-04-23 03:07:47 +00001962
1963 if (FieldBaseElementType->isReferenceType()) {
1964 SemaRef.Diag(Constructor->getLocation(),
1965 diag::err_uninitialized_member_in_ctor)
1966 << (int)Constructor->isImplicit()
1967 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1968 << 0 << Field->getDeclName();
1969 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1970 return true;
1971 }
1972
1973 if (FieldBaseElementType.isConstQualified()) {
1974 SemaRef.Diag(Constructor->getLocation(),
1975 diag::err_uninitialized_member_in_ctor)
1976 << (int)Constructor->isImplicit()
1977 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1978 << 1 << Field->getDeclName();
1979 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1980 return true;
1981 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001982
1983 // Nothing to initialize.
1984 CXXMemberInit = 0;
1985 return false;
1986}
John McCallf1860e52010-05-20 23:23:51 +00001987
1988namespace {
1989struct BaseAndFieldInfo {
1990 Sema &S;
1991 CXXConstructorDecl *Ctor;
1992 bool AnyErrorsInInits;
1993 ImplicitInitializerKind IIK;
Sean Huntcbb67482011-01-08 20:30:50 +00001994 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
1995 llvm::SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallf1860e52010-05-20 23:23:51 +00001996
1997 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
1998 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
1999 // FIXME: Handle implicit move constructors.
2000 if (Ctor->isImplicit() && Ctor->isCopyConstructor())
2001 IIK = IIK_Copy;
2002 else
2003 IIK = IIK_Default;
2004 }
2005};
2006}
2007
2008static bool CollectFieldInitializer(BaseAndFieldInfo &Info,
2009 FieldDecl *Top, FieldDecl *Field) {
2010
Chandler Carruthe861c602010-06-30 02:59:29 +00002011 // Overwhelmingly common case: we have a direct initializer for this field.
Sean Huntcbb67482011-01-08 20:30:50 +00002012 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002013 Info.AllToInit.push_back(Init);
John McCallf1860e52010-05-20 23:23:51 +00002014 return false;
2015 }
2016
2017 if (Info.IIK == IIK_Default && Field->isAnonymousStructOrUnion()) {
2018 const RecordType *FieldClassType = Field->getType()->getAs<RecordType>();
2019 assert(FieldClassType && "anonymous struct/union without record type");
John McCallf1860e52010-05-20 23:23:51 +00002020 CXXRecordDecl *FieldClassDecl
2021 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Chandler Carruthe861c602010-06-30 02:59:29 +00002022
2023 // Even though union members never have non-trivial default
2024 // constructions in C++03, we still build member initializers for aggregate
2025 // record types which can be union members, and C++0x allows non-trivial
2026 // default constructors for union members, so we ensure that only one
2027 // member is initialized for these.
2028 if (FieldClassDecl->isUnion()) {
2029 // First check for an explicit initializer for one field.
2030 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
2031 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
Sean Huntcbb67482011-01-08 20:30:50 +00002032 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(*FA)) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002033 Info.AllToInit.push_back(Init);
Chandler Carruthe861c602010-06-30 02:59:29 +00002034
2035 // Once we've initialized a field of an anonymous union, the union
2036 // field in the class is also initialized, so exit immediately.
2037 return false;
Argyrios Kyrtzidis881b36c2010-08-16 17:27:13 +00002038 } else if ((*FA)->isAnonymousStructOrUnion()) {
2039 if (CollectFieldInitializer(Info, Top, *FA))
2040 return true;
Chandler Carruthe861c602010-06-30 02:59:29 +00002041 }
2042 }
2043
2044 // Fallthrough and construct a default initializer for the union as
2045 // a whole, which can call its default constructor if such a thing exists
2046 // (C++0x perhaps). FIXME: It's not clear that this is the correct
2047 // behavior going forward with C++0x, when anonymous unions there are
2048 // finalized, we should revisit this.
2049 } else {
2050 // For structs, we simply descend through to initialize all members where
2051 // necessary.
2052 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
2053 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
2054 if (CollectFieldInitializer(Info, Top, *FA))
2055 return true;
2056 }
2057 }
John McCallf1860e52010-05-20 23:23:51 +00002058 }
2059
2060 // Don't try to build an implicit initializer if there were semantic
2061 // errors in any of the initializers (and therefore we might be
2062 // missing some that the user actually wrote).
2063 if (Info.AnyErrorsInInits)
2064 return false;
2065
Sean Huntcbb67482011-01-08 20:30:50 +00002066 CXXCtorInitializer *Init = 0;
John McCallf1860e52010-05-20 23:23:51 +00002067 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, Init))
2068 return true;
John McCallf1860e52010-05-20 23:23:51 +00002069
Francois Pichet00eb3f92010-12-04 09:14:42 +00002070 if (Init)
2071 Info.AllToInit.push_back(Init);
2072
John McCallf1860e52010-05-20 23:23:51 +00002073 return false;
2074}
Sean Hunt059ce0d2011-05-01 07:04:31 +00002075
2076bool
2077Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
2078 CXXCtorInitializer *Initializer) {
Sean Huntfe57eef2011-05-04 05:57:24 +00002079 assert(Initializer->isDelegatingInitializer());
Sean Hunt01aacc02011-05-03 20:43:02 +00002080 Constructor->setNumCtorInitializers(1);
2081 CXXCtorInitializer **initializer =
2082 new (Context) CXXCtorInitializer*[1];
2083 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
2084 Constructor->setCtorInitializers(initializer);
2085
Sean Huntb76af9c2011-05-03 23:05:34 +00002086 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
2087 MarkDeclarationReferenced(Initializer->getSourceLocation(), Dtor);
2088 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
2089 }
2090
Sean Huntc1598702011-05-05 00:05:47 +00002091 DelegatingCtorDecls.push_back(Constructor);
Sean Huntfe57eef2011-05-04 05:57:24 +00002092
Sean Hunt059ce0d2011-05-01 07:04:31 +00002093 return false;
2094}
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002095
Eli Friedman80c30da2009-11-09 19:20:36 +00002096bool
Sean Huntcbb67482011-01-08 20:30:50 +00002097Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
2098 CXXCtorInitializer **Initializers,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002099 unsigned NumInitializers,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002100 bool AnyErrors) {
John McCalld6ca8da2010-04-10 07:37:23 +00002101 if (Constructor->getDeclContext()->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002102 // Just store the initializers as written, they will be checked during
2103 // instantiation.
2104 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00002105 Constructor->setNumCtorInitializers(NumInitializers);
2106 CXXCtorInitializer **baseOrMemberInitializers =
2107 new (Context) CXXCtorInitializer*[NumInitializers];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002108 memcpy(baseOrMemberInitializers, Initializers,
Sean Huntcbb67482011-01-08 20:30:50 +00002109 NumInitializers * sizeof(CXXCtorInitializer*));
2110 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002111 }
2112
2113 return false;
2114 }
2115
John McCallf1860e52010-05-20 23:23:51 +00002116 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00002117
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002118 // We need to build the initializer AST according to order of construction
2119 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00002120 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00002121 if (!ClassDecl)
2122 return true;
2123
Eli Friedman80c30da2009-11-09 19:20:36 +00002124 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002125
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002126 for (unsigned i = 0; i < NumInitializers; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00002127 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002128
2129 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00002130 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002131 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00002132 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002133 }
2134
Anders Carlsson711f34a2010-04-21 19:52:01 +00002135 // Keep track of the direct virtual bases.
2136 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
2137 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
2138 E = ClassDecl->bases_end(); I != E; ++I) {
2139 if (I->isVirtual())
2140 DirectVBases.insert(I);
2141 }
2142
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002143 // Push virtual bases before others.
2144 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2145 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2146
Sean Huntcbb67482011-01-08 20:30:50 +00002147 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00002148 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
2149 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002150 } else if (!AnyErrors) {
Anders Carlsson711f34a2010-04-21 19:52:01 +00002151 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00002152 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00002153 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002154 VBase, IsInheritedVirtualBase,
2155 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002156 HadError = true;
2157 continue;
2158 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002159
John McCallf1860e52010-05-20 23:23:51 +00002160 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002161 }
2162 }
Mike Stump1eb44332009-09-09 15:08:12 +00002163
John McCallf1860e52010-05-20 23:23:51 +00002164 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002165 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2166 E = ClassDecl->bases_end(); Base != E; ++Base) {
2167 // Virtuals are in the virtual base list and already constructed.
2168 if (Base->isVirtual())
2169 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00002170
Sean Huntcbb67482011-01-08 20:30:50 +00002171 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00002172 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
2173 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002174 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00002175 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00002176 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002177 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00002178 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002179 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002180 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002181 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00002182
John McCallf1860e52010-05-20 23:23:51 +00002183 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002184 }
2185 }
Mike Stump1eb44332009-09-09 15:08:12 +00002186
John McCallf1860e52010-05-20 23:23:51 +00002187 // Fields.
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002188 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00002189 E = ClassDecl->field_end(); Field != E; ++Field) {
2190 if ((*Field)->getType()->isIncompleteArrayType()) {
2191 assert(ClassDecl->hasFlexibleArrayMember() &&
2192 "Incomplete array type is not valid");
2193 continue;
2194 }
John McCallf1860e52010-05-20 23:23:51 +00002195 if (CollectFieldInitializer(Info, *Field, *Field))
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002196 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00002197 }
Mike Stump1eb44332009-09-09 15:08:12 +00002198
John McCallf1860e52010-05-20 23:23:51 +00002199 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002200 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00002201 Constructor->setNumCtorInitializers(NumInitializers);
2202 CXXCtorInitializer **baseOrMemberInitializers =
2203 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00002204 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00002205 NumInitializers * sizeof(CXXCtorInitializer*));
2206 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00002207
John McCallef027fe2010-03-16 21:39:52 +00002208 // Constructors implicitly reference the base and member
2209 // destructors.
2210 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
2211 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002212 }
Eli Friedman80c30da2009-11-09 19:20:36 +00002213
2214 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002215}
2216
Eli Friedman6347f422009-07-21 19:28:10 +00002217static void *GetKeyForTopLevelField(FieldDecl *Field) {
2218 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00002219 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00002220 if (RT->getDecl()->isAnonymousStructOrUnion())
2221 return static_cast<void *>(RT->getDecl());
2222 }
2223 return static_cast<void *>(Field);
2224}
2225
Anders Carlssonea356fb2010-04-02 05:42:15 +00002226static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCallf4c73712011-01-19 06:33:43 +00002227 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssoncdc83c72009-09-01 06:22:14 +00002228}
2229
Anders Carlssonea356fb2010-04-02 05:42:15 +00002230static void *GetKeyForMember(ASTContext &Context,
Sean Huntcbb67482011-01-08 20:30:50 +00002231 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002232 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00002233 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00002234
Eli Friedman6347f422009-07-21 19:28:10 +00002235 // For fields injected into the class via declaration of an anonymous union,
2236 // use its anonymous union class declaration as the unique key.
Francois Pichet00eb3f92010-12-04 09:14:42 +00002237 FieldDecl *Field = Member->getAnyMember();
2238
John McCall3c3ccdb2010-04-10 09:28:51 +00002239 // If the field is a member of an anonymous struct or union, our key
2240 // is the anonymous record decl that's a direct child of the class.
Anders Carlssonee11b2d2010-03-30 16:19:37 +00002241 RecordDecl *RD = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00002242 if (RD->isAnonymousStructOrUnion()) {
2243 while (true) {
2244 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
2245 if (Parent->isAnonymousStructOrUnion())
2246 RD = Parent;
2247 else
2248 break;
2249 }
2250
Anders Carlssonee11b2d2010-03-30 16:19:37 +00002251 return static_cast<void *>(RD);
John McCall3c3ccdb2010-04-10 09:28:51 +00002252 }
Mike Stump1eb44332009-09-09 15:08:12 +00002253
Anders Carlsson8f1a2402010-03-30 15:39:27 +00002254 return static_cast<void *>(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00002255}
2256
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002257static void
2258DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson071d6102010-04-02 03:38:04 +00002259 const CXXConstructorDecl *Constructor,
Sean Huntcbb67482011-01-08 20:30:50 +00002260 CXXCtorInitializer **Inits,
John McCalld6ca8da2010-04-10 07:37:23 +00002261 unsigned NumInits) {
2262 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00002263 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002264
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00002265 // Don't check initializers order unless the warning is enabled at the
2266 // location of at least one initializer.
2267 bool ShouldCheckOrder = false;
2268 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00002269 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00002270 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
2271 Init->getSourceLocation())
2272 != Diagnostic::Ignored) {
2273 ShouldCheckOrder = true;
2274 break;
2275 }
2276 }
2277 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002278 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002279
John McCalld6ca8da2010-04-10 07:37:23 +00002280 // Build the list of bases and members in the order that they'll
2281 // actually be initialized. The explicit initializers should be in
2282 // this same order but may be missing things.
2283 llvm::SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00002284
Anders Carlsson071d6102010-04-02 03:38:04 +00002285 const CXXRecordDecl *ClassDecl = Constructor->getParent();
2286
John McCalld6ca8da2010-04-10 07:37:23 +00002287 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00002288 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002289 ClassDecl->vbases_begin(),
2290 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00002291 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002292
John McCalld6ca8da2010-04-10 07:37:23 +00002293 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00002294 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002295 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002296 if (Base->isVirtual())
2297 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00002298 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002299 }
Mike Stump1eb44332009-09-09 15:08:12 +00002300
John McCalld6ca8da2010-04-10 07:37:23 +00002301 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002302 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2303 E = ClassDecl->field_end(); Field != E; ++Field)
John McCalld6ca8da2010-04-10 07:37:23 +00002304 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Mike Stump1eb44332009-09-09 15:08:12 +00002305
John McCalld6ca8da2010-04-10 07:37:23 +00002306 unsigned NumIdealInits = IdealInitKeys.size();
2307 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00002308
Sean Huntcbb67482011-01-08 20:30:50 +00002309 CXXCtorInitializer *PrevInit = 0;
John McCalld6ca8da2010-04-10 07:37:23 +00002310 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00002311 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichet00eb3f92010-12-04 09:14:42 +00002312 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00002313
2314 // Scan forward to try to find this initializer in the idealized
2315 // initializers list.
2316 for (; IdealIndex != NumIdealInits; ++IdealIndex)
2317 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002318 break;
John McCalld6ca8da2010-04-10 07:37:23 +00002319
2320 // If we didn't find this initializer, it must be because we
2321 // scanned past it on a previous iteration. That can only
2322 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00002323 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00002324 Sema::SemaDiagnosticBuilder D =
2325 SemaRef.Diag(PrevInit->getSourceLocation(),
2326 diag::warn_initializer_out_of_order);
2327
Francois Pichet00eb3f92010-12-04 09:14:42 +00002328 if (PrevInit->isAnyMemberInitializer())
2329 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00002330 else
2331 D << 1 << PrevInit->getBaseClassInfo()->getType();
2332
Francois Pichet00eb3f92010-12-04 09:14:42 +00002333 if (Init->isAnyMemberInitializer())
2334 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00002335 else
2336 D << 1 << Init->getBaseClassInfo()->getType();
2337
2338 // Move back to the initializer's location in the ideal list.
2339 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
2340 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002341 break;
John McCalld6ca8da2010-04-10 07:37:23 +00002342
2343 assert(IdealIndex != NumIdealInits &&
2344 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00002345 }
John McCalld6ca8da2010-04-10 07:37:23 +00002346
2347 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00002348 }
Anders Carlssona7b35212009-03-25 02:58:17 +00002349}
2350
John McCall3c3ccdb2010-04-10 09:28:51 +00002351namespace {
2352bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00002353 CXXCtorInitializer *Init,
2354 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00002355 if (!PrevInit) {
2356 PrevInit = Init;
2357 return false;
2358 }
2359
2360 if (FieldDecl *Field = Init->getMember())
2361 S.Diag(Init->getSourceLocation(),
2362 diag::err_multiple_mem_initialization)
2363 << Field->getDeclName()
2364 << Init->getSourceRange();
2365 else {
John McCallf4c73712011-01-19 06:33:43 +00002366 const Type *BaseClass = Init->getBaseClass();
John McCall3c3ccdb2010-04-10 09:28:51 +00002367 assert(BaseClass && "neither field nor base");
2368 S.Diag(Init->getSourceLocation(),
2369 diag::err_multiple_base_initialization)
2370 << QualType(BaseClass, 0)
2371 << Init->getSourceRange();
2372 }
2373 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
2374 << 0 << PrevInit->getSourceRange();
2375
2376 return true;
2377}
2378
Sean Huntcbb67482011-01-08 20:30:50 +00002379typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00002380typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
2381
2382bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00002383 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00002384 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002385 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00002386 RecordDecl *Parent = Field->getParent();
2387 if (!Parent->isAnonymousStructOrUnion())
2388 return false;
2389
2390 NamedDecl *Child = Field;
2391 do {
2392 if (Parent->isUnion()) {
2393 UnionEntry &En = Unions[Parent];
2394 if (En.first && En.first != Child) {
2395 S.Diag(Init->getSourceLocation(),
2396 diag::err_multiple_mem_union_initialization)
2397 << Field->getDeclName()
2398 << Init->getSourceRange();
2399 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
2400 << 0 << En.second->getSourceRange();
2401 return true;
2402 } else if (!En.first) {
2403 En.first = Child;
2404 En.second = Init;
2405 }
2406 }
2407
2408 Child = Parent;
2409 Parent = cast<RecordDecl>(Parent->getDeclContext());
2410 } while (Parent->isAnonymousStructOrUnion());
2411
2412 return false;
2413}
2414}
2415
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002416/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00002417void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002418 SourceLocation ColonLoc,
2419 MemInitTy **meminits, unsigned NumMemInits,
2420 bool AnyErrors) {
2421 if (!ConstructorDecl)
2422 return;
2423
2424 AdjustDeclIfTemplate(ConstructorDecl);
2425
2426 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002427 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002428
2429 if (!Constructor) {
2430 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
2431 return;
2432 }
2433
Sean Huntcbb67482011-01-08 20:30:50 +00002434 CXXCtorInitializer **MemInits =
2435 reinterpret_cast<CXXCtorInitializer **>(meminits);
John McCall3c3ccdb2010-04-10 09:28:51 +00002436
2437 // Mapping for the duplicate initializers check.
2438 // For member initializers, this is keyed with a FieldDecl*.
2439 // For base initializers, this is keyed with a Type*.
Sean Huntcbb67482011-01-08 20:30:50 +00002440 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00002441
2442 // Mapping for the inconsistent anonymous-union initializers check.
2443 RedundantUnionMap MemberUnions;
2444
Anders Carlssonea356fb2010-04-02 05:42:15 +00002445 bool HadError = false;
2446 for (unsigned i = 0; i < NumMemInits; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00002447 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002448
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00002449 // Set the source order index.
2450 Init->setSourceOrder(i);
2451
Francois Pichet00eb3f92010-12-04 09:14:42 +00002452 if (Init->isAnyMemberInitializer()) {
2453 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00002454 if (CheckRedundantInit(*this, Init, Members[Field]) ||
2455 CheckRedundantUnionInit(*this, Init, MemberUnions))
2456 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00002457 } else if (Init->isBaseInitializer()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00002458 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
2459 if (CheckRedundantInit(*this, Init, Members[Key]))
2460 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00002461 } else {
2462 assert(Init->isDelegatingInitializer());
2463 // This must be the only initializer
2464 if (i != 0 || NumMemInits > 1) {
2465 Diag(MemInits[0]->getSourceLocation(),
2466 diag::err_delegating_initializer_alone)
2467 << MemInits[0]->getSourceRange();
2468 HadError = true;
Sean Hunt059ce0d2011-05-01 07:04:31 +00002469 // We will treat this as being the only initializer.
Sean Hunt41717662011-02-26 19:13:13 +00002470 }
Sean Huntfe57eef2011-05-04 05:57:24 +00002471 SetDelegatingInitializer(Constructor, MemInits[i]);
Sean Hunt059ce0d2011-05-01 07:04:31 +00002472 // Return immediately as the initializer is set.
2473 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002474 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002475 }
2476
Anders Carlssonea356fb2010-04-02 05:42:15 +00002477 if (HadError)
2478 return;
2479
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002480 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00002481
Sean Huntcbb67482011-01-08 20:30:50 +00002482 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002483}
2484
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002485void
John McCallef027fe2010-03-16 21:39:52 +00002486Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
2487 CXXRecordDecl *ClassDecl) {
2488 // Ignore dependent contexts.
2489 if (ClassDecl->isDependentContext())
Anders Carlsson9f853df2009-11-17 04:44:12 +00002490 return;
John McCall58e6f342010-03-16 05:22:47 +00002491
2492 // FIXME: all the access-control diagnostics are positioned on the
2493 // field/base declaration. That's probably good; that said, the
2494 // user might reasonably want to know why the destructor is being
2495 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00002496
Anders Carlsson9f853df2009-11-17 04:44:12 +00002497 // Non-static data members.
2498 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
2499 E = ClassDecl->field_end(); I != E; ++I) {
2500 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00002501 if (Field->isInvalidDecl())
2502 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00002503 QualType FieldType = Context.getBaseElementType(Field->getType());
2504
2505 const RecordType* RT = FieldType->getAs<RecordType>();
2506 if (!RT)
2507 continue;
2508
2509 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002510 if (FieldClassDecl->isInvalidDecl())
2511 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00002512 if (FieldClassDecl->hasTrivialDestructor())
2513 continue;
2514
Douglas Gregordb89f282010-07-01 22:47:18 +00002515 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002516 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00002517 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002518 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00002519 << Field->getDeclName()
2520 << FieldType);
2521
John McCallef027fe2010-03-16 21:39:52 +00002522 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00002523 }
2524
John McCall58e6f342010-03-16 05:22:47 +00002525 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
2526
Anders Carlsson9f853df2009-11-17 04:44:12 +00002527 // Bases.
2528 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2529 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00002530 // Bases are always records in a well-formed non-dependent class.
2531 const RecordType *RT = Base->getType()->getAs<RecordType>();
2532
2533 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00002534 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00002535 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00002536
John McCall58e6f342010-03-16 05:22:47 +00002537 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002538 // If our base class is invalid, we probably can't get its dtor anyway.
2539 if (BaseClassDecl->isInvalidDecl())
2540 continue;
2541 // Ignore trivial destructors.
Anders Carlsson9f853df2009-11-17 04:44:12 +00002542 if (BaseClassDecl->hasTrivialDestructor())
2543 continue;
John McCall58e6f342010-03-16 05:22:47 +00002544
Douglas Gregordb89f282010-07-01 22:47:18 +00002545 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002546 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00002547
2548 // FIXME: caret should be on the start of the class name
2549 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002550 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00002551 << Base->getType()
2552 << Base->getSourceRange());
Anders Carlsson9f853df2009-11-17 04:44:12 +00002553
John McCallef027fe2010-03-16 21:39:52 +00002554 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00002555 }
2556
2557 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002558 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2559 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00002560
2561 // Bases are always records in a well-formed non-dependent class.
2562 const RecordType *RT = VBase->getType()->getAs<RecordType>();
2563
2564 // Ignore direct virtual bases.
2565 if (DirectVirtualBases.count(RT))
2566 continue;
2567
John McCall58e6f342010-03-16 05:22:47 +00002568 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002569 // If our base class is invalid, we probably can't get its dtor anyway.
2570 if (BaseClassDecl->isInvalidDecl())
2571 continue;
2572 // Ignore trivial destructors.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002573 if (BaseClassDecl->hasTrivialDestructor())
2574 continue;
John McCall58e6f342010-03-16 05:22:47 +00002575
Douglas Gregordb89f282010-07-01 22:47:18 +00002576 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002577 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00002578 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002579 PDiag(diag::err_access_dtor_vbase)
John McCall58e6f342010-03-16 05:22:47 +00002580 << VBase->getType());
2581
John McCallef027fe2010-03-16 21:39:52 +00002582 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002583 }
2584}
2585
John McCalld226f652010-08-21 09:40:31 +00002586void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00002587 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00002588 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002589
Mike Stump1eb44332009-09-09 15:08:12 +00002590 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002591 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Sean Huntcbb67482011-01-08 20:30:50 +00002592 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00002593}
2594
Mike Stump1eb44332009-09-09 15:08:12 +00002595bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00002596 unsigned DiagID, AbstractDiagSelID SelID) {
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002597 if (SelID == -1)
John McCall94c3b562010-08-18 09:41:07 +00002598 return RequireNonAbstractType(Loc, T, PDiag(DiagID));
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002599 else
John McCall94c3b562010-08-18 09:41:07 +00002600 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
Mike Stump1eb44332009-09-09 15:08:12 +00002601}
2602
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002603bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00002604 const PartialDiagnostic &PD) {
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002605 if (!getLangOptions().CPlusPlus)
2606 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002607
Anders Carlsson11f21a02009-03-23 19:10:31 +00002608 if (const ArrayType *AT = Context.getAsArrayType(T))
John McCall94c3b562010-08-18 09:41:07 +00002609 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Mike Stump1eb44332009-09-09 15:08:12 +00002610
Ted Kremenek6217b802009-07-29 21:53:49 +00002611 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002612 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00002613 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002614 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00002615
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002616 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
John McCall94c3b562010-08-18 09:41:07 +00002617 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002618 }
Mike Stump1eb44332009-09-09 15:08:12 +00002619
Ted Kremenek6217b802009-07-29 21:53:49 +00002620 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002621 if (!RT)
2622 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002623
John McCall86ff3082010-02-04 22:26:26 +00002624 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002625
John McCall94c3b562010-08-18 09:41:07 +00002626 // We can't answer whether something is abstract until it has a
2627 // definition. If it's currently being defined, we'll walk back
2628 // over all the declarations when we have a full definition.
2629 const CXXRecordDecl *Def = RD->getDefinition();
2630 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00002631 return false;
2632
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002633 if (!RD->isAbstract())
2634 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002635
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002636 Diag(Loc, PD) << RD->getDeclName();
John McCall94c3b562010-08-18 09:41:07 +00002637 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00002638
John McCall94c3b562010-08-18 09:41:07 +00002639 return true;
2640}
2641
2642void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
2643 // Check if we've already emitted the list of pure virtual functions
2644 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002645 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00002646 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002647
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002648 CXXFinalOverriderMap FinalOverriders;
2649 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00002650
Anders Carlssonffdb2d22010-06-03 01:00:02 +00002651 // Keep a set of seen pure methods so we won't diagnose the same method
2652 // more than once.
2653 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
2654
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002655 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2656 MEnd = FinalOverriders.end();
2657 M != MEnd;
2658 ++M) {
2659 for (OverridingMethods::iterator SO = M->second.begin(),
2660 SOEnd = M->second.end();
2661 SO != SOEnd; ++SO) {
2662 // C++ [class.abstract]p4:
2663 // A class is abstract if it contains or inherits at least one
2664 // pure virtual function for which the final overrider is pure
2665 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00002666
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002667 //
2668 if (SO->second.size() != 1)
2669 continue;
2670
2671 if (!SO->second.front().Method->isPure())
2672 continue;
2673
Anders Carlssonffdb2d22010-06-03 01:00:02 +00002674 if (!SeenPureMethods.insert(SO->second.front().Method))
2675 continue;
2676
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002677 Diag(SO->second.front().Method->getLocation(),
2678 diag::note_pure_virtual_function)
Chandler Carruth45f11b72011-02-18 23:59:51 +00002679 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002680 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002681 }
2682
2683 if (!PureVirtualClassDiagSet)
2684 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2685 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002686}
2687
Anders Carlsson8211eff2009-03-24 01:19:16 +00002688namespace {
John McCall94c3b562010-08-18 09:41:07 +00002689struct AbstractUsageInfo {
2690 Sema &S;
2691 CXXRecordDecl *Record;
2692 CanQualType AbstractType;
2693 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00002694
John McCall94c3b562010-08-18 09:41:07 +00002695 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
2696 : S(S), Record(Record),
2697 AbstractType(S.Context.getCanonicalType(
2698 S.Context.getTypeDeclType(Record))),
2699 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00002700
John McCall94c3b562010-08-18 09:41:07 +00002701 void DiagnoseAbstractType() {
2702 if (Invalid) return;
2703 S.DiagnoseAbstractType(Record);
2704 Invalid = true;
2705 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00002706
John McCall94c3b562010-08-18 09:41:07 +00002707 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
2708};
2709
2710struct CheckAbstractUsage {
2711 AbstractUsageInfo &Info;
2712 const NamedDecl *Ctx;
2713
2714 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
2715 : Info(Info), Ctx(Ctx) {}
2716
2717 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2718 switch (TL.getTypeLocClass()) {
2719#define ABSTRACT_TYPELOC(CLASS, PARENT)
2720#define TYPELOC(CLASS, PARENT) \
2721 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
2722#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00002723 }
John McCall94c3b562010-08-18 09:41:07 +00002724 }
Mike Stump1eb44332009-09-09 15:08:12 +00002725
John McCall94c3b562010-08-18 09:41:07 +00002726 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2727 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
2728 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor70191862011-02-22 23:21:06 +00002729 if (!TL.getArg(I))
2730 continue;
2731
John McCall94c3b562010-08-18 09:41:07 +00002732 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
2733 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00002734 }
John McCall94c3b562010-08-18 09:41:07 +00002735 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00002736
John McCall94c3b562010-08-18 09:41:07 +00002737 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2738 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
2739 }
Mike Stump1eb44332009-09-09 15:08:12 +00002740
John McCall94c3b562010-08-18 09:41:07 +00002741 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2742 // Visit the type parameters from a permissive context.
2743 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2744 TemplateArgumentLoc TAL = TL.getArgLoc(I);
2745 if (TAL.getArgument().getKind() == TemplateArgument::Type)
2746 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
2747 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
2748 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00002749 }
John McCall94c3b562010-08-18 09:41:07 +00002750 }
Mike Stump1eb44332009-09-09 15:08:12 +00002751
John McCall94c3b562010-08-18 09:41:07 +00002752 // Visit pointee types from a permissive context.
2753#define CheckPolymorphic(Type) \
2754 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
2755 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
2756 }
2757 CheckPolymorphic(PointerTypeLoc)
2758 CheckPolymorphic(ReferenceTypeLoc)
2759 CheckPolymorphic(MemberPointerTypeLoc)
2760 CheckPolymorphic(BlockPointerTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00002761
John McCall94c3b562010-08-18 09:41:07 +00002762 /// Handle all the types we haven't given a more specific
2763 /// implementation for above.
2764 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2765 // Every other kind of type that we haven't called out already
2766 // that has an inner type is either (1) sugar or (2) contains that
2767 // inner type in some way as a subobject.
2768 if (TypeLoc Next = TL.getNextTypeLoc())
2769 return Visit(Next, Sel);
2770
2771 // If there's no inner type and we're in a permissive context,
2772 // don't diagnose.
2773 if (Sel == Sema::AbstractNone) return;
2774
2775 // Check whether the type matches the abstract type.
2776 QualType T = TL.getType();
2777 if (T->isArrayType()) {
2778 Sel = Sema::AbstractArrayType;
2779 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00002780 }
John McCall94c3b562010-08-18 09:41:07 +00002781 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
2782 if (CT != Info.AbstractType) return;
2783
2784 // It matched; do some magic.
2785 if (Sel == Sema::AbstractArrayType) {
2786 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
2787 << T << TL.getSourceRange();
2788 } else {
2789 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
2790 << Sel << T << TL.getSourceRange();
2791 }
2792 Info.DiagnoseAbstractType();
2793 }
2794};
2795
2796void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
2797 Sema::AbstractDiagSelID Sel) {
2798 CheckAbstractUsage(*this, D).Visit(TL, Sel);
2799}
2800
2801}
2802
2803/// Check for invalid uses of an abstract type in a method declaration.
2804static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2805 CXXMethodDecl *MD) {
2806 // No need to do the check on definitions, which require that
2807 // the return/param types be complete.
Sean Hunt10620eb2011-05-06 20:44:56 +00002808 if (MD->doesThisDeclarationHaveABody())
John McCall94c3b562010-08-18 09:41:07 +00002809 return;
2810
2811 // For safety's sake, just ignore it if we don't have type source
2812 // information. This should never happen for non-implicit methods,
2813 // but...
2814 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
2815 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
2816}
2817
2818/// Check for invalid uses of an abstract type within a class definition.
2819static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2820 CXXRecordDecl *RD) {
2821 for (CXXRecordDecl::decl_iterator
2822 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
2823 Decl *D = *I;
2824 if (D->isImplicit()) continue;
2825
2826 // Methods and method templates.
2827 if (isa<CXXMethodDecl>(D)) {
2828 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
2829 } else if (isa<FunctionTemplateDecl>(D)) {
2830 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
2831 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
2832
2833 // Fields and static variables.
2834 } else if (isa<FieldDecl>(D)) {
2835 FieldDecl *FD = cast<FieldDecl>(D);
2836 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
2837 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
2838 } else if (isa<VarDecl>(D)) {
2839 VarDecl *VD = cast<VarDecl>(D);
2840 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
2841 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
2842
2843 // Nested classes and class templates.
2844 } else if (isa<CXXRecordDecl>(D)) {
2845 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
2846 } else if (isa<ClassTemplateDecl>(D)) {
2847 CheckAbstractClassUsage(Info,
2848 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
2849 }
2850 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00002851}
2852
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002853/// \brief Perform semantic checks on a class definition that has been
2854/// completing, introducing implicitly-declared members, checking for
2855/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00002856void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00002857 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002858 return;
2859
John McCall94c3b562010-08-18 09:41:07 +00002860 if (Record->isAbstract() && !Record->isInvalidDecl()) {
2861 AbstractUsageInfo Info(*this, Record);
2862 CheckAbstractClassUsage(Info, Record);
2863 }
Douglas Gregor325e5932010-04-15 00:00:53 +00002864
2865 // If this is not an aggregate type and has no user-declared constructor,
2866 // complain about any non-static data members of reference or const scalar
2867 // type, since they will never get initializers.
2868 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
2869 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
2870 bool Complained = false;
2871 for (RecordDecl::field_iterator F = Record->field_begin(),
2872 FEnd = Record->field_end();
2873 F != FEnd; ++F) {
2874 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00002875 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00002876 if (!Complained) {
2877 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
2878 << Record->getTagKind() << Record;
2879 Complained = true;
2880 }
2881
2882 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
2883 << F->getType()->isReferenceType()
2884 << F->getDeclName();
2885 }
2886 }
2887 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002888
Anders Carlssona5c6c2a2011-01-25 18:08:22 +00002889 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002890 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00002891
2892 if (Record->getIdentifier()) {
2893 // C++ [class.mem]p13:
2894 // If T is the name of a class, then each of the following shall have a
2895 // name different from T:
2896 // - every member of every anonymous union that is a member of class T.
2897 //
2898 // C++ [class.mem]p14:
2899 // In addition, if class T has a user-declared constructor (12.1), every
2900 // non-static data member of class T shall have a name different from T.
2901 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
Francois Pichet87c2e122010-11-21 06:08:52 +00002902 R.first != R.second; ++R.first) {
2903 NamedDecl *D = *R.first;
2904 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
2905 isa<IndirectFieldDecl>(D)) {
2906 Diag(D->getLocation(), diag::err_member_name_of_class)
2907 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00002908 break;
2909 }
Francois Pichet87c2e122010-11-21 06:08:52 +00002910 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00002911 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00002912
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00002913 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregorf4b793c2011-02-19 19:14:36 +00002914 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00002915 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00002916 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00002917 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
2918 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
2919 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00002920
2921 // See if a method overloads virtual methods in a base
2922 /// class without overriding any.
2923 if (!Record->isDependentType()) {
2924 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
2925 MEnd = Record->method_end();
2926 M != MEnd; ++M) {
Argyrios Kyrtzidis0266aa32011-03-03 22:58:57 +00002927 if (!(*M)->isStatic())
2928 DiagnoseHiddenVirtualMethods(Record, *M);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00002929 }
2930 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00002931
2932 // Declare inherited constructors. We do this eagerly here because:
2933 // - The standard requires an eager diagnostic for conflicting inherited
2934 // constructors from different classes.
2935 // - The lazy declaration of the other implicit constructors is so as to not
2936 // waste space and performance on classes that are not meant to be
2937 // instantiated (e.g. meta-functions). This doesn't apply to classes that
2938 // have inherited constructors.
Sebastian Redlcaa35e42011-03-12 13:44:32 +00002939 DeclareInheritedConstructors(Record);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00002940}
2941
2942/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramerc54061a2011-03-04 13:12:48 +00002943namespace {
2944 struct FindHiddenVirtualMethodData {
2945 Sema *S;
2946 CXXMethodDecl *Method;
2947 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
2948 llvm::SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
2949 };
2950}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00002951
2952/// \brief Member lookup function that determines whether a given C++
2953/// method overloads virtual methods in a base class without overriding any,
2954/// to be used with CXXRecordDecl::lookupInBases().
2955static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
2956 CXXBasePath &Path,
2957 void *UserData) {
2958 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
2959
2960 FindHiddenVirtualMethodData &Data
2961 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
2962
2963 DeclarationName Name = Data.Method->getDeclName();
2964 assert(Name.getNameKind() == DeclarationName::Identifier);
2965
2966 bool foundSameNameMethod = false;
2967 llvm::SmallVector<CXXMethodDecl *, 8> overloadedMethods;
2968 for (Path.Decls = BaseRecord->lookup(Name);
2969 Path.Decls.first != Path.Decls.second;
2970 ++Path.Decls.first) {
2971 NamedDecl *D = *Path.Decls.first;
2972 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00002973 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00002974 foundSameNameMethod = true;
2975 // Interested only in hidden virtual methods.
2976 if (!MD->isVirtual())
2977 continue;
2978 // If the method we are checking overrides a method from its base
2979 // don't warn about the other overloaded methods.
2980 if (!Data.S->IsOverload(Data.Method, MD, false))
2981 return true;
2982 // Collect the overload only if its hidden.
2983 if (!Data.OverridenAndUsingBaseMethods.count(MD))
2984 overloadedMethods.push_back(MD);
2985 }
2986 }
2987
2988 if (foundSameNameMethod)
2989 Data.OverloadedMethods.append(overloadedMethods.begin(),
2990 overloadedMethods.end());
2991 return foundSameNameMethod;
2992}
2993
2994/// \brief See if a method overloads virtual methods in a base class without
2995/// overriding any.
2996void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
2997 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
2998 MD->getLocation()) == Diagnostic::Ignored)
2999 return;
3000 if (MD->getDeclName().getNameKind() != DeclarationName::Identifier)
3001 return;
3002
3003 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
3004 /*bool RecordPaths=*/false,
3005 /*bool DetectVirtual=*/false);
3006 FindHiddenVirtualMethodData Data;
3007 Data.Method = MD;
3008 Data.S = this;
3009
3010 // Keep the base methods that were overriden or introduced in the subclass
3011 // by 'using' in a set. A base method not in this set is hidden.
3012 for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
3013 res.first != res.second; ++res.first) {
3014 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first))
3015 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
3016 E = MD->end_overridden_methods();
3017 I != E; ++I)
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00003018 Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003019 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
3020 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl()))
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00003021 Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003022 }
3023
3024 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
3025 !Data.OverloadedMethods.empty()) {
3026 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
3027 << MD << (Data.OverloadedMethods.size() > 1);
3028
3029 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
3030 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
3031 Diag(overloadedMD->getLocation(),
3032 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
3033 }
3034 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003035}
3036
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00003037void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00003038 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00003039 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00003040 SourceLocation RBrac,
3041 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00003042 if (!TagDecl)
3043 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003044
Douglas Gregor42af25f2009-05-11 19:58:34 +00003045 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003046
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00003047 ActOnFields(S, RLoc, TagDecl,
John McCalld226f652010-08-21 09:40:31 +00003048 // strict aliasing violation!
3049 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00003050 FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00003051
Douglas Gregor23c94db2010-07-02 17:43:08 +00003052 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00003053 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00003054}
3055
Douglas Gregord92ec472010-07-01 05:10:53 +00003056namespace {
3057 /// \brief Helper class that collects exception specifications for
3058 /// implicitly-declared special member functions.
3059 class ImplicitExceptionSpecification {
3060 ASTContext &Context;
Sebastian Redl60618fa2011-03-12 11:50:43 +00003061 // We order exception specifications thus:
3062 // noexcept is the most restrictive, but is only used in C++0x.
3063 // throw() comes next.
3064 // Then a throw(collected exceptions)
3065 // Finally no specification.
3066 // throw(...) is used instead if any called function uses it.
3067 ExceptionSpecificationType ComputedEST;
Douglas Gregord92ec472010-07-01 05:10:53 +00003068 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
3069 llvm::SmallVector<QualType, 4> Exceptions;
Sebastian Redl60618fa2011-03-12 11:50:43 +00003070
3071 void ClearExceptions() {
3072 ExceptionsSeen.clear();
3073 Exceptions.clear();
3074 }
3075
Douglas Gregord92ec472010-07-01 05:10:53 +00003076 public:
3077 explicit ImplicitExceptionSpecification(ASTContext &Context)
Sebastian Redl60618fa2011-03-12 11:50:43 +00003078 : Context(Context), ComputedEST(EST_BasicNoexcept) {
3079 if (!Context.getLangOptions().CPlusPlus0x)
3080 ComputedEST = EST_DynamicNone;
Douglas Gregord92ec472010-07-01 05:10:53 +00003081 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00003082
3083 /// \brief Get the computed exception specification type.
3084 ExceptionSpecificationType getExceptionSpecType() const {
3085 assert(ComputedEST != EST_ComputedNoexcept &&
3086 "noexcept(expr) should not be a possible result");
3087 return ComputedEST;
Douglas Gregord92ec472010-07-01 05:10:53 +00003088 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00003089
Douglas Gregord92ec472010-07-01 05:10:53 +00003090 /// \brief The number of exceptions in the exception specification.
3091 unsigned size() const { return Exceptions.size(); }
Sebastian Redl60618fa2011-03-12 11:50:43 +00003092
Douglas Gregord92ec472010-07-01 05:10:53 +00003093 /// \brief The set of exceptions in the exception specification.
3094 const QualType *data() const { return Exceptions.data(); }
Sebastian Redl60618fa2011-03-12 11:50:43 +00003095
3096 /// \brief Integrate another called method into the collected data.
Douglas Gregord92ec472010-07-01 05:10:53 +00003097 void CalledDecl(CXXMethodDecl *Method) {
Sebastian Redl60618fa2011-03-12 11:50:43 +00003098 // If we have an MSAny spec already, don't bother.
3099 if (!Method || ComputedEST == EST_MSAny)
Douglas Gregord92ec472010-07-01 05:10:53 +00003100 return;
Sebastian Redl60618fa2011-03-12 11:50:43 +00003101
Douglas Gregord92ec472010-07-01 05:10:53 +00003102 const FunctionProtoType *Proto
3103 = Method->getType()->getAs<FunctionProtoType>();
Sebastian Redl60618fa2011-03-12 11:50:43 +00003104
3105 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
3106
Douglas Gregord92ec472010-07-01 05:10:53 +00003107 // If this function can throw any exceptions, make a note of that.
Sebastian Redl60618fa2011-03-12 11:50:43 +00003108 if (EST == EST_MSAny || EST == EST_None) {
3109 ClearExceptions();
3110 ComputedEST = EST;
Douglas Gregord92ec472010-07-01 05:10:53 +00003111 return;
3112 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00003113
3114 // If this function has a basic noexcept, it doesn't affect the outcome.
3115 if (EST == EST_BasicNoexcept)
3116 return;
3117
3118 // If we have a throw-all spec at this point, ignore the function.
3119 if (ComputedEST == EST_None)
3120 return;
3121
3122 // If we're still at noexcept(true) and there's a nothrow() callee,
3123 // change to that specification.
3124 if (EST == EST_DynamicNone) {
3125 if (ComputedEST == EST_BasicNoexcept)
3126 ComputedEST = EST_DynamicNone;
3127 return;
3128 }
3129
3130 // Check out noexcept specs.
3131 if (EST == EST_ComputedNoexcept) {
Sebastian Redl8026f6d2011-03-13 17:09:40 +00003132 FunctionProtoType::NoexceptResult NR = Proto->getNoexceptSpec(Context);
Sebastian Redl60618fa2011-03-12 11:50:43 +00003133 assert(NR != FunctionProtoType::NR_NoNoexcept &&
3134 "Must have noexcept result for EST_ComputedNoexcept.");
3135 assert(NR != FunctionProtoType::NR_Dependent &&
3136 "Should not generate implicit declarations for dependent cases, "
3137 "and don't know how to handle them anyway.");
3138
3139 // noexcept(false) -> no spec on the new function
3140 if (NR == FunctionProtoType::NR_Throw) {
3141 ClearExceptions();
3142 ComputedEST = EST_None;
3143 }
3144 // noexcept(true) won't change anything either.
3145 return;
3146 }
3147
3148 assert(EST == EST_Dynamic && "EST case not considered earlier.");
3149 assert(ComputedEST != EST_None &&
3150 "Shouldn't collect exceptions when throw-all is guaranteed.");
3151 ComputedEST = EST_Dynamic;
Douglas Gregord92ec472010-07-01 05:10:53 +00003152 // Record the exceptions in this function's exception specification.
3153 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
3154 EEnd = Proto->exception_end();
Sebastian Redl60618fa2011-03-12 11:50:43 +00003155 E != EEnd; ++E)
Douglas Gregord92ec472010-07-01 05:10:53 +00003156 if (ExceptionsSeen.insert(Context.getCanonicalType(*E)))
3157 Exceptions.push_back(*E);
3158 }
3159 };
3160}
3161
3162
Douglas Gregor396b7cd2008-11-03 17:51:48 +00003163/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
3164/// special functions, such as the default constructor, copy
3165/// constructor, or destructor, to the given C++ class (C++
3166/// [special]p1). This routine can only be executed just before the
3167/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00003168void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00003169 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00003170 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00003171
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00003172 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregor22584312010-07-02 23:41:54 +00003173 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00003174
Douglas Gregora376d102010-07-02 21:50:04 +00003175 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
3176 ++ASTContext::NumImplicitCopyAssignmentOperators;
3177
3178 // If we have a dynamic class, then the copy assignment operator may be
3179 // virtual, so we have to declare it immediately. This ensures that, e.g.,
3180 // it shows up in the right place in the vtable and that we diagnose
3181 // problems with the implicit exception specification.
3182 if (ClassDecl->isDynamicClass())
3183 DeclareImplicitCopyAssignment(ClassDecl);
3184 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00003185
Douglas Gregor4923aa22010-07-02 20:37:36 +00003186 if (!ClassDecl->hasUserDeclaredDestructor()) {
3187 ++ASTContext::NumImplicitDestructors;
3188
3189 // If we have a dynamic class, then the destructor may be virtual, so we
3190 // have to declare the destructor immediately. This ensures that, e.g., it
3191 // shows up in the right place in the vtable and that we diagnose problems
3192 // with the implicit exception specification.
3193 if (ClassDecl->isDynamicClass())
3194 DeclareImplicitDestructor(ClassDecl);
3195 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00003196}
3197
Francois Pichet8387e2a2011-04-22 22:18:13 +00003198void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
3199 if (!D)
3200 return;
3201
3202 int NumParamList = D->getNumTemplateParameterLists();
3203 for (int i = 0; i < NumParamList; i++) {
3204 TemplateParameterList* Params = D->getTemplateParameterList(i);
3205 for (TemplateParameterList::iterator Param = Params->begin(),
3206 ParamEnd = Params->end();
3207 Param != ParamEnd; ++Param) {
3208 NamedDecl *Named = cast<NamedDecl>(*Param);
3209 if (Named->getDeclName()) {
3210 S->AddDecl(Named);
3211 IdResolver.AddDecl(Named);
3212 }
3213 }
3214 }
3215}
3216
John McCalld226f652010-08-21 09:40:31 +00003217void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00003218 if (!D)
3219 return;
3220
3221 TemplateParameterList *Params = 0;
3222 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
3223 Params = Template->getTemplateParameters();
3224 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
3225 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
3226 Params = PartialSpec->getTemplateParameters();
3227 else
Douglas Gregor6569d682009-05-27 23:11:45 +00003228 return;
3229
Douglas Gregor6569d682009-05-27 23:11:45 +00003230 for (TemplateParameterList::iterator Param = Params->begin(),
3231 ParamEnd = Params->end();
3232 Param != ParamEnd; ++Param) {
3233 NamedDecl *Named = cast<NamedDecl>(*Param);
3234 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00003235 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00003236 IdResolver.AddDecl(Named);
3237 }
3238 }
3239}
3240
John McCalld226f652010-08-21 09:40:31 +00003241void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00003242 if (!RecordD) return;
3243 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00003244 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00003245 PushDeclContext(S, Record);
3246}
3247
John McCalld226f652010-08-21 09:40:31 +00003248void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00003249 if (!RecordD) return;
3250 PopDeclContext();
3251}
3252
Douglas Gregor72b505b2008-12-16 21:30:33 +00003253/// ActOnStartDelayedCXXMethodDeclaration - We have completed
3254/// parsing a top-level (non-nested) C++ class, and we are now
3255/// parsing those parts of the given Method declaration that could
3256/// not be parsed earlier (C++ [class.mem]p2), such as default
3257/// arguments. This action should enter the scope of the given
3258/// Method declaration as if we had just parsed the qualified method
3259/// name. However, it should not bring the parameters into scope;
3260/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00003261void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00003262}
3263
3264/// ActOnDelayedCXXMethodParameter - We've already started a delayed
3265/// C++ method declaration. We're (re-)introducing the given
3266/// function parameter into scope for use in parsing later parts of
3267/// the method declaration. For example, we could see an
3268/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00003269void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00003270 if (!ParamD)
3271 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003272
John McCalld226f652010-08-21 09:40:31 +00003273 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00003274
3275 // If this parameter has an unparsed default argument, clear it out
3276 // to make way for the parsed default argument.
3277 if (Param->hasUnparsedDefaultArg())
3278 Param->setDefaultArg(0);
3279
John McCalld226f652010-08-21 09:40:31 +00003280 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00003281 if (Param->getDeclName())
3282 IdResolver.AddDecl(Param);
3283}
3284
3285/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
3286/// processing the delayed method declaration for Method. The method
3287/// declaration is now considered finished. There may be a separate
3288/// ActOnStartOfFunctionDef action later (not necessarily
3289/// immediately!) for this method, if it was also defined inside the
3290/// class body.
John McCalld226f652010-08-21 09:40:31 +00003291void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00003292 if (!MethodD)
3293 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003294
Douglas Gregorefd5bda2009-08-24 11:57:43 +00003295 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00003296
John McCalld226f652010-08-21 09:40:31 +00003297 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00003298
3299 // Now that we have our default arguments, check the constructor
3300 // again. It could produce additional diagnostics or affect whether
3301 // the class has implicitly-declared destructors, among other
3302 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00003303 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
3304 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00003305
3306 // Check the default arguments, which we may have added.
3307 if (!Method->isInvalidDecl())
3308 CheckCXXDefaultArguments(Method);
3309}
3310
Douglas Gregor42a552f2008-11-05 20:51:48 +00003311/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00003312/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00003313/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00003314/// emit diagnostics and set the invalid bit to true. In any case, the type
3315/// will be updated to reflect a well-formed type for the constructor and
3316/// returned.
3317QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00003318 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00003319 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00003320
3321 // C++ [class.ctor]p3:
3322 // A constructor shall not be virtual (10.3) or static (9.4). A
3323 // constructor can be invoked for a const, volatile or const
3324 // volatile object. A constructor shall not be declared const,
3325 // volatile, or const volatile (9.3.2).
3326 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00003327 if (!D.isInvalidType())
3328 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
3329 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
3330 << SourceRange(D.getIdentifierLoc());
3331 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00003332 }
John McCalld931b082010-08-26 03:08:43 +00003333 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00003334 if (!D.isInvalidType())
3335 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
3336 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
3337 << SourceRange(D.getIdentifierLoc());
3338 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00003339 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00003340 }
Mike Stump1eb44332009-09-09 15:08:12 +00003341
Abramo Bagnara075f8f12010-12-10 16:29:40 +00003342 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00003343 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00003344 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003345 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
3346 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00003347 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003348 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
3349 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00003350 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003351 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
3352 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00003353 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00003354 }
Mike Stump1eb44332009-09-09 15:08:12 +00003355
Douglas Gregorc938c162011-01-26 05:01:58 +00003356 // C++0x [class.ctor]p4:
3357 // A constructor shall not be declared with a ref-qualifier.
3358 if (FTI.hasRefQualifier()) {
3359 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
3360 << FTI.RefQualifierIsLValueRef
3361 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
3362 D.setInvalidType();
3363 }
3364
Douglas Gregor42a552f2008-11-05 20:51:48 +00003365 // Rebuild the function type "R" without any type qualifiers (in
3366 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00003367 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00003368 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00003369 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
3370 return R;
3371
3372 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3373 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00003374 EPI.RefQualifier = RQ_None;
3375
Chris Lattner65401802009-04-25 08:28:21 +00003376 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00003377 Proto->getNumArgs(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00003378}
3379
Douglas Gregor72b505b2008-12-16 21:30:33 +00003380/// CheckConstructor - Checks a fully-formed constructor for
3381/// well-formedness, issuing any diagnostics required. Returns true if
3382/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00003383void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00003384 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00003385 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
3386 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00003387 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00003388
3389 // C++ [class.copy]p3:
3390 // A declaration of a constructor for a class X is ill-formed if
3391 // its first parameter is of type (optionally cv-qualified) X and
3392 // either there are no other parameters or else all other
3393 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00003394 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00003395 ((Constructor->getNumParams() == 1) ||
3396 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00003397 Constructor->getParamDecl(1)->hasDefaultArg())) &&
3398 Constructor->getTemplateSpecializationKind()
3399 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00003400 QualType ParamType = Constructor->getParamDecl(0)->getType();
3401 QualType ClassTy = Context.getTagDeclType(ClassDecl);
3402 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00003403 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00003404 const char *ConstRef
3405 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
3406 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00003407 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00003408 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00003409
3410 // FIXME: Rather that making the constructor invalid, we should endeavor
3411 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00003412 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00003413 }
3414 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00003415}
3416
John McCall15442822010-08-04 01:04:25 +00003417/// CheckDestructor - Checks a fully-formed destructor definition for
3418/// well-formedness, issuing any diagnostics required. Returns true
3419/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00003420bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00003421 CXXRecordDecl *RD = Destructor->getParent();
3422
3423 if (Destructor->isVirtual()) {
3424 SourceLocation Loc;
3425
3426 if (!Destructor->isImplicit())
3427 Loc = Destructor->getLocation();
3428 else
3429 Loc = RD->getLocation();
3430
3431 // If we have a virtual destructor, look up the deallocation function
3432 FunctionDecl *OperatorDelete = 0;
3433 DeclarationName Name =
3434 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00003435 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00003436 return true;
John McCall5efd91a2010-07-03 18:33:00 +00003437
3438 MarkDeclarationReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00003439
3440 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00003441 }
Anders Carlsson37909802009-11-30 21:24:50 +00003442
3443 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00003444}
3445
Mike Stump1eb44332009-09-09 15:08:12 +00003446static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00003447FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
3448 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
3449 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00003450 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00003451}
3452
Douglas Gregor42a552f2008-11-05 20:51:48 +00003453/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
3454/// the well-formednes of the destructor declarator @p D with type @p
3455/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00003456/// emit diagnostics and set the declarator to invalid. Even if this happens,
3457/// will be updated to reflect a well-formed type for the destructor and
3458/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00003459QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00003460 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00003461 // C++ [class.dtor]p1:
3462 // [...] A typedef-name that names a class is a class-name
3463 // (7.1.3); however, a typedef-name that names a class shall not
3464 // be used as the identifier in the declarator for a destructor
3465 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00003466 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smith162e1c12011-04-15 14:24:37 +00003467 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner65401802009-04-25 08:28:21 +00003468 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smith162e1c12011-04-15 14:24:37 +00003469 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00003470 else if (const TemplateSpecializationType *TST =
3471 DeclaratorType->getAs<TemplateSpecializationType>())
3472 if (TST->isTypeAlias())
3473 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
3474 << DeclaratorType << 1;
Douglas Gregor42a552f2008-11-05 20:51:48 +00003475
3476 // C++ [class.dtor]p2:
3477 // A destructor is used to destroy objects of its class type. A
3478 // destructor takes no parameters, and no return type can be
3479 // specified for it (not even void). The address of a destructor
3480 // shall not be taken. A destructor shall not be static. A
3481 // destructor can be invoked for a const, volatile or const
3482 // volatile object. A destructor shall not be declared const,
3483 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00003484 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00003485 if (!D.isInvalidType())
3486 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
3487 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00003488 << SourceRange(D.getIdentifierLoc())
3489 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
3490
John McCalld931b082010-08-26 03:08:43 +00003491 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00003492 }
Chris Lattner65401802009-04-25 08:28:21 +00003493 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00003494 // Destructors don't have return types, but the parser will
3495 // happily parse something like:
3496 //
3497 // class X {
3498 // float ~X();
3499 // };
3500 //
3501 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003502 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
3503 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3504 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00003505 }
Mike Stump1eb44332009-09-09 15:08:12 +00003506
Abramo Bagnara075f8f12010-12-10 16:29:40 +00003507 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00003508 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00003509 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003510 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3511 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00003512 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003513 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3514 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00003515 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003516 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3517 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00003518 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00003519 }
3520
Douglas Gregorc938c162011-01-26 05:01:58 +00003521 // C++0x [class.dtor]p2:
3522 // A destructor shall not be declared with a ref-qualifier.
3523 if (FTI.hasRefQualifier()) {
3524 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
3525 << FTI.RefQualifierIsLValueRef
3526 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
3527 D.setInvalidType();
3528 }
3529
Douglas Gregor42a552f2008-11-05 20:51:48 +00003530 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00003531 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00003532 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
3533
3534 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00003535 FTI.freeArgs();
3536 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00003537 }
3538
Mike Stump1eb44332009-09-09 15:08:12 +00003539 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00003540 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00003541 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00003542 D.setInvalidType();
3543 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00003544
3545 // Rebuild the function type "R" without any type qualifiers or
3546 // parameters (in case any of the errors above fired) and with
3547 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00003548 // types.
John McCalle23cf432010-12-14 08:05:40 +00003549 if (!D.isInvalidType())
3550 return R;
3551
Douglas Gregord92ec472010-07-01 05:10:53 +00003552 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00003553 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3554 EPI.Variadic = false;
3555 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00003556 EPI.RefQualifier = RQ_None;
John McCalle23cf432010-12-14 08:05:40 +00003557 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00003558}
3559
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003560/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
3561/// well-formednes of the conversion function declarator @p D with
3562/// type @p R. If there are any errors in the declarator, this routine
3563/// will emit diagnostics and return true. Otherwise, it will return
3564/// false. Either way, the type @p R will be updated to reflect a
3565/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00003566void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00003567 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003568 // C++ [class.conv.fct]p1:
3569 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00003570 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00003571 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00003572 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00003573 if (!D.isInvalidType())
3574 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
3575 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
3576 << SourceRange(D.getIdentifierLoc());
3577 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00003578 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003579 }
John McCalla3f81372010-04-13 00:04:31 +00003580
3581 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
3582
Chris Lattner6e475012009-04-25 08:35:12 +00003583 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003584 // Conversion functions don't have return types, but the parser will
3585 // happily parse something like:
3586 //
3587 // class X {
3588 // float operator bool();
3589 // };
3590 //
3591 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003592 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
3593 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3594 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00003595 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003596 }
3597
John McCalla3f81372010-04-13 00:04:31 +00003598 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
3599
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003600 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00003601 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003602 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
3603
3604 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00003605 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00003606 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00003607 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003608 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00003609 D.setInvalidType();
3610 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003611
John McCalla3f81372010-04-13 00:04:31 +00003612 // Diagnose "&operator bool()" and other such nonsense. This
3613 // is actually a gcc extension which we don't support.
3614 if (Proto->getResultType() != ConvType) {
3615 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
3616 << Proto->getResultType();
3617 D.setInvalidType();
3618 ConvType = Proto->getResultType();
3619 }
3620
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003621 // C++ [class.conv.fct]p4:
3622 // The conversion-type-id shall not represent a function type nor
3623 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003624 if (ConvType->isArrayType()) {
3625 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
3626 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00003627 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003628 } else if (ConvType->isFunctionType()) {
3629 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
3630 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00003631 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003632 }
3633
3634 // Rebuild the function type "R" without any parameters (in case any
3635 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00003636 // return type.
John McCalle23cf432010-12-14 08:05:40 +00003637 if (D.isInvalidType())
3638 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003639
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003640 // C++0x explicit conversion operators.
3641 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump1eb44332009-09-09 15:08:12 +00003642 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003643 diag::warn_explicit_conversion_functions)
3644 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003645}
3646
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003647/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
3648/// the declaration of the given C++ conversion function. This routine
3649/// is responsible for recording the conversion function in the C++
3650/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00003651Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003652 assert(Conversion && "Expected to receive a conversion function declaration");
3653
Douglas Gregor9d350972008-12-12 08:25:50 +00003654 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003655
3656 // Make sure we aren't redeclaring the conversion function.
3657 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003658
3659 // C++ [class.conv.fct]p1:
3660 // [...] A conversion function is never used to convert a
3661 // (possibly cv-qualified) object to the (possibly cv-qualified)
3662 // same object type (or a reference to it), to a (possibly
3663 // cv-qualified) base class of that type (or a reference to it),
3664 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00003665 // FIXME: Suppress this warning if the conversion function ends up being a
3666 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00003667 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003668 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00003669 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003670 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00003671 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
3672 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00003673 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00003674 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003675 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
3676 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00003677 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00003678 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003679 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00003680 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00003681 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003682 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00003683 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00003684 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003685 }
3686
Douglas Gregore80622f2010-09-29 04:25:11 +00003687 if (FunctionTemplateDecl *ConversionTemplate
3688 = Conversion->getDescribedFunctionTemplate())
3689 return ConversionTemplate;
3690
John McCalld226f652010-08-21 09:40:31 +00003691 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003692}
3693
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003694//===----------------------------------------------------------------------===//
3695// Namespace Handling
3696//===----------------------------------------------------------------------===//
3697
John McCallea318642010-08-26 09:15:37 +00003698
3699
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003700/// ActOnStartNamespaceDef - This is called at the start of a namespace
3701/// definition.
John McCalld226f652010-08-21 09:40:31 +00003702Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00003703 SourceLocation InlineLoc,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00003704 SourceLocation NamespaceLoc,
John McCallea318642010-08-26 09:15:37 +00003705 SourceLocation IdentLoc,
3706 IdentifierInfo *II,
3707 SourceLocation LBrace,
3708 AttributeList *AttrList) {
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00003709 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
3710 // For anonymous namespace, take the location of the left brace.
3711 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregor21e09b62010-08-19 20:55:47 +00003712 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00003713 StartLoc, Loc, II);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00003714 Namespc->setInline(InlineLoc.isValid());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003715
3716 Scope *DeclRegionScope = NamespcScope->getParent();
3717
Anders Carlsson2a3503d2010-02-07 01:09:23 +00003718 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
3719
John McCall90f14502010-12-10 02:59:44 +00003720 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
3721 PushNamespaceVisibilityAttr(Attr);
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00003722
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003723 if (II) {
3724 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00003725 // The identifier in an original-namespace-definition shall not
3726 // have been previously defined in the declarative region in
3727 // which the original-namespace-definition appears. The
3728 // identifier in an original-namespace-definition is the name of
3729 // the namespace. Subsequently in that declarative region, it is
3730 // treated as an original-namespace-name.
3731 //
3732 // Since namespace names are unique in their scope, and we don't
3733 // look through using directives, just
3734 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
3735 NamedDecl *PrevDecl = R.first == R.second? 0 : *R.first;
Mike Stump1eb44332009-09-09 15:08:12 +00003736
Douglas Gregor44b43212008-12-11 16:49:14 +00003737 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
3738 // This is an extended namespace definition.
Sebastian Redl4e4d5702010-08-31 00:36:36 +00003739 if (Namespc->isInline() != OrigNS->isInline()) {
3740 // inline-ness must match
3741 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
3742 << Namespc->isInline();
3743 Diag(OrigNS->getLocation(), diag::note_previous_definition);
3744 Namespc->setInvalidDecl();
3745 // Recover by ignoring the new namespace's inline status.
3746 Namespc->setInline(OrigNS->isInline());
3747 }
3748
Douglas Gregor44b43212008-12-11 16:49:14 +00003749 // Attach this namespace decl to the chain of extended namespace
3750 // definitions.
3751 OrigNS->setNextNamespace(Namespc);
3752 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003753
Mike Stump1eb44332009-09-09 15:08:12 +00003754 // Remove the previous declaration from the scope.
John McCalld226f652010-08-21 09:40:31 +00003755 if (DeclRegionScope->isDeclScope(OrigNS)) {
Douglas Gregore267ff32008-12-11 20:41:00 +00003756 IdResolver.RemoveDecl(OrigNS);
John McCalld226f652010-08-21 09:40:31 +00003757 DeclRegionScope->RemoveDecl(OrigNS);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003758 }
Douglas Gregor44b43212008-12-11 16:49:14 +00003759 } else if (PrevDecl) {
3760 // This is an invalid name redefinition.
3761 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
3762 << Namespc->getDeclName();
3763 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3764 Namespc->setInvalidDecl();
3765 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor7adb10f2009-09-15 22:30:29 +00003766 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00003767 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00003768 // This is the first "real" definition of the namespace "std", so update
3769 // our cache of the "std" namespace to point at this definition.
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00003770 if (NamespaceDecl *StdNS = getStdNamespace()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00003771 // We had already defined a dummy namespace "std". Link this new
3772 // namespace definition to the dummy namespace "std".
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00003773 StdNS->setNextNamespace(Namespc);
3774 StdNS->setLocation(IdentLoc);
3775 Namespc->setOriginalNamespace(StdNS->getOriginalNamespace());
Douglas Gregor7adb10f2009-09-15 22:30:29 +00003776 }
3777
3778 // Make our StdNamespace cache point at the first real definition of the
3779 // "std" namespace.
3780 StdNamespace = Namespc;
Mike Stump1eb44332009-09-09 15:08:12 +00003781 }
Douglas Gregor44b43212008-12-11 16:49:14 +00003782
3783 PushOnScopeChains(Namespc, DeclRegionScope);
3784 } else {
John McCall9aeed322009-10-01 00:25:31 +00003785 // Anonymous namespaces.
John McCall5fdd7642009-12-16 02:06:49 +00003786 assert(Namespc->isAnonymousNamespace());
John McCall5fdd7642009-12-16 02:06:49 +00003787
3788 // Link the anonymous namespace into its parent.
3789 NamespaceDecl *PrevDecl;
Sebastian Redl7a126a42010-08-31 00:36:30 +00003790 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00003791 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
3792 PrevDecl = TU->getAnonymousNamespace();
3793 TU->setAnonymousNamespace(Namespc);
3794 } else {
3795 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
3796 PrevDecl = ND->getAnonymousNamespace();
3797 ND->setAnonymousNamespace(Namespc);
3798 }
3799
3800 // Link the anonymous namespace with its previous declaration.
3801 if (PrevDecl) {
3802 assert(PrevDecl->isAnonymousNamespace());
3803 assert(!PrevDecl->getNextNamespace());
3804 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
3805 PrevDecl->setNextNamespace(Namespc);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00003806
3807 if (Namespc->isInline() != PrevDecl->isInline()) {
3808 // inline-ness must match
3809 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
3810 << Namespc->isInline();
3811 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3812 Namespc->setInvalidDecl();
3813 // Recover by ignoring the new namespace's inline status.
3814 Namespc->setInline(PrevDecl->isInline());
3815 }
John McCall5fdd7642009-12-16 02:06:49 +00003816 }
John McCall9aeed322009-10-01 00:25:31 +00003817
Douglas Gregora4181472010-03-24 00:46:35 +00003818 CurContext->addDecl(Namespc);
3819
John McCall9aeed322009-10-01 00:25:31 +00003820 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
3821 // behaves as if it were replaced by
3822 // namespace unique { /* empty body */ }
3823 // using namespace unique;
3824 // namespace unique { namespace-body }
3825 // where all occurrences of 'unique' in a translation unit are
3826 // replaced by the same identifier and this identifier differs
3827 // from all other identifiers in the entire program.
3828
3829 // We just create the namespace with an empty name and then add an
3830 // implicit using declaration, just like the standard suggests.
3831 //
3832 // CodeGen enforces the "universally unique" aspect by giving all
3833 // declarations semantically contained within an anonymous
3834 // namespace internal linkage.
3835
John McCall5fdd7642009-12-16 02:06:49 +00003836 if (!PrevDecl) {
3837 UsingDirectiveDecl* UD
3838 = UsingDirectiveDecl::Create(Context, CurContext,
3839 /* 'using' */ LBrace,
3840 /* 'namespace' */ SourceLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00003841 /* qualifier */ NestedNameSpecifierLoc(),
John McCall5fdd7642009-12-16 02:06:49 +00003842 /* identifier */ SourceLocation(),
3843 Namespc,
3844 /* Ancestor */ CurContext);
3845 UD->setImplicit();
3846 CurContext->addDecl(UD);
3847 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003848 }
3849
3850 // Although we could have an invalid decl (i.e. the namespace name is a
3851 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00003852 // FIXME: We should be able to push Namespc here, so that the each DeclContext
3853 // for the namespace has the declarations that showed up in that particular
3854 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00003855 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00003856 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003857}
3858
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003859/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
3860/// is a namespace alias, returns the namespace it points to.
3861static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
3862 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
3863 return AD->getNamespace();
3864 return dyn_cast_or_null<NamespaceDecl>(D);
3865}
3866
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003867/// ActOnFinishNamespaceDef - This callback is called after a namespace is
3868/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00003869void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003870 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
3871 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00003872 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003873 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00003874 if (Namespc->hasAttr<VisibilityAttr>())
3875 PopPragmaVisibility();
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003876}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003877
John McCall384aff82010-08-25 07:42:41 +00003878CXXRecordDecl *Sema::getStdBadAlloc() const {
3879 return cast_or_null<CXXRecordDecl>(
3880 StdBadAlloc.get(Context.getExternalSource()));
3881}
3882
3883NamespaceDecl *Sema::getStdNamespace() const {
3884 return cast_or_null<NamespaceDecl>(
3885 StdNamespace.get(Context.getExternalSource()));
3886}
3887
Douglas Gregor66992202010-06-29 17:53:46 +00003888/// \brief Retrieve the special "std" namespace, which may require us to
3889/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00003890NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00003891 if (!StdNamespace) {
3892 // The "std" namespace has not yet been defined, so build one implicitly.
3893 StdNamespace = NamespaceDecl::Create(Context,
3894 Context.getTranslationUnitDecl(),
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00003895 SourceLocation(), SourceLocation(),
Douglas Gregor66992202010-06-29 17:53:46 +00003896 &PP.getIdentifierTable().get("std"));
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00003897 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00003898 }
3899
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00003900 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00003901}
3902
Douglas Gregor9172aa62011-03-26 22:25:30 +00003903/// \brief Determine whether a using statement is in a context where it will be
3904/// apply in all contexts.
3905static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
3906 switch (CurContext->getDeclKind()) {
3907 case Decl::TranslationUnit:
3908 return true;
3909 case Decl::LinkageSpec:
3910 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
3911 default:
3912 return false;
3913 }
3914}
3915
John McCalld226f652010-08-21 09:40:31 +00003916Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00003917 SourceLocation UsingLoc,
3918 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003919 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00003920 SourceLocation IdentLoc,
3921 IdentifierInfo *NamespcName,
3922 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00003923 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3924 assert(NamespcName && "Invalid NamespcName.");
3925 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00003926
3927 // This can only happen along a recovery path.
3928 while (S->getFlags() & Scope::TemplateParamScope)
3929 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003930 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00003931
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003932 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00003933 NestedNameSpecifier *Qualifier = 0;
3934 if (SS.isSet())
3935 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3936
Douglas Gregoreb11cd02009-01-14 22:20:51 +00003937 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00003938 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
3939 LookupParsedName(R, S, &SS);
3940 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00003941 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00003942
Douglas Gregor66992202010-06-29 17:53:46 +00003943 if (R.empty()) {
3944 // Allow "using namespace std;" or "using namespace ::std;" even if
3945 // "std" hasn't been defined yet, for GCC compatibility.
3946 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
3947 NamespcName->isStr("std")) {
3948 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00003949 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00003950 R.resolveKind();
3951 }
3952 // Otherwise, attempt typo correction.
3953 else if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
3954 CTC_NoKeywords, 0)) {
3955 if (R.getAsSingle<NamespaceDecl>() ||
3956 R.getAsSingle<NamespaceAliasDecl>()) {
3957 if (DeclContext *DC = computeDeclContext(SS, false))
3958 Diag(IdentLoc, diag::err_using_directive_member_suggest)
3959 << NamespcName << DC << Corrected << SS.getRange()
3960 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3961 else
3962 Diag(IdentLoc, diag::err_using_directive_suggest)
3963 << NamespcName << Corrected
3964 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3965 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
3966 << Corrected;
3967
3968 NamespcName = Corrected.getAsIdentifierInfo();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00003969 } else {
3970 R.clear();
3971 R.setLookupName(NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00003972 }
3973 }
3974 }
3975
John McCallf36e02d2009-10-09 21:13:30 +00003976 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003977 NamedDecl *Named = R.getFoundDecl();
3978 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
3979 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003980 // C++ [namespace.udir]p1:
3981 // A using-directive specifies that the names in the nominated
3982 // namespace can be used in the scope in which the
3983 // using-directive appears after the using-directive. During
3984 // unqualified name lookup (3.4.1), the names appear as if they
3985 // were declared in the nearest enclosing namespace which
3986 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00003987 // namespace. [Note: in this context, "contains" means "contains
3988 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003989
3990 // Find enclosing context containing both using-directive and
3991 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003992 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003993 DeclContext *CommonAncestor = cast<DeclContext>(NS);
3994 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
3995 CommonAncestor = CommonAncestor->getParent();
3996
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003997 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregordb992412011-02-25 16:33:46 +00003998 SS.getWithLocInContext(Context),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003999 IdentLoc, Named, CommonAncestor);
Douglas Gregord6a49bb2011-03-18 16:10:52 +00004000
Douglas Gregor9172aa62011-03-26 22:25:30 +00004001 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Nico Weber21669482011-04-02 19:45:15 +00004002 !SourceMgr.isFromMainFile(SourceMgr.getInstantiationLoc(IdentLoc))) {
Douglas Gregord6a49bb2011-03-18 16:10:52 +00004003 Diag(IdentLoc, diag::warn_using_directive_in_header);
4004 }
4005
Douglas Gregor2a3009a2009-02-03 19:21:40 +00004006 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00004007 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00004008 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00004009 }
4010
Douglas Gregor2a3009a2009-02-03 19:21:40 +00004011 // FIXME: We ignore attributes for now.
John McCalld226f652010-08-21 09:40:31 +00004012 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00004013}
4014
4015void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
4016 // If scope has associated entity, then using directive is at namespace
4017 // or translation unit scope. We add UsingDirectiveDecls, into
4018 // it's lookup structure.
4019 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004020 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00004021 else
4022 // Otherwise it is block-sope. using-directives will affect lookup
4023 // only to the end of scope.
John McCalld226f652010-08-21 09:40:31 +00004024 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00004025}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004026
Douglas Gregor9cfbe482009-06-20 00:51:54 +00004027
John McCalld226f652010-08-21 09:40:31 +00004028Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00004029 AccessSpecifier AS,
4030 bool HasUsingKeyword,
4031 SourceLocation UsingLoc,
4032 CXXScopeSpec &SS,
4033 UnqualifiedId &Name,
4034 AttributeList *AttrList,
4035 bool IsTypeName,
4036 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00004037 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00004038
Douglas Gregor12c118a2009-11-04 16:30:06 +00004039 switch (Name.getKind()) {
4040 case UnqualifiedId::IK_Identifier:
4041 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00004042 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00004043 case UnqualifiedId::IK_ConversionFunctionId:
4044 break;
4045
4046 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00004047 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall604e7f12009-12-08 07:46:18 +00004048 // C++0x inherited constructors.
4049 if (getLangOptions().CPlusPlus0x) break;
4050
Douglas Gregor12c118a2009-11-04 16:30:06 +00004051 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
4052 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00004053 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00004054
4055 case UnqualifiedId::IK_DestructorName:
4056 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
4057 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00004058 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00004059
4060 case UnqualifiedId::IK_TemplateId:
4061 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
4062 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00004063 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00004064 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00004065
4066 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
4067 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00004068 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00004069 return 0;
John McCall604e7f12009-12-08 07:46:18 +00004070
John McCall60fa3cf2009-12-11 02:10:03 +00004071 // Warn about using declarations.
4072 // TODO: store that the declaration was written without 'using' and
4073 // talk about access decls instead of using decls in the
4074 // diagnostics.
4075 if (!HasUsingKeyword) {
4076 UsingLoc = Name.getSourceRange().getBegin();
4077
4078 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00004079 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00004080 }
4081
Douglas Gregor56c04582010-12-16 00:46:58 +00004082 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
4083 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
4084 return 0;
4085
John McCall9488ea12009-11-17 05:59:44 +00004086 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00004087 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00004088 /* IsInstantiation */ false,
4089 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00004090 if (UD)
4091 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00004092
John McCalld226f652010-08-21 09:40:31 +00004093 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00004094}
4095
Douglas Gregor09acc982010-07-07 23:08:52 +00004096/// \brief Determine whether a using declaration considers the given
4097/// declarations as "equivalent", e.g., if they are redeclarations of
4098/// the same entity or are both typedefs of the same type.
4099static bool
4100IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
4101 bool &SuppressRedeclaration) {
4102 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
4103 SuppressRedeclaration = false;
4104 return true;
4105 }
4106
Richard Smith162e1c12011-04-15 14:24:37 +00004107 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
4108 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor09acc982010-07-07 23:08:52 +00004109 SuppressRedeclaration = true;
4110 return Context.hasSameType(TD1->getUnderlyingType(),
4111 TD2->getUnderlyingType());
4112 }
4113
4114 return false;
4115}
4116
4117
John McCall9f54ad42009-12-10 09:41:52 +00004118/// Determines whether to create a using shadow decl for a particular
4119/// decl, given the set of decls existing prior to this using lookup.
4120bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
4121 const LookupResult &Previous) {
4122 // Diagnose finding a decl which is not from a base class of the
4123 // current class. We do this now because there are cases where this
4124 // function will silently decide not to build a shadow decl, which
4125 // will pre-empt further diagnostics.
4126 //
4127 // We don't need to do this in C++0x because we do the check once on
4128 // the qualifier.
4129 //
4130 // FIXME: diagnose the following if we care enough:
4131 // struct A { int foo; };
4132 // struct B : A { using A::foo; };
4133 // template <class T> struct C : A {};
4134 // template <class T> struct D : C<T> { using B::foo; } // <---
4135 // This is invalid (during instantiation) in C++03 because B::foo
4136 // resolves to the using decl in B, which is not a base class of D<T>.
4137 // We can't diagnose it immediately because C<T> is an unknown
4138 // specialization. The UsingShadowDecl in D<T> then points directly
4139 // to A::foo, which will look well-formed when we instantiate.
4140 // The right solution is to not collapse the shadow-decl chain.
4141 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
4142 DeclContext *OrigDC = Orig->getDeclContext();
4143
4144 // Handle enums and anonymous structs.
4145 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
4146 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
4147 while (OrigRec->isAnonymousStructOrUnion())
4148 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
4149
4150 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
4151 if (OrigDC == CurContext) {
4152 Diag(Using->getLocation(),
4153 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregordc355712011-02-25 00:36:19 +00004154 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00004155 Diag(Orig->getLocation(), diag::note_using_decl_target);
4156 return true;
4157 }
4158
Douglas Gregordc355712011-02-25 00:36:19 +00004159 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall9f54ad42009-12-10 09:41:52 +00004160 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregordc355712011-02-25 00:36:19 +00004161 << Using->getQualifier()
John McCall9f54ad42009-12-10 09:41:52 +00004162 << cast<CXXRecordDecl>(CurContext)
Douglas Gregordc355712011-02-25 00:36:19 +00004163 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00004164 Diag(Orig->getLocation(), diag::note_using_decl_target);
4165 return true;
4166 }
4167 }
4168
4169 if (Previous.empty()) return false;
4170
4171 NamedDecl *Target = Orig;
4172 if (isa<UsingShadowDecl>(Target))
4173 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
4174
John McCalld7533ec2009-12-11 02:33:26 +00004175 // If the target happens to be one of the previous declarations, we
4176 // don't have a conflict.
4177 //
4178 // FIXME: but we might be increasing its access, in which case we
4179 // should redeclare it.
4180 NamedDecl *NonTag = 0, *Tag = 0;
4181 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4182 I != E; ++I) {
4183 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00004184 bool Result;
4185 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
4186 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00004187
4188 (isa<TagDecl>(D) ? Tag : NonTag) = D;
4189 }
4190
John McCall9f54ad42009-12-10 09:41:52 +00004191 if (Target->isFunctionOrFunctionTemplate()) {
4192 FunctionDecl *FD;
4193 if (isa<FunctionTemplateDecl>(Target))
4194 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
4195 else
4196 FD = cast<FunctionDecl>(Target);
4197
4198 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00004199 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00004200 case Ovl_Overload:
4201 return false;
4202
4203 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00004204 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00004205 break;
4206
4207 // We found a decl with the exact signature.
4208 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00004209 // If we're in a record, we want to hide the target, so we
4210 // return true (without a diagnostic) to tell the caller not to
4211 // build a shadow decl.
4212 if (CurContext->isRecord())
4213 return true;
4214
4215 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00004216 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00004217 break;
4218 }
4219
4220 Diag(Target->getLocation(), diag::note_using_decl_target);
4221 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
4222 return true;
4223 }
4224
4225 // Target is not a function.
4226
John McCall9f54ad42009-12-10 09:41:52 +00004227 if (isa<TagDecl>(Target)) {
4228 // No conflict between a tag and a non-tag.
4229 if (!Tag) return false;
4230
John McCall41ce66f2009-12-10 19:51:03 +00004231 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00004232 Diag(Target->getLocation(), diag::note_using_decl_target);
4233 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
4234 return true;
4235 }
4236
4237 // No conflict between a tag and a non-tag.
4238 if (!NonTag) return false;
4239
John McCall41ce66f2009-12-10 19:51:03 +00004240 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00004241 Diag(Target->getLocation(), diag::note_using_decl_target);
4242 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
4243 return true;
4244}
4245
John McCall9488ea12009-11-17 05:59:44 +00004246/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00004247UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00004248 UsingDecl *UD,
4249 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00004250
4251 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00004252 NamedDecl *Target = Orig;
4253 if (isa<UsingShadowDecl>(Target)) {
4254 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
4255 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00004256 }
4257
4258 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00004259 = UsingShadowDecl::Create(Context, CurContext,
4260 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00004261 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00004262
4263 Shadow->setAccess(UD->getAccess());
4264 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
4265 Shadow->setInvalidDecl();
4266
John McCall9488ea12009-11-17 05:59:44 +00004267 if (S)
John McCall604e7f12009-12-08 07:46:18 +00004268 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00004269 else
John McCall604e7f12009-12-08 07:46:18 +00004270 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00004271
John McCall604e7f12009-12-08 07:46:18 +00004272
John McCall9f54ad42009-12-10 09:41:52 +00004273 return Shadow;
4274}
John McCall604e7f12009-12-08 07:46:18 +00004275
John McCall9f54ad42009-12-10 09:41:52 +00004276/// Hides a using shadow declaration. This is required by the current
4277/// using-decl implementation when a resolvable using declaration in a
4278/// class is followed by a declaration which would hide or override
4279/// one or more of the using decl's targets; for example:
4280///
4281/// struct Base { void foo(int); };
4282/// struct Derived : Base {
4283/// using Base::foo;
4284/// void foo(int);
4285/// };
4286///
4287/// The governing language is C++03 [namespace.udecl]p12:
4288///
4289/// When a using-declaration brings names from a base class into a
4290/// derived class scope, member functions in the derived class
4291/// override and/or hide member functions with the same name and
4292/// parameter types in a base class (rather than conflicting).
4293///
4294/// There are two ways to implement this:
4295/// (1) optimistically create shadow decls when they're not hidden
4296/// by existing declarations, or
4297/// (2) don't create any shadow decls (or at least don't make them
4298/// visible) until we've fully parsed/instantiated the class.
4299/// The problem with (1) is that we might have to retroactively remove
4300/// a shadow decl, which requires several O(n) operations because the
4301/// decl structures are (very reasonably) not designed for removal.
4302/// (2) avoids this but is very fiddly and phase-dependent.
4303void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00004304 if (Shadow->getDeclName().getNameKind() ==
4305 DeclarationName::CXXConversionFunctionName)
4306 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
4307
John McCall9f54ad42009-12-10 09:41:52 +00004308 // Remove it from the DeclContext...
4309 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00004310
John McCall9f54ad42009-12-10 09:41:52 +00004311 // ...and the scope, if applicable...
4312 if (S) {
John McCalld226f652010-08-21 09:40:31 +00004313 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00004314 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00004315 }
4316
John McCall9f54ad42009-12-10 09:41:52 +00004317 // ...and the using decl.
4318 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
4319
4320 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00004321 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00004322}
4323
John McCall7ba107a2009-11-18 02:36:19 +00004324/// Builds a using declaration.
4325///
4326/// \param IsInstantiation - Whether this call arises from an
4327/// instantiation of an unresolved using declaration. We treat
4328/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00004329NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
4330 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00004331 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00004332 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00004333 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00004334 bool IsInstantiation,
4335 bool IsTypeName,
4336 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00004337 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00004338 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00004339 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00004340
Anders Carlsson550b14b2009-08-28 05:49:21 +00004341 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00004342
Anders Carlssoncf9f9212009-08-28 03:16:11 +00004343 if (SS.isEmpty()) {
4344 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00004345 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00004346 }
Mike Stump1eb44332009-09-09 15:08:12 +00004347
John McCall9f54ad42009-12-10 09:41:52 +00004348 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00004349 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00004350 ForRedeclaration);
4351 Previous.setHideTags(false);
4352 if (S) {
4353 LookupName(Previous, S);
4354
4355 // It is really dumb that we have to do this.
4356 LookupResult::Filter F = Previous.makeFilter();
4357 while (F.hasNext()) {
4358 NamedDecl *D = F.next();
4359 if (!isDeclInScope(D, CurContext, S))
4360 F.erase();
4361 }
4362 F.done();
4363 } else {
4364 assert(IsInstantiation && "no scope in non-instantiation");
4365 assert(CurContext->isRecord() && "scope not record in instantiation");
4366 LookupQualifiedName(Previous, CurContext);
4367 }
4368
John McCall9f54ad42009-12-10 09:41:52 +00004369 // Check for invalid redeclarations.
4370 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
4371 return 0;
4372
4373 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00004374 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
4375 return 0;
4376
John McCallaf8e6ed2009-11-12 03:15:40 +00004377 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00004378 NamedDecl *D;
Douglas Gregordc355712011-02-25 00:36:19 +00004379 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallaf8e6ed2009-11-12 03:15:40 +00004380 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00004381 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00004382 // FIXME: not all declaration name kinds are legal here
4383 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
4384 UsingLoc, TypenameLoc,
Douglas Gregordc355712011-02-25 00:36:19 +00004385 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00004386 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00004387 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00004388 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
4389 QualifierLoc, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00004390 }
John McCalled976492009-12-04 22:46:56 +00004391 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00004392 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
4393 NameInfo, IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00004394 }
John McCalled976492009-12-04 22:46:56 +00004395 D->setAccess(AS);
4396 CurContext->addDecl(D);
4397
4398 if (!LookupContext) return D;
4399 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00004400
John McCall77bb1aa2010-05-01 00:40:08 +00004401 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00004402 UD->setInvalidDecl();
4403 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00004404 }
4405
Sebastian Redlf677ea32011-02-05 19:23:19 +00004406 // Constructor inheriting using decls get special treatment.
4407 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Sebastian Redlcaa35e42011-03-12 13:44:32 +00004408 if (CheckInheritedConstructorUsingDecl(UD))
4409 UD->setInvalidDecl();
Sebastian Redlf677ea32011-02-05 19:23:19 +00004410 return UD;
4411 }
4412
4413 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00004414
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00004415 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00004416
John McCall604e7f12009-12-08 07:46:18 +00004417 // Unlike most lookups, we don't always want to hide tag
4418 // declarations: tag names are visible through the using declaration
4419 // even if hidden by ordinary names, *except* in a dependent context
4420 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00004421 if (!IsInstantiation)
4422 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00004423
John McCalla24dc2e2009-11-17 02:14:36 +00004424 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00004425
John McCallf36e02d2009-10-09 21:13:30 +00004426 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00004427 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00004428 << NameInfo.getName() << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00004429 UD->setInvalidDecl();
4430 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00004431 }
4432
John McCalled976492009-12-04 22:46:56 +00004433 if (R.isAmbiguous()) {
4434 UD->setInvalidDecl();
4435 return UD;
4436 }
Mike Stump1eb44332009-09-09 15:08:12 +00004437
John McCall7ba107a2009-11-18 02:36:19 +00004438 if (IsTypeName) {
4439 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00004440 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00004441 Diag(IdentLoc, diag::err_using_typename_non_type);
4442 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
4443 Diag((*I)->getUnderlyingDecl()->getLocation(),
4444 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00004445 UD->setInvalidDecl();
4446 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00004447 }
4448 } else {
4449 // If we asked for a non-typename and we got a type, error out,
4450 // but only if this is an instantiation of an unresolved using
4451 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00004452 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00004453 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
4454 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00004455 UD->setInvalidDecl();
4456 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00004457 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00004458 }
4459
Anders Carlsson73b39cf2009-08-28 03:35:18 +00004460 // C++0x N2914 [namespace.udecl]p6:
4461 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00004462 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00004463 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
4464 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00004465 UD->setInvalidDecl();
4466 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00004467 }
Mike Stump1eb44332009-09-09 15:08:12 +00004468
John McCall9f54ad42009-12-10 09:41:52 +00004469 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
4470 if (!CheckUsingShadowDecl(UD, *I, Previous))
4471 BuildUsingShadowDecl(S, UD, *I);
4472 }
John McCall9488ea12009-11-17 05:59:44 +00004473
4474 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00004475}
4476
Sebastian Redlf677ea32011-02-05 19:23:19 +00004477/// Additional checks for a using declaration referring to a constructor name.
4478bool Sema::CheckInheritedConstructorUsingDecl(UsingDecl *UD) {
4479 if (UD->isTypeName()) {
4480 // FIXME: Cannot specify typename when specifying constructor
4481 return true;
4482 }
4483
Douglas Gregordc355712011-02-25 00:36:19 +00004484 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redlf677ea32011-02-05 19:23:19 +00004485 assert(SourceType &&
4486 "Using decl naming constructor doesn't have type in scope spec.");
4487 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
4488
4489 // Check whether the named type is a direct base class.
4490 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
4491 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
4492 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
4493 BaseIt != BaseE; ++BaseIt) {
4494 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
4495 if (CanonicalSourceType == BaseType)
4496 break;
4497 }
4498
4499 if (BaseIt == BaseE) {
4500 // Did not find SourceType in the bases.
4501 Diag(UD->getUsingLocation(),
4502 diag::err_using_decl_constructor_not_in_direct_base)
4503 << UD->getNameInfo().getSourceRange()
4504 << QualType(SourceType, 0) << TargetClass;
4505 return true;
4506 }
4507
4508 BaseIt->setInheritConstructors();
4509
4510 return false;
4511}
4512
John McCall9f54ad42009-12-10 09:41:52 +00004513/// Checks that the given using declaration is not an invalid
4514/// redeclaration. Note that this is checking only for the using decl
4515/// itself, not for any ill-formedness among the UsingShadowDecls.
4516bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
4517 bool isTypeName,
4518 const CXXScopeSpec &SS,
4519 SourceLocation NameLoc,
4520 const LookupResult &Prev) {
4521 // C++03 [namespace.udecl]p8:
4522 // C++0x [namespace.udecl]p10:
4523 // A using-declaration is a declaration and can therefore be used
4524 // repeatedly where (and only where) multiple declarations are
4525 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00004526 //
John McCall8a726212010-11-29 18:01:58 +00004527 // That's in non-member contexts.
4528 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00004529 return false;
4530
4531 NestedNameSpecifier *Qual
4532 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
4533
4534 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
4535 NamedDecl *D = *I;
4536
4537 bool DTypename;
4538 NestedNameSpecifier *DQual;
4539 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
4540 DTypename = UD->isTypeName();
Douglas Gregordc355712011-02-25 00:36:19 +00004541 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00004542 } else if (UnresolvedUsingValueDecl *UD
4543 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
4544 DTypename = false;
Douglas Gregordc355712011-02-25 00:36:19 +00004545 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00004546 } else if (UnresolvedUsingTypenameDecl *UD
4547 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
4548 DTypename = true;
Douglas Gregordc355712011-02-25 00:36:19 +00004549 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00004550 } else continue;
4551
4552 // using decls differ if one says 'typename' and the other doesn't.
4553 // FIXME: non-dependent using decls?
4554 if (isTypeName != DTypename) continue;
4555
4556 // using decls differ if they name different scopes (but note that
4557 // template instantiation can cause this check to trigger when it
4558 // didn't before instantiation).
4559 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
4560 Context.getCanonicalNestedNameSpecifier(DQual))
4561 continue;
4562
4563 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00004564 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00004565 return true;
4566 }
4567
4568 return false;
4569}
4570
John McCall604e7f12009-12-08 07:46:18 +00004571
John McCalled976492009-12-04 22:46:56 +00004572/// Checks that the given nested-name qualifier used in a using decl
4573/// in the current context is appropriately related to the current
4574/// scope. If an error is found, diagnoses it and returns true.
4575bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
4576 const CXXScopeSpec &SS,
4577 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00004578 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00004579
John McCall604e7f12009-12-08 07:46:18 +00004580 if (!CurContext->isRecord()) {
4581 // C++03 [namespace.udecl]p3:
4582 // C++0x [namespace.udecl]p8:
4583 // A using-declaration for a class member shall be a member-declaration.
4584
4585 // If we weren't able to compute a valid scope, it must be a
4586 // dependent class scope.
4587 if (!NamedContext || NamedContext->isRecord()) {
4588 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
4589 << SS.getRange();
4590 return true;
4591 }
4592
4593 // Otherwise, everything is known to be fine.
4594 return false;
4595 }
4596
4597 // The current scope is a record.
4598
4599 // If the named context is dependent, we can't decide much.
4600 if (!NamedContext) {
4601 // FIXME: in C++0x, we can diagnose if we can prove that the
4602 // nested-name-specifier does not refer to a base class, which is
4603 // still possible in some cases.
4604
4605 // Otherwise we have to conservatively report that things might be
4606 // okay.
4607 return false;
4608 }
4609
4610 if (!NamedContext->isRecord()) {
4611 // Ideally this would point at the last name in the specifier,
4612 // but we don't have that level of source info.
4613 Diag(SS.getRange().getBegin(),
4614 diag::err_using_decl_nested_name_specifier_is_not_class)
4615 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
4616 return true;
4617 }
4618
Douglas Gregor6fb07292010-12-21 07:41:49 +00004619 if (!NamedContext->isDependentContext() &&
4620 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
4621 return true;
4622
John McCall604e7f12009-12-08 07:46:18 +00004623 if (getLangOptions().CPlusPlus0x) {
4624 // C++0x [namespace.udecl]p3:
4625 // In a using-declaration used as a member-declaration, the
4626 // nested-name-specifier shall name a base class of the class
4627 // being defined.
4628
4629 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
4630 cast<CXXRecordDecl>(NamedContext))) {
4631 if (CurContext == NamedContext) {
4632 Diag(NameLoc,
4633 diag::err_using_decl_nested_name_specifier_is_current_class)
4634 << SS.getRange();
4635 return true;
4636 }
4637
4638 Diag(SS.getRange().getBegin(),
4639 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4640 << (NestedNameSpecifier*) SS.getScopeRep()
4641 << cast<CXXRecordDecl>(CurContext)
4642 << SS.getRange();
4643 return true;
4644 }
4645
4646 return false;
4647 }
4648
4649 // C++03 [namespace.udecl]p4:
4650 // A using-declaration used as a member-declaration shall refer
4651 // to a member of a base class of the class being defined [etc.].
4652
4653 // Salient point: SS doesn't have to name a base class as long as
4654 // lookup only finds members from base classes. Therefore we can
4655 // diagnose here only if we can prove that that can't happen,
4656 // i.e. if the class hierarchies provably don't intersect.
4657
4658 // TODO: it would be nice if "definitely valid" results were cached
4659 // in the UsingDecl and UsingShadowDecl so that these checks didn't
4660 // need to be repeated.
4661
4662 struct UserData {
4663 llvm::DenseSet<const CXXRecordDecl*> Bases;
4664
4665 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
4666 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4667 Data->Bases.insert(Base);
4668 return true;
4669 }
4670
4671 bool hasDependentBases(const CXXRecordDecl *Class) {
4672 return !Class->forallBases(collect, this);
4673 }
4674
4675 /// Returns true if the base is dependent or is one of the
4676 /// accumulated base classes.
4677 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
4678 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4679 return !Data->Bases.count(Base);
4680 }
4681
4682 bool mightShareBases(const CXXRecordDecl *Class) {
4683 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
4684 }
4685 };
4686
4687 UserData Data;
4688
4689 // Returns false if we find a dependent base.
4690 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
4691 return false;
4692
4693 // Returns false if the class has a dependent base or if it or one
4694 // of its bases is present in the base set of the current context.
4695 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
4696 return false;
4697
4698 Diag(SS.getRange().getBegin(),
4699 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4700 << (NestedNameSpecifier*) SS.getScopeRep()
4701 << cast<CXXRecordDecl>(CurContext)
4702 << SS.getRange();
4703
4704 return true;
John McCalled976492009-12-04 22:46:56 +00004705}
4706
Richard Smith162e1c12011-04-15 14:24:37 +00004707Decl *Sema::ActOnAliasDeclaration(Scope *S,
4708 AccessSpecifier AS,
Richard Smith3e4c6c42011-05-05 21:57:07 +00004709 MultiTemplateParamsArg TemplateParamLists,
Richard Smith162e1c12011-04-15 14:24:37 +00004710 SourceLocation UsingLoc,
4711 UnqualifiedId &Name,
4712 TypeResult Type) {
Richard Smith3e4c6c42011-05-05 21:57:07 +00004713 // Skip up to the relevant declaration scope.
4714 while (S->getFlags() & Scope::TemplateParamScope)
4715 S = S->getParent();
Richard Smith162e1c12011-04-15 14:24:37 +00004716 assert((S->getFlags() & Scope::DeclScope) &&
4717 "got alias-declaration outside of declaration scope");
4718
4719 if (Type.isInvalid())
4720 return 0;
4721
4722 bool Invalid = false;
4723 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
4724 TypeSourceInfo *TInfo = 0;
Nick Lewyckyb79bf1d2011-05-02 01:07:19 +00004725 GetTypeFromParser(Type.get(), &TInfo);
Richard Smith162e1c12011-04-15 14:24:37 +00004726
4727 if (DiagnoseClassNameShadow(CurContext, NameInfo))
4728 return 0;
4729
4730 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3e4c6c42011-05-05 21:57:07 +00004731 UPPC_DeclarationType)) {
Richard Smith162e1c12011-04-15 14:24:37 +00004732 Invalid = true;
Richard Smith3e4c6c42011-05-05 21:57:07 +00004733 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
4734 TInfo->getTypeLoc().getBeginLoc());
4735 }
Richard Smith162e1c12011-04-15 14:24:37 +00004736
4737 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
4738 LookupName(Previous, S);
4739
4740 // Warn about shadowing the name of a template parameter.
4741 if (Previous.isSingleResult() &&
4742 Previous.getFoundDecl()->isTemplateParameter()) {
4743 if (DiagnoseTemplateParameterShadow(Name.StartLocation,
4744 Previous.getFoundDecl()))
4745 Invalid = true;
4746 Previous.clear();
4747 }
4748
4749 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
4750 "name in alias declaration must be an identifier");
4751 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
4752 Name.StartLocation,
4753 Name.Identifier, TInfo);
4754
4755 NewTD->setAccess(AS);
4756
4757 if (Invalid)
4758 NewTD->setInvalidDecl();
4759
Richard Smith3e4c6c42011-05-05 21:57:07 +00004760 CheckTypedefForVariablyModifiedType(S, NewTD);
4761 Invalid |= NewTD->isInvalidDecl();
4762
Richard Smith162e1c12011-04-15 14:24:37 +00004763 bool Redeclaration = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00004764
4765 NamedDecl *NewND;
4766 if (TemplateParamLists.size()) {
4767 TypeAliasTemplateDecl *OldDecl = 0;
4768 TemplateParameterList *OldTemplateParams = 0;
4769
4770 if (TemplateParamLists.size() != 1) {
4771 Diag(UsingLoc, diag::err_alias_template_extra_headers)
4772 << SourceRange(TemplateParamLists.get()[1]->getTemplateLoc(),
4773 TemplateParamLists.get()[TemplateParamLists.size()-1]->getRAngleLoc());
4774 }
4775 TemplateParameterList *TemplateParams = TemplateParamLists.get()[0];
4776
4777 // Only consider previous declarations in the same scope.
4778 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
4779 /*ExplicitInstantiationOrSpecialization*/false);
4780 if (!Previous.empty()) {
4781 Redeclaration = true;
4782
4783 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
4784 if (!OldDecl && !Invalid) {
4785 Diag(UsingLoc, diag::err_redefinition_different_kind)
4786 << Name.Identifier;
4787
4788 NamedDecl *OldD = Previous.getRepresentativeDecl();
4789 if (OldD->getLocation().isValid())
4790 Diag(OldD->getLocation(), diag::note_previous_definition);
4791
4792 Invalid = true;
4793 }
4794
4795 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
4796 if (TemplateParameterListsAreEqual(TemplateParams,
4797 OldDecl->getTemplateParameters(),
4798 /*Complain=*/true,
4799 TPL_TemplateMatch))
4800 OldTemplateParams = OldDecl->getTemplateParameters();
4801 else
4802 Invalid = true;
4803
4804 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
4805 if (!Invalid &&
4806 !Context.hasSameType(OldTD->getUnderlyingType(),
4807 NewTD->getUnderlyingType())) {
4808 // FIXME: The C++0x standard does not clearly say this is ill-formed,
4809 // but we can't reasonably accept it.
4810 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
4811 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
4812 if (OldTD->getLocation().isValid())
4813 Diag(OldTD->getLocation(), diag::note_previous_definition);
4814 Invalid = true;
4815 }
4816 }
4817 }
4818
4819 // Merge any previous default template arguments into our parameters,
4820 // and check the parameter list.
4821 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
4822 TPC_TypeAliasTemplate))
4823 return 0;
4824
4825 TypeAliasTemplateDecl *NewDecl =
4826 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
4827 Name.Identifier, TemplateParams,
4828 NewTD);
4829
4830 NewDecl->setAccess(AS);
4831
4832 if (Invalid)
4833 NewDecl->setInvalidDecl();
4834 else if (OldDecl)
4835 NewDecl->setPreviousDeclaration(OldDecl);
4836
4837 NewND = NewDecl;
4838 } else {
4839 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
4840 NewND = NewTD;
4841 }
Richard Smith162e1c12011-04-15 14:24:37 +00004842
4843 if (!Redeclaration)
Richard Smith3e4c6c42011-05-05 21:57:07 +00004844 PushOnScopeChains(NewND, S);
Richard Smith162e1c12011-04-15 14:24:37 +00004845
Richard Smith3e4c6c42011-05-05 21:57:07 +00004846 return NewND;
Richard Smith162e1c12011-04-15 14:24:37 +00004847}
4848
John McCalld226f652010-08-21 09:40:31 +00004849Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00004850 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00004851 SourceLocation AliasLoc,
4852 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00004853 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00004854 SourceLocation IdentLoc,
4855 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00004856
Anders Carlsson81c85c42009-03-28 23:53:49 +00004857 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00004858 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
4859 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00004860
Anders Carlsson8d7ba402009-03-28 06:23:46 +00004861 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00004862 NamedDecl *PrevDecl
4863 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
4864 ForRedeclaration);
4865 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
4866 PrevDecl = 0;
4867
4868 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00004869 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00004870 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00004871 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00004872 // FIXME: At some point, we'll want to create the (redundant)
4873 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00004874 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00004875 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00004876 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00004877 }
Mike Stump1eb44332009-09-09 15:08:12 +00004878
Anders Carlsson8d7ba402009-03-28 06:23:46 +00004879 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
4880 diag::err_redefinition_different_kind;
4881 Diag(AliasLoc, DiagID) << Alias;
4882 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00004883 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00004884 }
4885
John McCalla24dc2e2009-11-17 02:14:36 +00004886 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00004887 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004888
John McCallf36e02d2009-10-09 21:13:30 +00004889 if (R.empty()) {
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00004890 if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
4891 CTC_NoKeywords, 0)) {
4892 if (R.getAsSingle<NamespaceDecl>() ||
4893 R.getAsSingle<NamespaceAliasDecl>()) {
4894 if (DeclContext *DC = computeDeclContext(SS, false))
4895 Diag(IdentLoc, diag::err_using_directive_member_suggest)
4896 << Ident << DC << Corrected << SS.getRange()
4897 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4898 else
4899 Diag(IdentLoc, diag::err_using_directive_suggest)
4900 << Ident << Corrected
4901 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4902
4903 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
4904 << Corrected;
4905
4906 Ident = Corrected.getAsIdentifierInfo();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00004907 } else {
4908 R.clear();
4909 R.setLookupName(Ident);
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00004910 }
4911 }
4912
4913 if (R.empty()) {
4914 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00004915 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00004916 }
Anders Carlsson5721c682009-03-28 06:42:02 +00004917 }
Mike Stump1eb44332009-09-09 15:08:12 +00004918
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00004919 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00004920 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00004921 Alias, SS.getWithLocInContext(Context),
John McCallf36e02d2009-10-09 21:13:30 +00004922 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00004923
John McCall3dbd3d52010-02-16 06:53:13 +00004924 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00004925 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00004926}
4927
Douglas Gregor39957dc2010-05-01 15:04:51 +00004928namespace {
4929 /// \brief Scoped object used to handle the state changes required in Sema
4930 /// to implicitly define the body of a C++ member function;
4931 class ImplicitlyDefinedFunctionScope {
4932 Sema &S;
John McCalleee1d542011-02-14 07:13:47 +00004933 Sema::ContextRAII SavedContext;
Douglas Gregor39957dc2010-05-01 15:04:51 +00004934
4935 public:
4936 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
John McCalleee1d542011-02-14 07:13:47 +00004937 : S(S), SavedContext(S, Method)
Douglas Gregor39957dc2010-05-01 15:04:51 +00004938 {
Douglas Gregor39957dc2010-05-01 15:04:51 +00004939 S.PushFunctionScope();
4940 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
4941 }
4942
4943 ~ImplicitlyDefinedFunctionScope() {
4944 S.PopExpressionEvaluationContext();
4945 S.PopFunctionOrBlockScope();
Douglas Gregor39957dc2010-05-01 15:04:51 +00004946 }
4947 };
4948}
4949
Sebastian Redl751025d2010-09-13 22:02:47 +00004950static CXXConstructorDecl *getDefaultConstructorUnsafe(Sema &Self,
4951 CXXRecordDecl *D) {
4952 ASTContext &Context = Self.Context;
4953 QualType ClassType = Context.getTypeDeclType(D);
4954 DeclarationName ConstructorName
4955 = Context.DeclarationNames.getCXXConstructorName(
4956 Context.getCanonicalType(ClassType.getUnqualifiedType()));
4957
4958 DeclContext::lookup_const_iterator Con, ConEnd;
4959 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
4960 Con != ConEnd; ++Con) {
4961 // FIXME: In C++0x, a constructor template can be a default constructor.
4962 if (isa<FunctionTemplateDecl>(*Con))
4963 continue;
4964
4965 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
4966 if (Constructor->isDefaultConstructor())
4967 return Constructor;
4968 }
4969 return 0;
4970}
4971
Douglas Gregor23c94db2010-07-02 17:43:08 +00004972CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
4973 CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00004974 // C++ [class.ctor]p5:
4975 // A default constructor for a class X is a constructor of class X
4976 // that can be called without an argument. If there is no
4977 // user-declared constructor for class X, a default constructor is
4978 // implicitly declared. An implicitly-declared default constructor
4979 // is an inline public member of its class.
Douglas Gregor18274032010-07-03 00:47:00 +00004980 assert(!ClassDecl->hasUserDeclaredConstructor() &&
4981 "Should not build implicit default constructor!");
4982
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004983 // C++ [except.spec]p14:
4984 // An implicitly declared special member function (Clause 12) shall have an
4985 // exception-specification. [...]
4986 ImplicitExceptionSpecification ExceptSpec(Context);
4987
Sebastian Redl60618fa2011-03-12 11:50:43 +00004988 // Direct base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004989 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4990 BEnd = ClassDecl->bases_end();
4991 B != BEnd; ++B) {
4992 if (B->isVirtual()) // Handled below.
4993 continue;
4994
Douglas Gregor18274032010-07-03 00:47:00 +00004995 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
4996 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4997 if (!BaseClassDecl->hasDeclaredDefaultConstructor())
4998 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
Sebastian Redl751025d2010-09-13 22:02:47 +00004999 else if (CXXConstructorDecl *Constructor
5000 = getDefaultConstructorUnsafe(*this, BaseClassDecl))
Douglas Gregoreb8c6702010-07-01 22:31:05 +00005001 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00005002 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00005003 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00005004
5005 // Virtual base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00005006 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
5007 BEnd = ClassDecl->vbases_end();
5008 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00005009 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
5010 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
5011 if (!BaseClassDecl->hasDeclaredDefaultConstructor())
5012 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
5013 else if (CXXConstructorDecl *Constructor
Sebastian Redl751025d2010-09-13 22:02:47 +00005014 = getDefaultConstructorUnsafe(*this, BaseClassDecl))
Douglas Gregoreb8c6702010-07-01 22:31:05 +00005015 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00005016 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00005017 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00005018
5019 // Field constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00005020 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
5021 FEnd = ClassDecl->field_end();
5022 F != FEnd; ++F) {
5023 if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00005024 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
5025 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
5026 if (!FieldClassDecl->hasDeclaredDefaultConstructor())
5027 ExceptSpec.CalledDecl(
5028 DeclareImplicitDefaultConstructor(FieldClassDecl));
5029 else if (CXXConstructorDecl *Constructor
Sebastian Redl751025d2010-09-13 22:02:47 +00005030 = getDefaultConstructorUnsafe(*this, FieldClassDecl))
Douglas Gregoreb8c6702010-07-01 22:31:05 +00005031 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00005032 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00005033 }
John McCalle23cf432010-12-14 08:05:40 +00005034
5035 FunctionProtoType::ExtProtoInfo EPI;
Sebastian Redl60618fa2011-03-12 11:50:43 +00005036 EPI.ExceptionSpecType = ExceptSpec.getExceptionSpecType();
John McCalle23cf432010-12-14 08:05:40 +00005037 EPI.NumExceptions = ExceptSpec.size();
5038 EPI.Exceptions = ExceptSpec.data();
Sebastian Redl8b5b4092011-03-06 10:52:04 +00005039
Douglas Gregoreb8c6702010-07-01 22:31:05 +00005040 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00005041 CanQualType ClassType
5042 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005043 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor32df23e2010-07-01 22:02:46 +00005044 DeclarationName Name
5045 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005046 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregor32df23e2010-07-01 22:02:46 +00005047 CXXConstructorDecl *DefaultCon
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005048 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Douglas Gregor32df23e2010-07-01 22:02:46 +00005049 Context.getFunctionType(Context.VoidTy,
John McCalle23cf432010-12-14 08:05:40 +00005050 0, 0, EPI),
Douglas Gregor32df23e2010-07-01 22:02:46 +00005051 /*TInfo=*/0,
5052 /*isExplicit=*/false,
5053 /*isInline=*/true,
Sean Hunt5f802e52011-05-06 00:11:07 +00005054 /*isImplicitlyDeclared=*/true);
Douglas Gregor32df23e2010-07-01 22:02:46 +00005055 DefaultCon->setAccess(AS_public);
5056 DefaultCon->setImplicit();
5057 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Douglas Gregor18274032010-07-03 00:47:00 +00005058
5059 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00005060 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
5061
Douglas Gregor23c94db2010-07-02 17:43:08 +00005062 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00005063 PushOnScopeChains(DefaultCon, S, false);
5064 ClassDecl->addDecl(DefaultCon);
5065
Douglas Gregor32df23e2010-07-01 22:02:46 +00005066 return DefaultCon;
5067}
5068
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00005069void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
5070 CXXConstructorDecl *Constructor) {
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00005071 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
Douglas Gregorc070cc62010-06-17 23:14:26 +00005072 !Constructor->isUsed(false)) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00005073 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00005074
Anders Carlssonf6513ed2010-04-23 16:04:08 +00005075 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00005076 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00005077
Douglas Gregor39957dc2010-05-01 15:04:51 +00005078 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00005079 DiagnosticErrorTrap Trap(Diags);
Sean Huntcbb67482011-01-08 20:30:50 +00005080 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00005081 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00005082 Diag(CurrentLocation, diag::note_member_synthesized_at)
Anders Carlsson3b8c53b2010-04-22 05:40:53 +00005083 << CXXConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00005084 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00005085 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00005086 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00005087
5088 SourceLocation Loc = Constructor->getLocation();
5089 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
5090
5091 Constructor->setUsed();
5092 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00005093
5094 if (ASTMutationListener *L = getASTMutationListener()) {
5095 L->CompletedImplicitDefinition(Constructor);
5096 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00005097}
5098
Sebastian Redlf677ea32011-02-05 19:23:19 +00005099void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
5100 // We start with an initial pass over the base classes to collect those that
5101 // inherit constructors from. If there are none, we can forgo all further
5102 // processing.
5103 typedef llvm::SmallVector<const RecordType *, 4> BasesVector;
5104 BasesVector BasesToInheritFrom;
5105 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
5106 BaseE = ClassDecl->bases_end();
5107 BaseIt != BaseE; ++BaseIt) {
5108 if (BaseIt->getInheritConstructors()) {
5109 QualType Base = BaseIt->getType();
5110 if (Base->isDependentType()) {
5111 // If we inherit constructors from anything that is dependent, just
5112 // abort processing altogether. We'll get another chance for the
5113 // instantiations.
5114 return;
5115 }
5116 BasesToInheritFrom.push_back(Base->castAs<RecordType>());
5117 }
5118 }
5119 if (BasesToInheritFrom.empty())
5120 return;
5121
5122 // Now collect the constructors that we already have in the current class.
5123 // Those take precedence over inherited constructors.
5124 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
5125 // unless there is a user-declared constructor with the same signature in
5126 // the class where the using-declaration appears.
5127 llvm::SmallSet<const Type *, 8> ExistingConstructors;
5128 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
5129 CtorE = ClassDecl->ctor_end();
5130 CtorIt != CtorE; ++CtorIt) {
5131 ExistingConstructors.insert(
5132 Context.getCanonicalType(CtorIt->getType()).getTypePtr());
5133 }
5134
5135 Scope *S = getScopeForContext(ClassDecl);
5136 DeclarationName CreatedCtorName =
5137 Context.DeclarationNames.getCXXConstructorName(
5138 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
5139
5140 // Now comes the true work.
5141 // First, we keep a map from constructor types to the base that introduced
5142 // them. Needed for finding conflicting constructors. We also keep the
5143 // actually inserted declarations in there, for pretty diagnostics.
5144 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
5145 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
5146 ConstructorToSourceMap InheritedConstructors;
5147 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
5148 BaseE = BasesToInheritFrom.end();
5149 BaseIt != BaseE; ++BaseIt) {
5150 const RecordType *Base = *BaseIt;
5151 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
5152 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
5153 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
5154 CtorE = BaseDecl->ctor_end();
5155 CtorIt != CtorE; ++CtorIt) {
5156 // Find the using declaration for inheriting this base's constructors.
5157 DeclarationName Name =
5158 Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
5159 UsingDecl *UD = dyn_cast_or_null<UsingDecl>(
5160 LookupSingleName(S, Name,SourceLocation(), LookupUsingDeclName));
5161 SourceLocation UsingLoc = UD ? UD->getLocation() :
5162 ClassDecl->getLocation();
5163
5164 // C++0x [class.inhctor]p1: The candidate set of inherited constructors
5165 // from the class X named in the using-declaration consists of actual
5166 // constructors and notional constructors that result from the
5167 // transformation of defaulted parameters as follows:
5168 // - all non-template default constructors of X, and
5169 // - for each non-template constructor of X that has at least one
5170 // parameter with a default argument, the set of constructors that
5171 // results from omitting any ellipsis parameter specification and
5172 // successively omitting parameters with a default argument from the
5173 // end of the parameter-type-list.
5174 CXXConstructorDecl *BaseCtor = *CtorIt;
5175 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
5176 const FunctionProtoType *BaseCtorType =
5177 BaseCtor->getType()->getAs<FunctionProtoType>();
5178
5179 for (unsigned params = BaseCtor->getMinRequiredArguments(),
5180 maxParams = BaseCtor->getNumParams();
5181 params <= maxParams; ++params) {
5182 // Skip default constructors. They're never inherited.
5183 if (params == 0)
5184 continue;
5185 // Skip copy and move constructors for the same reason.
5186 if (CanBeCopyOrMove && params == 1)
5187 continue;
5188
5189 // Build up a function type for this particular constructor.
5190 // FIXME: The working paper does not consider that the exception spec
5191 // for the inheriting constructor might be larger than that of the
5192 // source. This code doesn't yet, either.
5193 const Type *NewCtorType;
5194 if (params == maxParams)
5195 NewCtorType = BaseCtorType;
5196 else {
5197 llvm::SmallVector<QualType, 16> Args;
5198 for (unsigned i = 0; i < params; ++i) {
5199 Args.push_back(BaseCtorType->getArgType(i));
5200 }
5201 FunctionProtoType::ExtProtoInfo ExtInfo =
5202 BaseCtorType->getExtProtoInfo();
5203 ExtInfo.Variadic = false;
5204 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
5205 Args.data(), params, ExtInfo)
5206 .getTypePtr();
5207 }
5208 const Type *CanonicalNewCtorType =
5209 Context.getCanonicalType(NewCtorType);
5210
5211 // Now that we have the type, first check if the class already has a
5212 // constructor with this signature.
5213 if (ExistingConstructors.count(CanonicalNewCtorType))
5214 continue;
5215
5216 // Then we check if we have already declared an inherited constructor
5217 // with this signature.
5218 std::pair<ConstructorToSourceMap::iterator, bool> result =
5219 InheritedConstructors.insert(std::make_pair(
5220 CanonicalNewCtorType,
5221 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
5222 if (!result.second) {
5223 // Already in the map. If it came from a different class, that's an
5224 // error. Not if it's from the same.
5225 CanQualType PreviousBase = result.first->second.first;
5226 if (CanonicalBase != PreviousBase) {
5227 const CXXConstructorDecl *PrevCtor = result.first->second.second;
5228 const CXXConstructorDecl *PrevBaseCtor =
5229 PrevCtor->getInheritedConstructor();
5230 assert(PrevBaseCtor && "Conflicting constructor was not inherited");
5231
5232 Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
5233 Diag(BaseCtor->getLocation(),
5234 diag::note_using_decl_constructor_conflict_current_ctor);
5235 Diag(PrevBaseCtor->getLocation(),
5236 diag::note_using_decl_constructor_conflict_previous_ctor);
5237 Diag(PrevCtor->getLocation(),
5238 diag::note_using_decl_constructor_conflict_previous_using);
5239 }
5240 continue;
5241 }
5242
5243 // OK, we're there, now add the constructor.
5244 // C++0x [class.inhctor]p8: [...] that would be performed by a
5245 // user-writtern inline constructor [...]
5246 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
5247 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005248 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
5249 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
Sean Hunt5f802e52011-05-06 00:11:07 +00005250 /*ImplicitlyDeclared=*/true);
Sebastian Redlf677ea32011-02-05 19:23:19 +00005251 NewCtor->setAccess(BaseCtor->getAccess());
5252
5253 // Build up the parameter decls and add them.
5254 llvm::SmallVector<ParmVarDecl *, 16> ParamDecls;
5255 for (unsigned i = 0; i < params; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005256 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
5257 UsingLoc, UsingLoc,
Sebastian Redlf677ea32011-02-05 19:23:19 +00005258 /*IdentifierInfo=*/0,
5259 BaseCtorType->getArgType(i),
5260 /*TInfo=*/0, SC_None,
5261 SC_None, /*DefaultArg=*/0));
5262 }
5263 NewCtor->setParams(ParamDecls.data(), ParamDecls.size());
5264 NewCtor->setInheritedConstructor(BaseCtor);
5265
5266 PushOnScopeChains(NewCtor, S, false);
5267 ClassDecl->addDecl(NewCtor);
5268 result.first->second.second = NewCtor;
5269 }
5270 }
5271 }
5272}
5273
Douglas Gregor23c94db2010-07-02 17:43:08 +00005274CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
Douglas Gregorfabd43a2010-07-01 19:09:28 +00005275 // C++ [class.dtor]p2:
5276 // If a class has no user-declared destructor, a destructor is
5277 // declared implicitly. An implicitly-declared destructor is an
5278 // inline public member of its class.
5279
5280 // C++ [except.spec]p14:
5281 // An implicitly declared special member function (Clause 12) shall have
5282 // an exception-specification.
5283 ImplicitExceptionSpecification ExceptSpec(Context);
5284
5285 // Direct base-class destructors.
5286 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
5287 BEnd = ClassDecl->bases_end();
5288 B != BEnd; ++B) {
5289 if (B->isVirtual()) // Handled below.
5290 continue;
5291
5292 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
5293 ExceptSpec.CalledDecl(
Douglas Gregordb89f282010-07-01 22:47:18 +00005294 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00005295 }
5296
5297 // Virtual base-class destructors.
5298 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
5299 BEnd = ClassDecl->vbases_end();
5300 B != BEnd; ++B) {
5301 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
5302 ExceptSpec.CalledDecl(
Douglas Gregordb89f282010-07-01 22:47:18 +00005303 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00005304 }
5305
5306 // Field destructors.
5307 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
5308 FEnd = ClassDecl->field_end();
5309 F != FEnd; ++F) {
5310 if (const RecordType *RecordTy
5311 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
5312 ExceptSpec.CalledDecl(
Douglas Gregordb89f282010-07-01 22:47:18 +00005313 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00005314 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00005315
Douglas Gregor4923aa22010-07-02 20:37:36 +00005316 // Create the actual destructor declaration.
John McCalle23cf432010-12-14 08:05:40 +00005317 FunctionProtoType::ExtProtoInfo EPI;
Sebastian Redl60618fa2011-03-12 11:50:43 +00005318 EPI.ExceptionSpecType = ExceptSpec.getExceptionSpecType();
John McCalle23cf432010-12-14 08:05:40 +00005319 EPI.NumExceptions = ExceptSpec.size();
5320 EPI.Exceptions = ExceptSpec.data();
5321 QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Sebastian Redl60618fa2011-03-12 11:50:43 +00005322
Douglas Gregorfabd43a2010-07-01 19:09:28 +00005323 CanQualType ClassType
5324 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005325 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00005326 DeclarationName Name
5327 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005328 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00005329 CXXDestructorDecl *Destructor
Sebastian Redl60618fa2011-03-12 11:50:43 +00005330 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, Ty, 0,
5331 /*isInline=*/true,
5332 /*isImplicitlyDeclared=*/true);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00005333 Destructor->setAccess(AS_public);
5334 Destructor->setImplicit();
5335 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor4923aa22010-07-02 20:37:36 +00005336
5337 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00005338 ++ASTContext::NumImplicitDestructorsDeclared;
5339
5340 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00005341 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00005342 PushOnScopeChains(Destructor, S, false);
5343 ClassDecl->addDecl(Destructor);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00005344
5345 // This could be uniqued if it ever proves significant.
5346 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
5347
5348 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor4923aa22010-07-02 20:37:36 +00005349
Douglas Gregorfabd43a2010-07-01 19:09:28 +00005350 return Destructor;
5351}
5352
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00005353void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00005354 CXXDestructorDecl *Destructor) {
Douglas Gregorc070cc62010-06-17 23:14:26 +00005355 assert((Destructor->isImplicit() && !Destructor->isUsed(false)) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00005356 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00005357 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00005358 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005359
Douglas Gregorc63d2c82010-05-12 16:39:35 +00005360 if (Destructor->isInvalidDecl())
5361 return;
5362
Douglas Gregor39957dc2010-05-01 15:04:51 +00005363 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005364
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00005365 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00005366 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
5367 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00005368
Douglas Gregorc63d2c82010-05-12 16:39:35 +00005369 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00005370 Diag(CurrentLocation, diag::note_member_synthesized_at)
5371 << CXXDestructor << Context.getTagDeclType(ClassDecl);
5372
5373 Destructor->setInvalidDecl();
5374 return;
5375 }
5376
Douglas Gregor4ada9d32010-09-20 16:48:21 +00005377 SourceLocation Loc = Destructor->getLocation();
5378 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
5379
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00005380 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00005381 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00005382
5383 if (ASTMutationListener *L = getASTMutationListener()) {
5384 L->CompletedImplicitDefinition(Destructor);
5385 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00005386}
5387
Douglas Gregor06a9f362010-05-01 20:49:11 +00005388/// \brief Builds a statement that copies the given entity from \p From to
5389/// \c To.
5390///
5391/// This routine is used to copy the members of a class with an
5392/// implicitly-declared copy assignment operator. When the entities being
5393/// copied are arrays, this routine builds for loops to copy them.
5394///
5395/// \param S The Sema object used for type-checking.
5396///
5397/// \param Loc The location where the implicit copy is being generated.
5398///
5399/// \param T The type of the expressions being copied. Both expressions must
5400/// have this type.
5401///
5402/// \param To The expression we are copying to.
5403///
5404/// \param From The expression we are copying from.
5405///
Douglas Gregor6cdc1612010-05-04 15:20:55 +00005406/// \param CopyingBaseSubobject Whether we're copying a base subobject.
5407/// Otherwise, it's a non-static member subobject.
5408///
Douglas Gregor06a9f362010-05-01 20:49:11 +00005409/// \param Depth Internal parameter recording the depth of the recursion.
5410///
5411/// \returns A statement or a loop that copies the expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00005412static StmtResult
Douglas Gregor06a9f362010-05-01 20:49:11 +00005413BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCall9ae2f072010-08-23 23:25:46 +00005414 Expr *To, Expr *From,
Douglas Gregor6cdc1612010-05-04 15:20:55 +00005415 bool CopyingBaseSubobject, unsigned Depth = 0) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00005416 // C++0x [class.copy]p30:
5417 // Each subobject is assigned in the manner appropriate to its type:
5418 //
5419 // - if the subobject is of class type, the copy assignment operator
5420 // for the class is used (as if by explicit qualification; that is,
5421 // ignoring any possible virtual overriding functions in more derived
5422 // classes);
5423 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
5424 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
5425
5426 // Look for operator=.
5427 DeclarationName Name
5428 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
5429 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
5430 S.LookupQualifiedName(OpLookup, ClassDecl, false);
5431
5432 // Filter out any result that isn't a copy-assignment operator.
5433 LookupResult::Filter F = OpLookup.makeFilter();
5434 while (F.hasNext()) {
5435 NamedDecl *D = F.next();
5436 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
5437 if (Method->isCopyAssignmentOperator())
5438 continue;
5439
5440 F.erase();
John McCallb0207482010-03-16 06:11:48 +00005441 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00005442 F.done();
5443
Douglas Gregor6cdc1612010-05-04 15:20:55 +00005444 // Suppress the protected check (C++ [class.protected]) for each of the
5445 // assignment operators we found. This strange dance is required when
5446 // we're assigning via a base classes's copy-assignment operator. To
5447 // ensure that we're getting the right base class subobject (without
5448 // ambiguities), we need to cast "this" to that subobject type; to
5449 // ensure that we don't go through the virtual call mechanism, we need
5450 // to qualify the operator= name with the base class (see below). However,
5451 // this means that if the base class has a protected copy assignment
5452 // operator, the protected member access check will fail. So, we
5453 // rewrite "protected" access to "public" access in this case, since we
5454 // know by construction that we're calling from a derived class.
5455 if (CopyingBaseSubobject) {
5456 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
5457 L != LEnd; ++L) {
5458 if (L.getAccess() == AS_protected)
5459 L.setAccess(AS_public);
5460 }
5461 }
5462
Douglas Gregor06a9f362010-05-01 20:49:11 +00005463 // Create the nested-name-specifier that will be used to qualify the
5464 // reference to operator=; this is required to suppress the virtual
5465 // call mechanism.
5466 CXXScopeSpec SS;
Douglas Gregorc34348a2011-02-24 17:54:50 +00005467 SS.MakeTrivial(S.Context,
5468 NestedNameSpecifier::Create(S.Context, 0, false,
5469 T.getTypePtr()),
5470 Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005471
5472 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00005473 ExprResult OpEqualRef
John McCall9ae2f072010-08-23 23:25:46 +00005474 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Douglas Gregor06a9f362010-05-01 20:49:11 +00005475 /*FirstQualifierInScope=*/0, OpLookup,
5476 /*TemplateArgs=*/0,
5477 /*SuppressQualifierCheck=*/true);
5478 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005479 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00005480
5481 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00005482
John McCall60d7b3a2010-08-24 06:29:42 +00005483 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00005484 OpEqualRef.takeAs<Expr>(),
5485 Loc, &From, 1, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005486 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005487 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00005488
5489 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00005490 }
John McCallb0207482010-03-16 06:11:48 +00005491
Douglas Gregor06a9f362010-05-01 20:49:11 +00005492 // - if the subobject is of scalar type, the built-in assignment
5493 // operator is used.
5494 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
5495 if (!ArrayTy) {
John McCall2de56d12010-08-25 11:45:40 +00005496 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005497 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005498 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00005499
5500 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00005501 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00005502
5503 // - if the subobject is an array, each element is assigned, in the
5504 // manner appropriate to the element type;
5505
5506 // Construct a loop over the array bounds, e.g.,
5507 //
5508 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
5509 //
5510 // that will copy each of the array elements.
5511 QualType SizeType = S.Context.getSizeType();
5512
5513 // Create the iteration variable.
5514 IdentifierInfo *IterationVarName = 0;
5515 {
5516 llvm::SmallString<8> Str;
5517 llvm::raw_svector_ostream OS(Str);
5518 OS << "__i" << Depth;
5519 IterationVarName = &S.Context.Idents.get(OS.str());
5520 }
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005521 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00005522 IterationVarName, SizeType,
5523 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00005524 SC_None, SC_None);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005525
5526 // Initialize the iteration variable to zero.
5527 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00005528 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00005529
5530 // Create a reference to the iteration variable; we'll use this several
5531 // times throughout.
5532 Expr *IterationVarRef
John McCallf89e55a2010-11-18 06:31:45 +00005533 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00005534 assert(IterationVarRef && "Reference to invented variable cannot fail!");
5535
5536 // Create the DeclStmt that holds the iteration variable.
5537 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
5538
5539 // Create the comparison against the array bound.
Jay Foad9f71a8f2010-12-07 08:25:34 +00005540 llvm::APInt Upper
5541 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCall9ae2f072010-08-23 23:25:46 +00005542 Expr *Comparison
John McCall3fa5cae2010-10-26 07:05:15 +00005543 = new (S.Context) BinaryOperator(IterationVarRef,
John McCallf89e55a2010-11-18 06:31:45 +00005544 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
5545 BO_NE, S.Context.BoolTy,
5546 VK_RValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005547
5548 // Create the pre-increment of the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00005549 Expr *Increment
John McCallf89e55a2010-11-18 06:31:45 +00005550 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
5551 VK_LValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005552
5553 // Subscript the "from" and "to" expressions with the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00005554 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
5555 IterationVarRef, Loc));
5556 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
5557 IterationVarRef, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00005558
5559 // Build the copy for an individual element of the array.
John McCallf89e55a2010-11-18 06:31:45 +00005560 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
5561 To, From, CopyingBaseSubobject,
5562 Depth + 1);
Douglas Gregorff331c12010-07-25 18:17:45 +00005563 if (Copy.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005564 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00005565
5566 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00005567 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00005568 S.MakeFullExpr(Comparison),
John McCalld226f652010-08-21 09:40:31 +00005569 0, S.MakeFullExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00005570 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00005571}
5572
Douglas Gregora376d102010-07-02 21:50:04 +00005573/// \brief Determine whether the given class has a copy assignment operator
5574/// that accepts a const-qualified argument.
5575static bool hasConstCopyAssignment(Sema &S, const CXXRecordDecl *CClass) {
5576 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(CClass);
5577
5578 if (!Class->hasDeclaredCopyAssignment())
5579 S.DeclareImplicitCopyAssignment(Class);
5580
5581 QualType ClassType = S.Context.getCanonicalType(S.Context.getTypeDeclType(Class));
5582 DeclarationName OpName
5583 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
5584
5585 DeclContext::lookup_const_iterator Op, OpEnd;
5586 for (llvm::tie(Op, OpEnd) = Class->lookup(OpName); Op != OpEnd; ++Op) {
5587 // C++ [class.copy]p9:
5588 // A user-declared copy assignment operator is a non-static non-template
5589 // member function of class X with exactly one parameter of type X, X&,
5590 // const X&, volatile X& or const volatile X&.
5591 const CXXMethodDecl* Method = dyn_cast<CXXMethodDecl>(*Op);
5592 if (!Method)
5593 continue;
5594
5595 if (Method->isStatic())
5596 continue;
5597 if (Method->getPrimaryTemplate())
5598 continue;
5599 const FunctionProtoType *FnType =
5600 Method->getType()->getAs<FunctionProtoType>();
5601 assert(FnType && "Overloaded operator has no prototype.");
5602 // Don't assert on this; an invalid decl might have been left in the AST.
5603 if (FnType->getNumArgs() != 1 || FnType->isVariadic())
5604 continue;
5605 bool AcceptsConst = true;
5606 QualType ArgType = FnType->getArgType(0);
5607 if (const LValueReferenceType *Ref = ArgType->getAs<LValueReferenceType>()){
5608 ArgType = Ref->getPointeeType();
5609 // Is it a non-const lvalue reference?
5610 if (!ArgType.isConstQualified())
5611 AcceptsConst = false;
5612 }
5613 if (!S.Context.hasSameUnqualifiedType(ArgType, ClassType))
5614 continue;
5615
5616 // We have a single argument of type cv X or cv X&, i.e. we've found the
5617 // copy assignment operator. Return whether it accepts const arguments.
5618 return AcceptsConst;
5619 }
5620 assert(Class->isInvalidDecl() &&
5621 "No copy assignment operator declared in valid code.");
5622 return false;
5623}
5624
Douglas Gregor23c94db2010-07-02 17:43:08 +00005625CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
Douglas Gregord3c35902010-07-01 16:36:15 +00005626 // Note: The following rules are largely analoguous to the copy
5627 // constructor rules. Note that virtual bases are not taken into account
5628 // for determining the argument type of the operator. Note also that
5629 // operators taking an object instead of a reference are allowed.
Douglas Gregor18274032010-07-03 00:47:00 +00005630
5631
Douglas Gregord3c35902010-07-01 16:36:15 +00005632 // C++ [class.copy]p10:
5633 // If the class definition does not explicitly declare a copy
5634 // assignment operator, one is declared implicitly.
5635 // The implicitly-defined copy assignment operator for a class X
5636 // will have the form
5637 //
5638 // X& X::operator=(const X&)
5639 //
5640 // if
5641 bool HasConstCopyAssignment = true;
5642
5643 // -- each direct base class B of X has a copy assignment operator
5644 // whose parameter is of type const B&, const volatile B& or B,
5645 // and
5646 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5647 BaseEnd = ClassDecl->bases_end();
5648 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
5649 assert(!Base->getType()->isDependentType() &&
5650 "Cannot generate implicit members for class with dependent bases.");
5651 const CXXRecordDecl *BaseClassDecl
5652 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora376d102010-07-02 21:50:04 +00005653 HasConstCopyAssignment = hasConstCopyAssignment(*this, BaseClassDecl);
Douglas Gregord3c35902010-07-01 16:36:15 +00005654 }
5655
5656 // -- for all the nonstatic data members of X that are of a class
5657 // type M (or array thereof), each such class type has a copy
5658 // assignment operator whose parameter is of type const M&,
5659 // const volatile M& or M.
5660 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5661 FieldEnd = ClassDecl->field_end();
5662 HasConstCopyAssignment && Field != FieldEnd;
5663 ++Field) {
5664 QualType FieldType = Context.getBaseElementType((*Field)->getType());
5665 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
5666 const CXXRecordDecl *FieldClassDecl
5667 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora376d102010-07-02 21:50:04 +00005668 HasConstCopyAssignment = hasConstCopyAssignment(*this, FieldClassDecl);
Douglas Gregord3c35902010-07-01 16:36:15 +00005669 }
5670 }
5671
5672 // Otherwise, the implicitly declared copy assignment operator will
5673 // have the form
5674 //
5675 // X& X::operator=(X&)
5676 QualType ArgType = Context.getTypeDeclType(ClassDecl);
5677 QualType RetType = Context.getLValueReferenceType(ArgType);
5678 if (HasConstCopyAssignment)
5679 ArgType = ArgType.withConst();
5680 ArgType = Context.getLValueReferenceType(ArgType);
5681
Douglas Gregorb87786f2010-07-01 17:48:08 +00005682 // C++ [except.spec]p14:
5683 // An implicitly declared special member function (Clause 12) shall have an
5684 // exception-specification. [...]
5685 ImplicitExceptionSpecification ExceptSpec(Context);
5686 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5687 BaseEnd = ClassDecl->bases_end();
5688 Base != BaseEnd; ++Base) {
Douglas Gregora376d102010-07-02 21:50:04 +00005689 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00005690 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora376d102010-07-02 21:50:04 +00005691
5692 if (!BaseClassDecl->hasDeclaredCopyAssignment())
5693 DeclareImplicitCopyAssignment(BaseClassDecl);
5694
Douglas Gregorb87786f2010-07-01 17:48:08 +00005695 if (CXXMethodDecl *CopyAssign
5696 = BaseClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
5697 ExceptSpec.CalledDecl(CopyAssign);
5698 }
5699 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5700 FieldEnd = ClassDecl->field_end();
5701 Field != FieldEnd;
5702 ++Field) {
5703 QualType FieldType = Context.getBaseElementType((*Field)->getType());
5704 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregora376d102010-07-02 21:50:04 +00005705 CXXRecordDecl *FieldClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00005706 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora376d102010-07-02 21:50:04 +00005707
5708 if (!FieldClassDecl->hasDeclaredCopyAssignment())
5709 DeclareImplicitCopyAssignment(FieldClassDecl);
5710
Douglas Gregorb87786f2010-07-01 17:48:08 +00005711 if (CXXMethodDecl *CopyAssign
5712 = FieldClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
5713 ExceptSpec.CalledDecl(CopyAssign);
5714 }
5715 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00005716
Douglas Gregord3c35902010-07-01 16:36:15 +00005717 // An implicitly-declared copy assignment operator is an inline public
5718 // member of its class.
John McCalle23cf432010-12-14 08:05:40 +00005719 FunctionProtoType::ExtProtoInfo EPI;
Sebastian Redl60618fa2011-03-12 11:50:43 +00005720 EPI.ExceptionSpecType = ExceptSpec.getExceptionSpecType();
John McCalle23cf432010-12-14 08:05:40 +00005721 EPI.NumExceptions = ExceptSpec.size();
5722 EPI.Exceptions = ExceptSpec.data();
Douglas Gregord3c35902010-07-01 16:36:15 +00005723 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005724 SourceLocation ClassLoc = ClassDecl->getLocation();
5725 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregord3c35902010-07-01 16:36:15 +00005726 CXXMethodDecl *CopyAssignment
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005727 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
John McCalle23cf432010-12-14 08:05:40 +00005728 Context.getFunctionType(RetType, &ArgType, 1, EPI),
Douglas Gregord3c35902010-07-01 16:36:15 +00005729 /*TInfo=*/0, /*isStatic=*/false,
John McCalld931b082010-08-26 03:08:43 +00005730 /*StorageClassAsWritten=*/SC_None,
Douglas Gregorf5251602011-03-08 17:10:18 +00005731 /*isInline=*/true,
5732 SourceLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00005733 CopyAssignment->setAccess(AS_public);
5734 CopyAssignment->setImplicit();
5735 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Douglas Gregord3c35902010-07-01 16:36:15 +00005736
5737 // Add the parameter to the operator.
5738 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005739 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregord3c35902010-07-01 16:36:15 +00005740 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00005741 SC_None,
5742 SC_None, 0);
Douglas Gregord3c35902010-07-01 16:36:15 +00005743 CopyAssignment->setParams(&FromParam, 1);
5744
Douglas Gregora376d102010-07-02 21:50:04 +00005745 // Note that we have added this copy-assignment operator.
Douglas Gregora376d102010-07-02 21:50:04 +00005746 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
5747
Douglas Gregor23c94db2010-07-02 17:43:08 +00005748 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora376d102010-07-02 21:50:04 +00005749 PushOnScopeChains(CopyAssignment, S, false);
5750 ClassDecl->addDecl(CopyAssignment);
Douglas Gregord3c35902010-07-01 16:36:15 +00005751
5752 AddOverriddenMethods(ClassDecl, CopyAssignment);
5753 return CopyAssignment;
5754}
5755
Douglas Gregor06a9f362010-05-01 20:49:11 +00005756void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
5757 CXXMethodDecl *CopyAssignOperator) {
5758 assert((CopyAssignOperator->isImplicit() &&
5759 CopyAssignOperator->isOverloadedOperator() &&
5760 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Douglas Gregorc070cc62010-06-17 23:14:26 +00005761 !CopyAssignOperator->isUsed(false)) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00005762 "DefineImplicitCopyAssignment called for wrong function");
5763
5764 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
5765
5766 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
5767 CopyAssignOperator->setInvalidDecl();
5768 return;
5769 }
5770
5771 CopyAssignOperator->setUsed();
5772
5773 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00005774 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005775
5776 // C++0x [class.copy]p30:
5777 // The implicitly-defined or explicitly-defaulted copy assignment operator
5778 // for a non-union class X performs memberwise copy assignment of its
5779 // subobjects. The direct base classes of X are assigned first, in the
5780 // order of their declaration in the base-specifier-list, and then the
5781 // immediate non-static data members of X are assigned, in the order in
5782 // which they were declared in the class definition.
5783
5784 // The statements that form the synthesized function body.
John McCallca0408f2010-08-23 06:44:23 +00005785 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005786
5787 // The parameter for the "other" object, which we are copying from.
5788 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
5789 Qualifiers OtherQuals = Other->getType().getQualifiers();
5790 QualType OtherRefType = Other->getType();
5791 if (const LValueReferenceType *OtherRef
5792 = OtherRefType->getAs<LValueReferenceType>()) {
5793 OtherRefType = OtherRef->getPointeeType();
5794 OtherQuals = OtherRefType.getQualifiers();
5795 }
5796
5797 // Our location for everything implicitly-generated.
5798 SourceLocation Loc = CopyAssignOperator->getLocation();
5799
5800 // Construct a reference to the "other" object. We'll be using this
5801 // throughout the generated ASTs.
John McCall09431682010-11-18 19:01:18 +00005802 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00005803 assert(OtherRef && "Reference to parameter cannot fail!");
5804
5805 // Construct the "this" pointer. We'll be using this throughout the generated
5806 // ASTs.
5807 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
5808 assert(This && "Reference to this cannot fail!");
5809
5810 // Assign base classes.
5811 bool Invalid = false;
5812 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5813 E = ClassDecl->bases_end(); Base != E; ++Base) {
5814 // Form the assignment:
5815 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
5816 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00005817 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00005818 Invalid = true;
5819 continue;
5820 }
5821
John McCallf871d0c2010-08-07 06:22:56 +00005822 CXXCastPath BasePath;
5823 BasePath.push_back(Base);
5824
Douglas Gregor06a9f362010-05-01 20:49:11 +00005825 // Construct the "from" expression, which is an implicit cast to the
5826 // appropriately-qualified base type.
John McCall3fa5cae2010-10-26 07:05:15 +00005827 Expr *From = OtherRef;
John Wiegley429bb272011-04-08 18:41:53 +00005828 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
5829 CK_UncheckedDerivedToBase,
5830 VK_LValue, &BasePath).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00005831
5832 // Dereference "this".
John McCall5baba9d2010-08-25 10:28:54 +00005833 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005834
5835 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley429bb272011-04-08 18:41:53 +00005836 To = ImpCastExprToType(To.take(),
5837 Context.getCVRQualifiedType(BaseType,
5838 CopyAssignOperator->getTypeQualifiers()),
5839 CK_UncheckedDerivedToBase,
5840 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005841
5842 // Build the copy.
John McCall60d7b3a2010-08-24 06:29:42 +00005843 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00005844 To.get(), From,
5845 /*CopyingBaseSubobject=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005846 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00005847 Diag(CurrentLocation, diag::note_member_synthesized_at)
5848 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5849 CopyAssignOperator->setInvalidDecl();
5850 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00005851 }
5852
5853 // Success! Record the copy.
5854 Statements.push_back(Copy.takeAs<Expr>());
5855 }
5856
5857 // \brief Reference to the __builtin_memcpy function.
5858 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00005859 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00005860 Expr *CollectableMemCpyRef = 0;
Douglas Gregor06a9f362010-05-01 20:49:11 +00005861
5862 // Assign non-static members.
5863 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5864 FieldEnd = ClassDecl->field_end();
5865 Field != FieldEnd; ++Field) {
5866 // Check for members of reference type; we can't copy those.
5867 if (Field->getType()->isReferenceType()) {
5868 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
5869 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
5870 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00005871 Diag(CurrentLocation, diag::note_member_synthesized_at)
5872 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005873 Invalid = true;
5874 continue;
5875 }
5876
5877 // Check for members of const-qualified, non-class type.
5878 QualType BaseType = Context.getBaseElementType(Field->getType());
5879 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
5880 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
5881 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
5882 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00005883 Diag(CurrentLocation, diag::note_member_synthesized_at)
5884 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005885 Invalid = true;
5886 continue;
5887 }
5888
5889 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00005890 if (FieldType->isIncompleteArrayType()) {
5891 assert(ClassDecl->hasFlexibleArrayMember() &&
5892 "Incomplete array type is not valid");
5893 continue;
5894 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00005895
5896 // Build references to the field in the object we're copying from and to.
5897 CXXScopeSpec SS; // Intentionally empty
5898 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
5899 LookupMemberName);
5900 MemberLookup.addDecl(*Field);
5901 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00005902 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall09431682010-11-18 19:01:18 +00005903 Loc, /*IsArrow=*/false,
5904 SS, 0, MemberLookup, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00005905 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall09431682010-11-18 19:01:18 +00005906 Loc, /*IsArrow=*/true,
5907 SS, 0, MemberLookup, 0);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005908 assert(!From.isInvalid() && "Implicit field reference cannot fail");
5909 assert(!To.isInvalid() && "Implicit field reference cannot fail");
5910
5911 // If the field should be copied with __builtin_memcpy rather than via
5912 // explicit assignments, do so. This optimization only applies for arrays
5913 // of scalars and arrays of class type with trivial copy-assignment
5914 // operators.
5915 if (FieldType->isArrayType() &&
5916 (!BaseType->isRecordType() ||
5917 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl())
5918 ->hasTrivialCopyAssignment())) {
5919 // Compute the size of the memory buffer to be copied.
5920 QualType SizeType = Context.getSizeType();
5921 llvm::APInt Size(Context.getTypeSize(SizeType),
5922 Context.getTypeSizeInChars(BaseType).getQuantity());
5923 for (const ConstantArrayType *Array
5924 = Context.getAsConstantArrayType(FieldType);
5925 Array;
5926 Array = Context.getAsConstantArrayType(Array->getElementType())) {
Jay Foad9f71a8f2010-12-07 08:25:34 +00005927 llvm::APInt ArraySize
5928 = Array->getSize().zextOrTrunc(Size.getBitWidth());
Douglas Gregor06a9f362010-05-01 20:49:11 +00005929 Size *= ArraySize;
5930 }
5931
5932 // Take the address of the field references for "from" and "to".
John McCall2de56d12010-08-25 11:45:40 +00005933 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
5934 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00005935
5936 bool NeedsCollectableMemCpy =
5937 (BaseType->isRecordType() &&
5938 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
5939
5940 if (NeedsCollectableMemCpy) {
5941 if (!CollectableMemCpyRef) {
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00005942 // Create a reference to the __builtin_objc_memmove_collectable function.
5943 LookupResult R(*this,
5944 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00005945 Loc, LookupOrdinaryName);
5946 LookupName(R, TUScope, true);
5947
5948 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
5949 if (!CollectableMemCpy) {
5950 // Something went horribly wrong earlier, and we will have
5951 // complained about it.
5952 Invalid = true;
5953 continue;
5954 }
5955
5956 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
5957 CollectableMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00005958 VK_LValue, Loc, 0).take();
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00005959 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
5960 }
5961 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00005962 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00005963 else if (!BuiltinMemCpyRef) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00005964 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
5965 LookupOrdinaryName);
5966 LookupName(R, TUScope, true);
5967
5968 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
5969 if (!BuiltinMemCpy) {
5970 // Something went horribly wrong earlier, and we will have complained
5971 // about it.
5972 Invalid = true;
5973 continue;
5974 }
5975
5976 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
5977 BuiltinMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00005978 VK_LValue, Loc, 0).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00005979 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
5980 }
5981
John McCallca0408f2010-08-23 06:44:23 +00005982 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005983 CallArgs.push_back(To.takeAs<Expr>());
5984 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00005985 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCall60d7b3a2010-08-24 06:29:42 +00005986 ExprResult Call = ExprError();
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005987 if (NeedsCollectableMemCpy)
5988 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00005989 CollectableMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005990 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00005991 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005992 else
5993 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00005994 BuiltinMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005995 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00005996 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005997
Douglas Gregor06a9f362010-05-01 20:49:11 +00005998 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
5999 Statements.push_back(Call.takeAs<Expr>());
6000 continue;
6001 }
6002
6003 // Build the copy of this field.
John McCall60d7b3a2010-08-24 06:29:42 +00006004 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
John McCall9ae2f072010-08-23 23:25:46 +00006005 To.get(), From.get(),
Douglas Gregor6cdc1612010-05-04 15:20:55 +00006006 /*CopyingBaseSubobject=*/false);
Douglas Gregor06a9f362010-05-01 20:49:11 +00006007 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00006008 Diag(CurrentLocation, diag::note_member_synthesized_at)
6009 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
6010 CopyAssignOperator->setInvalidDecl();
6011 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00006012 }
6013
6014 // Success! Record the copy.
6015 Statements.push_back(Copy.takeAs<Stmt>());
6016 }
6017
6018 if (!Invalid) {
6019 // Add a "return *this;"
John McCall2de56d12010-08-25 11:45:40 +00006020 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00006021
John McCall60d7b3a2010-08-24 06:29:42 +00006022 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00006023 if (Return.isInvalid())
6024 Invalid = true;
6025 else {
6026 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00006027
6028 if (Trap.hasErrorOccurred()) {
6029 Diag(CurrentLocation, diag::note_member_synthesized_at)
6030 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
6031 Invalid = true;
6032 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00006033 }
6034 }
6035
6036 if (Invalid) {
6037 CopyAssignOperator->setInvalidDecl();
6038 return;
6039 }
6040
John McCall60d7b3a2010-08-24 06:29:42 +00006041 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
Douglas Gregor06a9f362010-05-01 20:49:11 +00006042 /*isStmtExpr=*/false);
6043 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
6044 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redl58a2cd82011-04-24 16:28:06 +00006045
6046 if (ASTMutationListener *L = getASTMutationListener()) {
6047 L->CompletedImplicitDefinition(CopyAssignOperator);
6048 }
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00006049}
6050
Douglas Gregor23c94db2010-07-02 17:43:08 +00006051CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
6052 CXXRecordDecl *ClassDecl) {
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00006053 // C++ [class.copy]p4:
6054 // If the class definition does not explicitly declare a copy
6055 // constructor, one is declared implicitly.
6056
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00006057 // C++ [class.copy]p5:
6058 // The implicitly-declared copy constructor for a class X will
6059 // have the form
6060 //
6061 // X::X(const X&)
6062 //
6063 // if
6064 bool HasConstCopyConstructor = true;
6065
6066 // -- each direct or virtual base class B of X has a copy
6067 // constructor whose first parameter is of type const B& or
6068 // const volatile B&, and
6069 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
6070 BaseEnd = ClassDecl->bases_end();
6071 HasConstCopyConstructor && Base != BaseEnd;
6072 ++Base) {
Douglas Gregor598a8542010-07-01 18:27:03 +00006073 // Virtual bases are handled below.
6074 if (Base->isVirtual())
6075 continue;
6076
Douglas Gregor22584312010-07-02 23:41:54 +00006077 CXXRecordDecl *BaseClassDecl
Douglas Gregor598a8542010-07-01 18:27:03 +00006078 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00006079 if (!BaseClassDecl->hasDeclaredCopyConstructor())
6080 DeclareImplicitCopyConstructor(BaseClassDecl);
6081
Douglas Gregor598a8542010-07-01 18:27:03 +00006082 HasConstCopyConstructor
6083 = BaseClassDecl->hasConstCopyConstructor(Context);
6084 }
6085
6086 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
6087 BaseEnd = ClassDecl->vbases_end();
6088 HasConstCopyConstructor && Base != BaseEnd;
6089 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00006090 CXXRecordDecl *BaseClassDecl
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00006091 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00006092 if (!BaseClassDecl->hasDeclaredCopyConstructor())
6093 DeclareImplicitCopyConstructor(BaseClassDecl);
6094
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00006095 HasConstCopyConstructor
6096 = BaseClassDecl->hasConstCopyConstructor(Context);
6097 }
6098
6099 // -- for all the nonstatic data members of X that are of a
6100 // class type M (or array thereof), each such class type
6101 // has a copy constructor whose first parameter is of type
6102 // const M& or const volatile M&.
6103 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
6104 FieldEnd = ClassDecl->field_end();
6105 HasConstCopyConstructor && Field != FieldEnd;
6106 ++Field) {
Douglas Gregor598a8542010-07-01 18:27:03 +00006107 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00006108 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregor22584312010-07-02 23:41:54 +00006109 CXXRecordDecl *FieldClassDecl
Douglas Gregor598a8542010-07-01 18:27:03 +00006110 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00006111 if (!FieldClassDecl->hasDeclaredCopyConstructor())
6112 DeclareImplicitCopyConstructor(FieldClassDecl);
6113
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00006114 HasConstCopyConstructor
Douglas Gregor598a8542010-07-01 18:27:03 +00006115 = FieldClassDecl->hasConstCopyConstructor(Context);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00006116 }
6117 }
6118
6119 // Otherwise, the implicitly declared copy constructor will have
6120 // the form
6121 //
6122 // X::X(X&)
6123 QualType ClassType = Context.getTypeDeclType(ClassDecl);
6124 QualType ArgType = ClassType;
6125 if (HasConstCopyConstructor)
6126 ArgType = ArgType.withConst();
6127 ArgType = Context.getLValueReferenceType(ArgType);
6128
Douglas Gregor0d405db2010-07-01 20:59:04 +00006129 // C++ [except.spec]p14:
6130 // An implicitly declared special member function (Clause 12) shall have an
6131 // exception-specification. [...]
6132 ImplicitExceptionSpecification ExceptSpec(Context);
6133 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
6134 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
6135 BaseEnd = ClassDecl->bases_end();
6136 Base != BaseEnd;
6137 ++Base) {
6138 // Virtual bases are handled below.
6139 if (Base->isVirtual())
6140 continue;
6141
Douglas Gregor22584312010-07-02 23:41:54 +00006142 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00006143 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00006144 if (!BaseClassDecl->hasDeclaredCopyConstructor())
6145 DeclareImplicitCopyConstructor(BaseClassDecl);
6146
Douglas Gregor0d405db2010-07-01 20:59:04 +00006147 if (CXXConstructorDecl *CopyConstructor
6148 = BaseClassDecl->getCopyConstructor(Context, Quals))
6149 ExceptSpec.CalledDecl(CopyConstructor);
6150 }
6151 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
6152 BaseEnd = ClassDecl->vbases_end();
6153 Base != BaseEnd;
6154 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00006155 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00006156 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00006157 if (!BaseClassDecl->hasDeclaredCopyConstructor())
6158 DeclareImplicitCopyConstructor(BaseClassDecl);
6159
Douglas Gregor0d405db2010-07-01 20:59:04 +00006160 if (CXXConstructorDecl *CopyConstructor
6161 = BaseClassDecl->getCopyConstructor(Context, Quals))
6162 ExceptSpec.CalledDecl(CopyConstructor);
6163 }
6164 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
6165 FieldEnd = ClassDecl->field_end();
6166 Field != FieldEnd;
6167 ++Field) {
6168 QualType FieldType = Context.getBaseElementType((*Field)->getType());
6169 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregor22584312010-07-02 23:41:54 +00006170 CXXRecordDecl *FieldClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00006171 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00006172 if (!FieldClassDecl->hasDeclaredCopyConstructor())
6173 DeclareImplicitCopyConstructor(FieldClassDecl);
6174
Douglas Gregor0d405db2010-07-01 20:59:04 +00006175 if (CXXConstructorDecl *CopyConstructor
6176 = FieldClassDecl->getCopyConstructor(Context, Quals))
6177 ExceptSpec.CalledDecl(CopyConstructor);
6178 }
6179 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00006180
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00006181 // An implicitly-declared copy constructor is an inline public
6182 // member of its class.
John McCalle23cf432010-12-14 08:05:40 +00006183 FunctionProtoType::ExtProtoInfo EPI;
Sebastian Redl60618fa2011-03-12 11:50:43 +00006184 EPI.ExceptionSpecType = ExceptSpec.getExceptionSpecType();
John McCalle23cf432010-12-14 08:05:40 +00006185 EPI.NumExceptions = ExceptSpec.size();
6186 EPI.Exceptions = ExceptSpec.data();
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00006187 DeclarationName Name
6188 = Context.DeclarationNames.getCXXConstructorName(
6189 Context.getCanonicalType(ClassType));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006190 SourceLocation ClassLoc = ClassDecl->getLocation();
6191 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00006192 CXXConstructorDecl *CopyConstructor
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006193 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00006194 Context.getFunctionType(Context.VoidTy,
John McCalle23cf432010-12-14 08:05:40 +00006195 &ArgType, 1, EPI),
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00006196 /*TInfo=*/0,
6197 /*isExplicit=*/false,
6198 /*isInline=*/true,
Sean Hunt5f802e52011-05-06 00:11:07 +00006199 /*isImplicitlyDeclared=*/true);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00006200 CopyConstructor->setAccess(AS_public);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00006201 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
6202
Douglas Gregor22584312010-07-02 23:41:54 +00006203 // Note that we have declared this constructor.
Douglas Gregor22584312010-07-02 23:41:54 +00006204 ++ASTContext::NumImplicitCopyConstructorsDeclared;
6205
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00006206 // Add the parameter to the constructor.
6207 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006208 ClassLoc, ClassLoc,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00006209 /*IdentifierInfo=*/0,
6210 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00006211 SC_None,
6212 SC_None, 0);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00006213 CopyConstructor->setParams(&FromParam, 1);
Douglas Gregor23c94db2010-07-02 17:43:08 +00006214 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor22584312010-07-02 23:41:54 +00006215 PushOnScopeChains(CopyConstructor, S, false);
6216 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00006217
6218 return CopyConstructor;
6219}
6220
Fariborz Jahanian485f0872009-06-22 23:34:40 +00006221void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
6222 CXXConstructorDecl *CopyConstructor,
6223 unsigned TypeQuals) {
Mike Stump1eb44332009-09-09 15:08:12 +00006224 assert((CopyConstructor->isImplicit() &&
Douglas Gregor9e9199d2009-12-22 00:34:07 +00006225 CopyConstructor->isCopyConstructor(TypeQuals) &&
Douglas Gregorc070cc62010-06-17 23:14:26 +00006226 !CopyConstructor->isUsed(false)) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00006227 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00006228
Anders Carlsson63010a72010-04-23 16:24:12 +00006229 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00006230 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006231
Douglas Gregor39957dc2010-05-01 15:04:51 +00006232 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00006233 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006234
Sean Huntcbb67482011-01-08 20:30:50 +00006235 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00006236 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00006237 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00006238 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00006239 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00006240 } else {
6241 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
6242 CopyConstructor->getLocation(),
6243 MultiStmtArg(*this, 0, 0),
6244 /*isStmtExpr=*/false)
6245 .takeAs<Stmt>());
Anders Carlsson8e142cc2010-04-25 00:52:09 +00006246 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00006247
6248 CopyConstructor->setUsed();
Sebastian Redl58a2cd82011-04-24 16:28:06 +00006249
6250 if (ASTMutationListener *L = getASTMutationListener()) {
6251 L->CompletedImplicitDefinition(CopyConstructor);
6252 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +00006253}
6254
John McCall60d7b3a2010-08-24 06:29:42 +00006255ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00006256Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00006257 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00006258 MultiExprArg ExprArgs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006259 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00006260 unsigned ConstructKind,
6261 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00006262 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00006263
Douglas Gregor2f599792010-04-02 18:24:57 +00006264 // C++0x [class.copy]p34:
6265 // When certain criteria are met, an implementation is allowed to
6266 // omit the copy/move construction of a class object, even if the
6267 // copy/move constructor and/or destructor for the object have
6268 // side effects. [...]
6269 // - when a temporary class object that has not been bound to a
6270 // reference (12.2) would be copied/moved to a class object
6271 // with the same cv-unqualified type, the copy/move operation
6272 // can be omitted by constructing the temporary object
6273 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +00006274 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregor70a21de2011-01-27 23:24:55 +00006275 Constructor->isCopyOrMoveConstructor() && ExprArgs.size() >= 1) {
Douglas Gregor2f599792010-04-02 18:24:57 +00006276 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
John McCall558d2ab2010-09-15 10:14:12 +00006277 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00006278 }
Mike Stump1eb44332009-09-09 15:08:12 +00006279
6280 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006281 Elidable, move(ExprArgs), RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00006282 ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00006283}
6284
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00006285/// BuildCXXConstructExpr - Creates a complete call to a constructor,
6286/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00006287ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00006288Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
6289 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00006290 MultiExprArg ExprArgs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006291 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00006292 unsigned ConstructKind,
6293 SourceRange ParenRange) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00006294 unsigned NumExprs = ExprArgs.size();
6295 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00006296
Nick Lewycky909a70d2011-03-25 01:44:32 +00006297 for (specific_attr_iterator<NonNullAttr>
6298 i = Constructor->specific_attr_begin<NonNullAttr>(),
6299 e = Constructor->specific_attr_end<NonNullAttr>(); i != e; ++i) {
6300 const NonNullAttr *NonNull = *i;
6301 CheckNonNullArguments(NonNull, ExprArgs.get(), ConstructLoc);
6302 }
6303
Douglas Gregor7edfb692009-11-23 12:27:39 +00006304 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00006305 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor16006c92009-12-16 18:50:27 +00006306 Constructor, Elidable, Exprs, NumExprs,
John McCall7a1fad32010-08-24 07:32:53 +00006307 RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00006308 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
6309 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00006310}
6311
Mike Stump1eb44332009-09-09 15:08:12 +00006312bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00006313 CXXConstructorDecl *Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00006314 MultiExprArg Exprs) {
Chandler Carruth428edaf2010-10-25 08:47:36 +00006315 // FIXME: Provide the correct paren SourceRange when available.
John McCall60d7b3a2010-08-24 06:29:42 +00006316 ExprResult TempResult =
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00006317 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Chandler Carruth428edaf2010-10-25 08:47:36 +00006318 move(Exprs), false, CXXConstructExpr::CK_Complete,
6319 SourceRange());
Anders Carlssonfe2de492009-08-25 05:18:00 +00006320 if (TempResult.isInvalid())
6321 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00006322
Anders Carlssonda3f4e22009-08-25 05:12:04 +00006323 Expr *Temp = TempResult.takeAs<Expr>();
John McCallb4eb64d2010-10-08 02:01:28 +00006324 CheckImplicitConversions(Temp, VD->getLocation());
Douglas Gregord7f37bf2009-06-22 23:06:13 +00006325 MarkDeclarationReferenced(VD->getLocation(), Constructor);
John McCall4765fa02010-12-06 08:20:24 +00006326 Temp = MaybeCreateExprWithCleanups(Temp);
Douglas Gregor838db382010-02-11 01:19:42 +00006327 VD->setInit(Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00006328
Anders Carlssonfe2de492009-08-25 05:18:00 +00006329 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00006330}
6331
John McCall68c6c9a2010-02-02 09:10:11 +00006332void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00006333 if (VD->isInvalidDecl()) return;
6334
John McCall68c6c9a2010-02-02 09:10:11 +00006335 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00006336 if (ClassDecl->isInvalidDecl()) return;
6337 if (ClassDecl->hasTrivialDestructor()) return;
6338 if (ClassDecl->isDependentContext()) return;
John McCall626e96e2010-08-01 20:20:59 +00006339
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00006340 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
6341 MarkDeclarationReferenced(VD->getLocation(), Destructor);
6342 CheckDestructorAccess(VD->getLocation(), Destructor,
6343 PDiag(diag::err_access_dtor_var)
6344 << VD->getDeclName()
6345 << VD->getType());
Anders Carlsson2b32dad2011-03-24 01:01:41 +00006346
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00006347 if (!VD->hasGlobalStorage()) return;
6348
6349 // Emit warning for non-trivial dtor in global scope (a real global,
6350 // class-static, function-static).
6351 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
6352
6353 // TODO: this should be re-enabled for static locals by !CXAAtExit
6354 if (!VD->isStaticLocal())
6355 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00006356}
6357
Mike Stump1eb44332009-09-09 15:08:12 +00006358/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006359/// ActOnDeclarator, when a C++ direct initializer is present.
6360/// e.g: "int x(1);"
John McCalld226f652010-08-21 09:40:31 +00006361void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006362 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +00006363 MultiExprArg Exprs,
Richard Smith34b41d92011-02-20 03:19:35 +00006364 SourceLocation RParenLoc,
6365 bool TypeMayContainAuto) {
Daniel Dunbar51846262009-12-24 19:19:26 +00006366 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006367
6368 // If there is no declaration, there was an error parsing it. Just ignore
6369 // the initializer.
Chris Lattnerb28317a2009-03-28 19:18:32 +00006370 if (RealDecl == 0)
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006371 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006372
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006373 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
6374 if (!VDecl) {
6375 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
6376 RealDecl->setInvalidDecl();
6377 return;
6378 }
6379
Richard Smith34b41d92011-02-20 03:19:35 +00006380 // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
6381 if (TypeMayContainAuto && VDecl->getType()->getContainedAutoType()) {
Richard Smith34b41d92011-02-20 03:19:35 +00006382 // FIXME: n3225 doesn't actually seem to indicate this is ill-formed
6383 if (Exprs.size() > 1) {
6384 Diag(Exprs.get()[1]->getSourceRange().getBegin(),
6385 diag::err_auto_var_init_multiple_expressions)
6386 << VDecl->getDeclName() << VDecl->getType()
6387 << VDecl->getSourceRange();
6388 RealDecl->setInvalidDecl();
6389 return;
6390 }
6391
6392 Expr *Init = Exprs.get()[0];
Richard Smitha085da82011-03-17 16:11:59 +00006393 TypeSourceInfo *DeducedType = 0;
6394 if (!DeduceAutoType(VDecl->getTypeSourceInfo(), Init, DeducedType))
Richard Smith34b41d92011-02-20 03:19:35 +00006395 Diag(VDecl->getLocation(), diag::err_auto_var_deduction_failure)
6396 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
6397 << Init->getSourceRange();
Richard Smitha085da82011-03-17 16:11:59 +00006398 if (!DeducedType) {
Richard Smith34b41d92011-02-20 03:19:35 +00006399 RealDecl->setInvalidDecl();
6400 return;
6401 }
Richard Smitha085da82011-03-17 16:11:59 +00006402 VDecl->setTypeSourceInfo(DeducedType);
6403 VDecl->setType(DeducedType->getType());
Richard Smith34b41d92011-02-20 03:19:35 +00006404
6405 // If this is a redeclaration, check that the type we just deduced matches
6406 // the previously declared type.
6407 if (VarDecl *Old = VDecl->getPreviousDeclaration())
6408 MergeVarDeclTypes(VDecl, Old);
6409 }
6410
Douglas Gregor83ddad32009-08-26 21:14:46 +00006411 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00006412 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006413 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
6414 //
6415 // Clients that want to distinguish between the two forms, can check for
6416 // direct initializer using VarDecl::hasCXXDirectInitializer().
6417 // A major benefit is that clients that don't particularly care about which
6418 // exactly form was it (like the CodeGen) can handle both cases without
6419 // special case code.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00006420
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006421 // C++ 8.5p11:
6422 // The form of initialization (using parentheses or '=') is generally
6423 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00006424 // class type.
6425
Douglas Gregor4dffad62010-02-11 22:55:30 +00006426 if (!VDecl->getType()->isDependentType() &&
6427 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor615c5d42009-03-24 16:43:20 +00006428 diag::err_typecheck_decl_incomplete_type)) {
6429 VDecl->setInvalidDecl();
6430 return;
6431 }
6432
Douglas Gregor90f93822009-12-22 22:17:25 +00006433 // The variable can not have an abstract class type.
6434 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
6435 diag::err_abstract_type_in_decl,
6436 AbstractVariableType))
6437 VDecl->setInvalidDecl();
6438
Sebastian Redl31310a22010-02-01 20:16:42 +00006439 const VarDecl *Def;
6440 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregor90f93822009-12-22 22:17:25 +00006441 Diag(VDecl->getLocation(), diag::err_redefinition)
6442 << VDecl->getDeclName();
6443 Diag(Def->getLocation(), diag::note_previous_definition);
6444 VDecl->setInvalidDecl();
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00006445 return;
6446 }
Douglas Gregor4dffad62010-02-11 22:55:30 +00006447
Douglas Gregor3a91abf2010-08-24 05:27:49 +00006448 // C++ [class.static.data]p4
6449 // If a static data member is of const integral or const
6450 // enumeration type, its declaration in the class definition can
6451 // specify a constant-initializer which shall be an integral
6452 // constant expression (5.19). In that case, the member can appear
6453 // in integral constant expressions. The member shall still be
6454 // defined in a namespace scope if it is used in the program and the
6455 // namespace scope definition shall not contain an initializer.
6456 //
6457 // We already performed a redefinition check above, but for static
6458 // data members we also need to check whether there was an in-class
6459 // declaration with an initializer.
6460 const VarDecl* PrevInit = 0;
6461 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
6462 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
6463 Diag(PrevInit->getLocation(), diag::note_previous_definition);
6464 return;
6465 }
6466
Douglas Gregora31040f2010-12-16 01:31:22 +00006467 bool IsDependent = false;
6468 for (unsigned I = 0, N = Exprs.size(); I != N; ++I) {
6469 if (DiagnoseUnexpandedParameterPack(Exprs.get()[I], UPPC_Expression)) {
6470 VDecl->setInvalidDecl();
6471 return;
6472 }
6473
6474 if (Exprs.get()[I]->isTypeDependent())
6475 IsDependent = true;
6476 }
6477
Douglas Gregor4dffad62010-02-11 22:55:30 +00006478 // If either the declaration has a dependent type or if any of the
6479 // expressions is type-dependent, we represent the initialization
6480 // via a ParenListExpr for later use during template instantiation.
Douglas Gregora31040f2010-12-16 01:31:22 +00006481 if (VDecl->getType()->isDependentType() || IsDependent) {
Douglas Gregor4dffad62010-02-11 22:55:30 +00006482 // Let clients know that initialization was done with a direct initializer.
6483 VDecl->setCXXDirectInitializer(true);
6484
6485 // Store the initialization expressions as a ParenListExpr.
6486 unsigned NumExprs = Exprs.size();
6487 VDecl->setInit(new (Context) ParenListExpr(Context, LParenLoc,
6488 (Expr **)Exprs.release(),
6489 NumExprs, RParenLoc));
6490 return;
6491 }
Douglas Gregor90f93822009-12-22 22:17:25 +00006492
6493 // Capture the variable that is being initialized and the style of
6494 // initialization.
6495 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
6496
6497 // FIXME: Poor source location information.
6498 InitializationKind Kind
6499 = InitializationKind::CreateDirect(VDecl->getLocation(),
6500 LParenLoc, RParenLoc);
6501
6502 InitializationSequence InitSeq(*this, Entity, Kind,
John McCall9ae2f072010-08-23 23:25:46 +00006503 Exprs.get(), Exprs.size());
John McCall60d7b3a2010-08-24 06:29:42 +00006504 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
Douglas Gregor90f93822009-12-22 22:17:25 +00006505 if (Result.isInvalid()) {
6506 VDecl->setInvalidDecl();
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006507 return;
6508 }
John McCallb4eb64d2010-10-08 02:01:28 +00006509
6510 CheckImplicitConversions(Result.get(), LParenLoc);
Douglas Gregor90f93822009-12-22 22:17:25 +00006511
Douglas Gregor53c374f2010-12-07 00:41:46 +00006512 Result = MaybeCreateExprWithCleanups(Result);
Douglas Gregor838db382010-02-11 01:19:42 +00006513 VDecl->setInit(Result.takeAs<Expr>());
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006514 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00006515
John McCall2998d6b2011-01-19 11:48:09 +00006516 CheckCompleteVariableDeclaration(VDecl);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006517}
Douglas Gregor27c8dc02008-10-29 00:13:59 +00006518
Douglas Gregor39da0b82009-09-09 23:08:42 +00006519/// \brief Given a constructor and the set of arguments provided for the
6520/// constructor, convert the arguments and add any required default arguments
6521/// to form a proper call to this constructor.
6522///
6523/// \returns true if an error occurred, false otherwise.
6524bool
6525Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
6526 MultiExprArg ArgsPtr,
6527 SourceLocation Loc,
John McCallca0408f2010-08-23 06:44:23 +00006528 ASTOwningVector<Expr*> &ConvertedArgs) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00006529 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
6530 unsigned NumArgs = ArgsPtr.size();
6531 Expr **Args = (Expr **)ArgsPtr.get();
6532
6533 const FunctionProtoType *Proto
6534 = Constructor->getType()->getAs<FunctionProtoType>();
6535 assert(Proto && "Constructor without a prototype?");
6536 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00006537
6538 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00006539 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00006540 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00006541 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00006542 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00006543
6544 VariadicCallType CallType =
6545 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
6546 llvm::SmallVector<Expr *, 8> AllArgs;
6547 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
6548 Proto, 0, Args, NumArgs, AllArgs,
6549 CallType);
6550 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
6551 ConvertedArgs.push_back(AllArgs[i]);
6552 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00006553}
6554
Anders Carlsson20d45d22009-12-12 00:32:00 +00006555static inline bool
6556CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
6557 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00006558 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +00006559 if (isa<NamespaceDecl>(DC)) {
6560 return SemaRef.Diag(FnDecl->getLocation(),
6561 diag::err_operator_new_delete_declared_in_namespace)
6562 << FnDecl->getDeclName();
6563 }
6564
6565 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +00006566 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00006567 return SemaRef.Diag(FnDecl->getLocation(),
6568 diag::err_operator_new_delete_declared_static)
6569 << FnDecl->getDeclName();
6570 }
6571
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00006572 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00006573}
6574
Anders Carlsson156c78e2009-12-13 17:53:43 +00006575static inline bool
6576CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
6577 CanQualType ExpectedResultType,
6578 CanQualType ExpectedFirstParamType,
6579 unsigned DependentParamTypeDiag,
6580 unsigned InvalidParamTypeDiag) {
6581 QualType ResultType =
6582 FnDecl->getType()->getAs<FunctionType>()->getResultType();
6583
6584 // Check that the result type is not dependent.
6585 if (ResultType->isDependentType())
6586 return SemaRef.Diag(FnDecl->getLocation(),
6587 diag::err_operator_new_delete_dependent_result_type)
6588 << FnDecl->getDeclName() << ExpectedResultType;
6589
6590 // Check that the result type is what we expect.
6591 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
6592 return SemaRef.Diag(FnDecl->getLocation(),
6593 diag::err_operator_new_delete_invalid_result_type)
6594 << FnDecl->getDeclName() << ExpectedResultType;
6595
6596 // A function template must have at least 2 parameters.
6597 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
6598 return SemaRef.Diag(FnDecl->getLocation(),
6599 diag::err_operator_new_delete_template_too_few_parameters)
6600 << FnDecl->getDeclName();
6601
6602 // The function decl must have at least 1 parameter.
6603 if (FnDecl->getNumParams() == 0)
6604 return SemaRef.Diag(FnDecl->getLocation(),
6605 diag::err_operator_new_delete_too_few_parameters)
6606 << FnDecl->getDeclName();
6607
6608 // Check the the first parameter type is not dependent.
6609 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
6610 if (FirstParamType->isDependentType())
6611 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
6612 << FnDecl->getDeclName() << ExpectedFirstParamType;
6613
6614 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +00006615 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +00006616 ExpectedFirstParamType)
6617 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
6618 << FnDecl->getDeclName() << ExpectedFirstParamType;
6619
6620 return false;
6621}
6622
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00006623static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +00006624CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00006625 // C++ [basic.stc.dynamic.allocation]p1:
6626 // A program is ill-formed if an allocation function is declared in a
6627 // namespace scope other than global scope or declared static in global
6628 // scope.
6629 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
6630 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +00006631
6632 CanQualType SizeTy =
6633 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
6634
6635 // C++ [basic.stc.dynamic.allocation]p1:
6636 // The return type shall be void*. The first parameter shall have type
6637 // std::size_t.
6638 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
6639 SizeTy,
6640 diag::err_operator_new_dependent_param_type,
6641 diag::err_operator_new_param_type))
6642 return true;
6643
6644 // C++ [basic.stc.dynamic.allocation]p1:
6645 // The first parameter shall not have an associated default argument.
6646 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +00006647 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +00006648 diag::err_operator_new_default_arg)
6649 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
6650
6651 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +00006652}
6653
6654static bool
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00006655CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
6656 // C++ [basic.stc.dynamic.deallocation]p1:
6657 // A program is ill-formed if deallocation functions are declared in a
6658 // namespace scope other than global scope or declared static in global
6659 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +00006660 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
6661 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00006662
6663 // C++ [basic.stc.dynamic.deallocation]p2:
6664 // Each deallocation function shall return void and its first parameter
6665 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +00006666 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
6667 SemaRef.Context.VoidPtrTy,
6668 diag::err_operator_delete_dependent_param_type,
6669 diag::err_operator_delete_param_type))
6670 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00006671
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00006672 return false;
6673}
6674
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006675/// CheckOverloadedOperatorDeclaration - Check whether the declaration
6676/// of this overloaded operator is well-formed. If so, returns false;
6677/// otherwise, emits appropriate diagnostics and returns true.
6678bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00006679 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006680 "Expected an overloaded operator declaration");
6681
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006682 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
6683
Mike Stump1eb44332009-09-09 15:08:12 +00006684 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006685 // The allocation and deallocation functions, operator new,
6686 // operator new[], operator delete and operator delete[], are
6687 // described completely in 3.7.3. The attributes and restrictions
6688 // found in the rest of this subclause do not apply to them unless
6689 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +00006690 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00006691 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00006692
Anders Carlssona3ccda52009-12-12 00:26:23 +00006693 if (Op == OO_New || Op == OO_Array_New)
6694 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006695
6696 // C++ [over.oper]p6:
6697 // An operator function shall either be a non-static member
6698 // function or be a non-member function and have at least one
6699 // parameter whose type is a class, a reference to a class, an
6700 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00006701 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
6702 if (MethodDecl->isStatic())
6703 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00006704 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006705 } else {
6706 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00006707 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
6708 ParamEnd = FnDecl->param_end();
6709 Param != ParamEnd; ++Param) {
6710 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00006711 if (ParamType->isDependentType() || ParamType->isRecordType() ||
6712 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006713 ClassOrEnumParam = true;
6714 break;
6715 }
6716 }
6717
Douglas Gregor43c7bad2008-11-17 16:14:12 +00006718 if (!ClassOrEnumParam)
6719 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00006720 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00006721 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006722 }
6723
6724 // C++ [over.oper]p8:
6725 // An operator function cannot have default arguments (8.3.6),
6726 // except where explicitly stated below.
6727 //
Mike Stump1eb44332009-09-09 15:08:12 +00006728 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006729 // (C++ [over.call]p1).
6730 if (Op != OO_Call) {
6731 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
6732 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +00006733 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00006734 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00006735 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +00006736 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006737 }
6738 }
6739
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00006740 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
6741 { false, false, false }
6742#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
6743 , { Unary, Binary, MemberOnly }
6744#include "clang/Basic/OperatorKinds.def"
6745 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006746
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00006747 bool CanBeUnaryOperator = OperatorUses[Op][0];
6748 bool CanBeBinaryOperator = OperatorUses[Op][1];
6749 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006750
6751 // C++ [over.oper]p8:
6752 // [...] Operator functions cannot have more or fewer parameters
6753 // than the number required for the corresponding operator, as
6754 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00006755 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00006756 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006757 if (Op != OO_Call &&
6758 ((NumParams == 1 && !CanBeUnaryOperator) ||
6759 (NumParams == 2 && !CanBeBinaryOperator) ||
6760 (NumParams < 1) || (NumParams > 2))) {
6761 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00006762 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00006763 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00006764 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00006765 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00006766 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00006767 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00006768 assert(CanBeBinaryOperator &&
6769 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00006770 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00006771 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006772
Chris Lattner416e46f2008-11-21 07:57:12 +00006773 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00006774 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006775 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00006776
Douglas Gregor43c7bad2008-11-17 16:14:12 +00006777 // Overloaded operators other than operator() cannot be variadic.
6778 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00006779 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00006780 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00006781 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006782 }
6783
6784 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00006785 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
6786 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00006787 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00006788 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006789 }
6790
6791 // C++ [over.inc]p1:
6792 // The user-defined function called operator++ implements the
6793 // prefix and postfix ++ operator. If this function is a member
6794 // function with no parameters, or a non-member function with one
6795 // parameter of class or enumeration type, it defines the prefix
6796 // increment operator ++ for objects of that type. If the function
6797 // is a member function with one parameter (which shall be of type
6798 // int) or a non-member function with two parameters (the second
6799 // of which shall be of type int), it defines the postfix
6800 // increment operator ++ for objects of that type.
6801 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
6802 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
6803 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00006804 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006805 ParamIsInt = BT->getKind() == BuiltinType::Int;
6806
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00006807 if (!ParamIsInt)
6808 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00006809 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00006810 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006811 }
6812
Douglas Gregor43c7bad2008-11-17 16:14:12 +00006813 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006814}
Chris Lattner5a003a42008-12-17 07:09:26 +00006815
Sean Hunta6c058d2010-01-13 09:01:02 +00006816/// CheckLiteralOperatorDeclaration - Check whether the declaration
6817/// of this literal operator function is well-formed. If so, returns
6818/// false; otherwise, emits appropriate diagnostics and returns true.
6819bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
6820 DeclContext *DC = FnDecl->getDeclContext();
6821 Decl::Kind Kind = DC->getDeclKind();
6822 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
6823 Kind != Decl::LinkageSpec) {
6824 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
6825 << FnDecl->getDeclName();
6826 return true;
6827 }
6828
6829 bool Valid = false;
6830
Sean Hunt216c2782010-04-07 23:11:06 +00006831 // template <char...> type operator "" name() is the only valid template
6832 // signature, and the only valid signature with no parameters.
6833 if (FnDecl->param_size() == 0) {
6834 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
6835 // Must have only one template parameter
6836 TemplateParameterList *Params = TpDecl->getTemplateParameters();
6837 if (Params->size() == 1) {
6838 NonTypeTemplateParmDecl *PmDecl =
6839 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +00006840
Sean Hunt216c2782010-04-07 23:11:06 +00006841 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +00006842 if (PmDecl && PmDecl->isTemplateParameterPack() &&
6843 Context.hasSameType(PmDecl->getType(), Context.CharTy))
6844 Valid = true;
6845 }
6846 }
6847 } else {
Sean Hunta6c058d2010-01-13 09:01:02 +00006848 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +00006849 FunctionDecl::param_iterator Param = FnDecl->param_begin();
6850
Sean Hunta6c058d2010-01-13 09:01:02 +00006851 QualType T = (*Param)->getType();
6852
Sean Hunt30019c02010-04-07 22:57:35 +00006853 // unsigned long long int, long double, and any character type are allowed
6854 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +00006855 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
6856 Context.hasSameType(T, Context.LongDoubleTy) ||
6857 Context.hasSameType(T, Context.CharTy) ||
6858 Context.hasSameType(T, Context.WCharTy) ||
6859 Context.hasSameType(T, Context.Char16Ty) ||
6860 Context.hasSameType(T, Context.Char32Ty)) {
6861 if (++Param == FnDecl->param_end())
6862 Valid = true;
6863 goto FinishedParams;
6864 }
6865
Sean Hunt30019c02010-04-07 22:57:35 +00006866 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +00006867 const PointerType *PT = T->getAs<PointerType>();
6868 if (!PT)
6869 goto FinishedParams;
6870 T = PT->getPointeeType();
6871 if (!T.isConstQualified())
6872 goto FinishedParams;
6873 T = T.getUnqualifiedType();
6874
6875 // Move on to the second parameter;
6876 ++Param;
6877
6878 // If there is no second parameter, the first must be a const char *
6879 if (Param == FnDecl->param_end()) {
6880 if (Context.hasSameType(T, Context.CharTy))
6881 Valid = true;
6882 goto FinishedParams;
6883 }
6884
6885 // const char *, const wchar_t*, const char16_t*, and const char32_t*
6886 // are allowed as the first parameter to a two-parameter function
6887 if (!(Context.hasSameType(T, Context.CharTy) ||
6888 Context.hasSameType(T, Context.WCharTy) ||
6889 Context.hasSameType(T, Context.Char16Ty) ||
6890 Context.hasSameType(T, Context.Char32Ty)))
6891 goto FinishedParams;
6892
6893 // The second and final parameter must be an std::size_t
6894 T = (*Param)->getType().getUnqualifiedType();
6895 if (Context.hasSameType(T, Context.getSizeType()) &&
6896 ++Param == FnDecl->param_end())
6897 Valid = true;
6898 }
6899
6900 // FIXME: This diagnostic is absolutely terrible.
6901FinishedParams:
6902 if (!Valid) {
6903 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
6904 << FnDecl->getDeclName();
6905 return true;
6906 }
6907
6908 return false;
6909}
6910
Douglas Gregor074149e2009-01-05 19:45:36 +00006911/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
6912/// linkage specification, including the language and (if present)
6913/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
6914/// the location of the language string literal, which is provided
6915/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
6916/// the '{' brace. Otherwise, this linkage specification does not
6917/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +00006918Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
6919 SourceLocation LangLoc,
6920 llvm::StringRef Lang,
6921 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00006922 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +00006923 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00006924 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +00006925 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00006926 Language = LinkageSpecDecl::lang_cxx;
6927 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00006928 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +00006929 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +00006930 }
Mike Stump1eb44332009-09-09 15:08:12 +00006931
Chris Lattnercc98eac2008-12-17 07:13:27 +00006932 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +00006933
Douglas Gregor074149e2009-01-05 19:45:36 +00006934 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00006935 ExternLoc, LangLoc, Language);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006936 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00006937 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +00006938 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +00006939}
6940
Abramo Bagnara35f9a192010-07-30 16:47:02 +00006941/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +00006942/// the C++ linkage specification LinkageSpec. If RBraceLoc is
6943/// valid, it's the position of the closing '}' brace in a linkage
6944/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +00006945Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +00006946 Decl *LinkageSpec,
6947 SourceLocation RBraceLoc) {
6948 if (LinkageSpec) {
6949 if (RBraceLoc.isValid()) {
6950 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
6951 LSDecl->setRBraceLoc(RBraceLoc);
6952 }
Douglas Gregor074149e2009-01-05 19:45:36 +00006953 PopDeclContext();
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +00006954 }
Douglas Gregor074149e2009-01-05 19:45:36 +00006955 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00006956}
6957
Douglas Gregord308e622009-05-18 20:51:54 +00006958/// \brief Perform semantic analysis for the variable declaration that
6959/// occurs within a C++ catch clause, returning the newly-created
6960/// variable.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006961VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +00006962 TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006963 SourceLocation StartLoc,
6964 SourceLocation Loc,
6965 IdentifierInfo *Name) {
Douglas Gregord308e622009-05-18 20:51:54 +00006966 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +00006967 QualType ExDeclType = TInfo->getType();
6968
Sebastian Redl4b07b292008-12-22 19:15:10 +00006969 // Arrays and functions decay.
6970 if (ExDeclType->isArrayType())
6971 ExDeclType = Context.getArrayDecayedType(ExDeclType);
6972 else if (ExDeclType->isFunctionType())
6973 ExDeclType = Context.getPointerType(ExDeclType);
6974
6975 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
6976 // The exception-declaration shall not denote a pointer or reference to an
6977 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00006978 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +00006979 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +00006980 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +00006981 Invalid = true;
6982 }
Douglas Gregord308e622009-05-18 20:51:54 +00006983
Douglas Gregora2762912010-03-08 01:47:36 +00006984 // GCC allows catching pointers and references to incomplete types
6985 // as an extension; so do we, but we warn by default.
6986
Sebastian Redl4b07b292008-12-22 19:15:10 +00006987 QualType BaseType = ExDeclType;
6988 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00006989 unsigned DK = diag::err_catch_incomplete;
Douglas Gregora2762912010-03-08 01:47:36 +00006990 bool IncompleteCatchIsInvalid = true;
Ted Kremenek6217b802009-07-29 21:53:49 +00006991 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00006992 BaseType = Ptr->getPointeeType();
6993 Mode = 1;
Douglas Gregora2762912010-03-08 01:47:36 +00006994 DK = diag::ext_catch_incomplete_ptr;
6995 IncompleteCatchIsInvalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +00006996 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00006997 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00006998 BaseType = Ref->getPointeeType();
6999 Mode = 2;
Douglas Gregora2762912010-03-08 01:47:36 +00007000 DK = diag::ext_catch_incomplete_ref;
7001 IncompleteCatchIsInvalid = false;
Sebastian Redl4b07b292008-12-22 19:15:10 +00007002 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00007003 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregora2762912010-03-08 01:47:36 +00007004 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
7005 IncompleteCatchIsInvalid)
Sebastian Redl4b07b292008-12-22 19:15:10 +00007006 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00007007
Mike Stump1eb44332009-09-09 15:08:12 +00007008 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +00007009 RequireNonAbstractType(Loc, ExDeclType,
7010 diag::err_abstract_type_in_decl,
7011 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00007012 Invalid = true;
7013
John McCall5a180392010-07-24 00:37:23 +00007014 // Only the non-fragile NeXT runtime currently supports C++ catches
7015 // of ObjC types, and no runtime supports catching ObjC types by value.
7016 if (!Invalid && getLangOptions().ObjC1) {
7017 QualType T = ExDeclType;
7018 if (const ReferenceType *RT = T->getAs<ReferenceType>())
7019 T = RT->getPointeeType();
7020
7021 if (T->isObjCObjectType()) {
7022 Diag(Loc, diag::err_objc_object_catch);
7023 Invalid = true;
7024 } else if (T->isObjCObjectPointerType()) {
David Chisnall80558d22011-03-20 21:35:39 +00007025 if (!getLangOptions().ObjCNonFragileABI) {
John McCall5a180392010-07-24 00:37:23 +00007026 Diag(Loc, diag::err_objc_pointer_cxx_catch_fragile);
7027 Invalid = true;
7028 }
7029 }
7030 }
7031
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007032 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
7033 ExDeclType, TInfo, SC_None, SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +00007034 ExDecl->setExceptionVariable(true);
7035
Douglas Gregor6d182892010-03-05 23:38:39 +00007036 if (!Invalid) {
John McCalle996ffd2011-02-16 08:02:54 +00007037 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
Douglas Gregor6d182892010-03-05 23:38:39 +00007038 // C++ [except.handle]p16:
7039 // The object declared in an exception-declaration or, if the
7040 // exception-declaration does not specify a name, a temporary (12.2) is
7041 // copy-initialized (8.5) from the exception object. [...]
7042 // The object is destroyed when the handler exits, after the destruction
7043 // of any automatic objects initialized within the handler.
7044 //
7045 // We just pretend to initialize the object with itself, then make sure
7046 // it can be destroyed later.
John McCalle996ffd2011-02-16 08:02:54 +00007047 QualType initType = ExDeclType;
7048
7049 InitializedEntity entity =
7050 InitializedEntity::InitializeVariable(ExDecl);
7051 InitializationKind initKind =
7052 InitializationKind::CreateCopy(Loc, SourceLocation());
7053
7054 Expr *opaqueValue =
7055 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
7056 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
7057 ExprResult result = sequence.Perform(*this, entity, initKind,
7058 MultiExprArg(&opaqueValue, 1));
7059 if (result.isInvalid())
Douglas Gregor6d182892010-03-05 23:38:39 +00007060 Invalid = true;
John McCalle996ffd2011-02-16 08:02:54 +00007061 else {
7062 // If the constructor used was non-trivial, set this as the
7063 // "initializer".
7064 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
7065 if (!construct->getConstructor()->isTrivial()) {
7066 Expr *init = MaybeCreateExprWithCleanups(construct);
7067 ExDecl->setInit(init);
7068 }
7069
7070 // And make sure it's destructable.
7071 FinalizeVarWithDestructor(ExDecl, recordType);
7072 }
Douglas Gregor6d182892010-03-05 23:38:39 +00007073 }
7074 }
7075
Douglas Gregord308e622009-05-18 20:51:54 +00007076 if (Invalid)
7077 ExDecl->setInvalidDecl();
7078
7079 return ExDecl;
7080}
7081
7082/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
7083/// handler.
John McCalld226f652010-08-21 09:40:31 +00007084Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +00007085 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +00007086 bool Invalid = D.isInvalidType();
7087
7088 // Check for unexpanded parameter packs.
7089 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
7090 UPPC_ExceptionType)) {
7091 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
7092 D.getIdentifierLoc());
7093 Invalid = true;
7094 }
7095
Sebastian Redl4b07b292008-12-22 19:15:10 +00007096 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +00007097 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +00007098 LookupOrdinaryName,
7099 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00007100 // The scope should be freshly made just for us. There is just no way
7101 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +00007102 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +00007103 if (PrevDecl->isTemplateParameter()) {
7104 // Maybe we will complain about the shadowed template parameter.
7105 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00007106 }
7107 }
7108
Chris Lattnereaaebc72009-04-25 08:06:05 +00007109 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00007110 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
7111 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00007112 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00007113 }
7114
Douglas Gregor83cb9422010-09-09 17:09:21 +00007115 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007116 D.getSourceRange().getBegin(),
7117 D.getIdentifierLoc(),
7118 D.getIdentifier());
Chris Lattnereaaebc72009-04-25 08:06:05 +00007119 if (Invalid)
7120 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00007121
Sebastian Redl4b07b292008-12-22 19:15:10 +00007122 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00007123 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00007124 PushOnScopeChains(ExDecl, S);
7125 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00007126 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00007127
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00007128 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +00007129 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +00007130}
Anders Carlssonfb311762009-03-14 00:25:26 +00007131
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00007132Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +00007133 Expr *AssertExpr,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00007134 Expr *AssertMessageExpr_,
7135 SourceLocation RParenLoc) {
John McCall9ae2f072010-08-23 23:25:46 +00007136 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
Anders Carlssonfb311762009-03-14 00:25:26 +00007137
Anders Carlssonc3082412009-03-14 00:33:21 +00007138 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
7139 llvm::APSInt Value(32);
7140 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00007141 Diag(StaticAssertLoc,
7142 diag::err_static_assert_expression_is_not_constant) <<
Anders Carlssonc3082412009-03-14 00:33:21 +00007143 AssertExpr->getSourceRange();
John McCalld226f652010-08-21 09:40:31 +00007144 return 0;
Anders Carlssonc3082412009-03-14 00:33:21 +00007145 }
Anders Carlssonfb311762009-03-14 00:25:26 +00007146
Anders Carlssonc3082412009-03-14 00:33:21 +00007147 if (Value == 0) {
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00007148 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Benjamin Kramer8d042582009-12-11 13:33:18 +00007149 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlssonc3082412009-03-14 00:33:21 +00007150 }
7151 }
Mike Stump1eb44332009-09-09 15:08:12 +00007152
Douglas Gregor399ad972010-12-15 23:55:21 +00007153 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
7154 return 0;
7155
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00007156 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
7157 AssertExpr, AssertMessage, RParenLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00007158
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00007159 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +00007160 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +00007161}
Sebastian Redl50de12f2009-03-24 22:27:57 +00007162
Douglas Gregor1d869352010-04-07 16:53:43 +00007163/// \brief Perform semantic analysis of the given friend type declaration.
7164///
7165/// \returns A friend declaration that.
7166FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc,
7167 TypeSourceInfo *TSInfo) {
7168 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
7169
7170 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00007171 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +00007172
Douglas Gregor06245bf2010-04-07 17:57:12 +00007173 if (!getLangOptions().CPlusPlus0x) {
7174 // C++03 [class.friend]p2:
7175 // An elaborated-type-specifier shall be used in a friend declaration
7176 // for a class.*
7177 //
7178 // * The class-key of the elaborated-type-specifier is required.
7179 if (!ActiveTemplateInstantiations.empty()) {
7180 // Do not complain about the form of friend template types during
7181 // template instantiation; we will already have complained when the
7182 // template was declared.
7183 } else if (!T->isElaboratedTypeSpecifier()) {
7184 // If we evaluated the type to a record type, suggest putting
7185 // a tag in front.
7186 if (const RecordType *RT = T->getAs<RecordType>()) {
7187 RecordDecl *RD = RT->getDecl();
7188
7189 std::string InsertionText = std::string(" ") + RD->getKindName();
7190
7191 Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type)
7192 << (unsigned) RD->getTagKind()
7193 << T
7194 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
7195 InsertionText);
7196 } else {
7197 Diag(FriendLoc, diag::ext_nonclass_type_friend)
7198 << T
7199 << SourceRange(FriendLoc, TypeRange.getEnd());
7200 }
7201 } else if (T->getAs<EnumType>()) {
7202 Diag(FriendLoc, diag::ext_enum_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +00007203 << T
Douglas Gregor1d869352010-04-07 16:53:43 +00007204 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregor1d869352010-04-07 16:53:43 +00007205 }
7206 }
7207
Douglas Gregor06245bf2010-04-07 17:57:12 +00007208 // C++0x [class.friend]p3:
7209 // If the type specifier in a friend declaration designates a (possibly
7210 // cv-qualified) class type, that class is declared as a friend; otherwise,
7211 // the friend declaration is ignored.
7212
7213 // FIXME: C++0x has some syntactic restrictions on friend type declarations
7214 // in [class.friend]p3 that we do not implement.
Douglas Gregor1d869352010-04-07 16:53:43 +00007215
7216 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc);
7217}
7218
John McCall9a34edb2010-10-19 01:40:49 +00007219/// Handle a friend tag declaration where the scope specifier was
7220/// templated.
7221Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
7222 unsigned TagSpec, SourceLocation TagLoc,
7223 CXXScopeSpec &SS,
7224 IdentifierInfo *Name, SourceLocation NameLoc,
7225 AttributeList *Attr,
7226 MultiTemplateParamsArg TempParamLists) {
7227 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
7228
7229 bool isExplicitSpecialization = false;
John McCall9a34edb2010-10-19 01:40:49 +00007230 bool Invalid = false;
7231
7232 if (TemplateParameterList *TemplateParams
7233 = MatchTemplateParametersToScopeSpecifier(TagLoc, SS,
7234 TempParamLists.get(),
7235 TempParamLists.size(),
7236 /*friend*/ true,
7237 isExplicitSpecialization,
7238 Invalid)) {
John McCall9a34edb2010-10-19 01:40:49 +00007239 if (TemplateParams->size() > 0) {
7240 // This is a declaration of a class template.
7241 if (Invalid)
7242 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +00007243
John McCall9a34edb2010-10-19 01:40:49 +00007244 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
7245 SS, Name, NameLoc, Attr,
Abramo Bagnarac57c17d2011-03-10 13:28:31 +00007246 TemplateParams, AS_public,
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00007247 TempParamLists.size() - 1,
Abramo Bagnarac57c17d2011-03-10 13:28:31 +00007248 (TemplateParameterList**) TempParamLists.release()).take();
John McCall9a34edb2010-10-19 01:40:49 +00007249 } else {
7250 // The "template<>" header is extraneous.
7251 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
7252 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
7253 isExplicitSpecialization = true;
7254 }
7255 }
7256
7257 if (Invalid) return 0;
7258
7259 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
7260
7261 bool isAllExplicitSpecializations = true;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00007262 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
John McCall9a34edb2010-10-19 01:40:49 +00007263 if (TempParamLists.get()[I]->size()) {
7264 isAllExplicitSpecializations = false;
7265 break;
7266 }
7267 }
7268
7269 // FIXME: don't ignore attributes.
7270
7271 // If it's explicit specializations all the way down, just forget
7272 // about the template header and build an appropriate non-templated
7273 // friend. TODO: for source fidelity, remember the headers.
7274 if (isAllExplicitSpecializations) {
Douglas Gregor2494dd02011-03-01 01:34:45 +00007275 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall9a34edb2010-10-19 01:40:49 +00007276 ElaboratedTypeKeyword Keyword
7277 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor2494dd02011-03-01 01:34:45 +00007278 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +00007279 *Name, NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +00007280 if (T.isNull())
7281 return 0;
7282
7283 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
7284 if (isa<DependentNameType>(T)) {
7285 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
7286 TL.setKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +00007287 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +00007288 TL.setNameLoc(NameLoc);
7289 } else {
7290 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
7291 TL.setKeywordLoc(TagLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +00007292 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +00007293 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
7294 }
7295
7296 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
7297 TSI, FriendLoc);
7298 Friend->setAccess(AS_public);
7299 CurContext->addDecl(Friend);
7300 return Friend;
7301 }
7302
7303 // Handle the case of a templated-scope friend class. e.g.
7304 // template <class T> class A<T>::B;
7305 // FIXME: we don't support these right now.
7306 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
7307 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
7308 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
7309 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
7310 TL.setKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +00007311 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCall9a34edb2010-10-19 01:40:49 +00007312 TL.setNameLoc(NameLoc);
7313
7314 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
7315 TSI, FriendLoc);
7316 Friend->setAccess(AS_public);
7317 Friend->setUnsupportedFriend(true);
7318 CurContext->addDecl(Friend);
7319 return Friend;
7320}
7321
7322
John McCalldd4a3b02009-09-16 22:47:08 +00007323/// Handle a friend type declaration. This works in tandem with
7324/// ActOnTag.
7325///
7326/// Notes on friend class templates:
7327///
7328/// We generally treat friend class declarations as if they were
7329/// declaring a class. So, for example, the elaborated type specifier
7330/// in a friend declaration is required to obey the restrictions of a
7331/// class-head (i.e. no typedefs in the scope chain), template
7332/// parameters are required to match up with simple template-ids, &c.
7333/// However, unlike when declaring a template specialization, it's
7334/// okay to refer to a template specialization without an empty
7335/// template parameter declaration, e.g.
7336/// friend class A<T>::B<unsigned>;
7337/// We permit this as a special case; if there are any template
7338/// parameters present at all, require proper matching, i.e.
7339/// template <> template <class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +00007340Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +00007341 MultiTemplateParamsArg TempParams) {
John McCall02cace72009-08-28 07:59:38 +00007342 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall67d1a672009-08-06 02:15:43 +00007343
7344 assert(DS.isFriendSpecified());
7345 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
7346
John McCalldd4a3b02009-09-16 22:47:08 +00007347 // Try to convert the decl specifier to a type. This works for
7348 // friend templates because ActOnTag never produces a ClassTemplateDecl
7349 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +00007350 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +00007351 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
7352 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +00007353 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +00007354 return 0;
John McCall67d1a672009-08-06 02:15:43 +00007355
Douglas Gregor6ccab972010-12-16 01:14:37 +00007356 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
7357 return 0;
7358
John McCalldd4a3b02009-09-16 22:47:08 +00007359 // This is definitely an error in C++98. It's probably meant to
7360 // be forbidden in C++0x, too, but the specification is just
7361 // poorly written.
7362 //
7363 // The problem is with declarations like the following:
7364 // template <T> friend A<T>::foo;
7365 // where deciding whether a class C is a friend or not now hinges
7366 // on whether there exists an instantiation of A that causes
7367 // 'foo' to equal C. There are restrictions on class-heads
7368 // (which we declare (by fiat) elaborated friend declarations to
7369 // be) that makes this tractable.
7370 //
7371 // FIXME: handle "template <> friend class A<T>;", which
7372 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +00007373 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +00007374 Diag(Loc, diag::err_tagless_friend_type_template)
7375 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +00007376 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +00007377 }
Douglas Gregor1d869352010-04-07 16:53:43 +00007378
John McCall02cace72009-08-28 07:59:38 +00007379 // C++98 [class.friend]p1: A friend of a class is a function
7380 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +00007381 // This is fixed in DR77, which just barely didn't make the C++03
7382 // deadline. It's also a very silly restriction that seriously
7383 // affects inner classes and which nobody else seems to implement;
7384 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +00007385 //
7386 // But note that we could warn about it: it's always useless to
7387 // friend one of your own members (it's not, however, worthless to
7388 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +00007389
John McCalldd4a3b02009-09-16 22:47:08 +00007390 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +00007391 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +00007392 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +00007393 NumTempParamLists,
John McCallbe04b6d2010-10-16 07:23:36 +00007394 TempParams.release(),
John McCall32f2fb52010-03-25 18:04:51 +00007395 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +00007396 DS.getFriendSpecLoc());
7397 else
Douglas Gregor1d869352010-04-07 16:53:43 +00007398 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
7399
7400 if (!D)
John McCalld226f652010-08-21 09:40:31 +00007401 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +00007402
John McCalldd4a3b02009-09-16 22:47:08 +00007403 D->setAccess(AS_public);
7404 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +00007405
John McCalld226f652010-08-21 09:40:31 +00007406 return D;
John McCall02cace72009-08-28 07:59:38 +00007407}
7408
John McCall337ec3d2010-10-12 23:13:28 +00007409Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, bool IsDefinition,
7410 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +00007411 const DeclSpec &DS = D.getDeclSpec();
7412
7413 assert(DS.isFriendSpecified());
7414 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
7415
7416 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +00007417 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
7418 QualType T = TInfo->getType();
John McCall67d1a672009-08-06 02:15:43 +00007419
7420 // C++ [class.friend]p1
7421 // A friend of a class is a function or class....
7422 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +00007423 // It *doesn't* see through dependent types, which is correct
7424 // according to [temp.arg.type]p3:
7425 // If a declaration acquires a function type through a
7426 // type dependent on a template-parameter and this causes
7427 // a declaration that does not use the syntactic form of a
7428 // function declarator to have a function type, the program
7429 // is ill-formed.
John McCall67d1a672009-08-06 02:15:43 +00007430 if (!T->isFunctionType()) {
7431 Diag(Loc, diag::err_unexpected_friend);
7432
7433 // It might be worthwhile to try to recover by creating an
7434 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +00007435 return 0;
John McCall67d1a672009-08-06 02:15:43 +00007436 }
7437
7438 // C++ [namespace.memdef]p3
7439 // - If a friend declaration in a non-local class first declares a
7440 // class or function, the friend class or function is a member
7441 // of the innermost enclosing namespace.
7442 // - The name of the friend is not found by simple name lookup
7443 // until a matching declaration is provided in that namespace
7444 // scope (either before or after the class declaration granting
7445 // friendship).
7446 // - If a friend function is called, its name may be found by the
7447 // name lookup that considers functions from namespaces and
7448 // classes associated with the types of the function arguments.
7449 // - When looking for a prior declaration of a class or a function
7450 // declared as a friend, scopes outside the innermost enclosing
7451 // namespace scope are not considered.
7452
John McCall337ec3d2010-10-12 23:13:28 +00007453 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00007454 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
7455 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +00007456 assert(Name);
7457
Douglas Gregor6ccab972010-12-16 01:14:37 +00007458 // Check for unexpanded parameter packs.
7459 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
7460 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
7461 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
7462 return 0;
7463
John McCall67d1a672009-08-06 02:15:43 +00007464 // The context we found the declaration in, or in which we should
7465 // create the declaration.
7466 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +00007467 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +00007468 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +00007469 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +00007470
John McCall337ec3d2010-10-12 23:13:28 +00007471 // FIXME: there are different rules in local classes
John McCall67d1a672009-08-06 02:15:43 +00007472
John McCall337ec3d2010-10-12 23:13:28 +00007473 // There are four cases here.
7474 // - There's no scope specifier, in which case we just go to the
John McCall29ae6e52010-10-13 05:45:15 +00007475 // appropriate scope and look for a function or function template
John McCall337ec3d2010-10-12 23:13:28 +00007476 // there as appropriate.
7477 // Recover from invalid scope qualifiers as if they just weren't there.
7478 if (SS.isInvalid() || !SS.isSet()) {
John McCall29ae6e52010-10-13 05:45:15 +00007479 // C++0x [namespace.memdef]p3:
7480 // If the name in a friend declaration is neither qualified nor
7481 // a template-id and the declaration is a function or an
7482 // elaborated-type-specifier, the lookup to determine whether
7483 // the entity has been previously declared shall not consider
7484 // any scopes outside the innermost enclosing namespace.
7485 // C++0x [class.friend]p11:
7486 // If a friend declaration appears in a local class and the name
7487 // specified is an unqualified name, a prior declaration is
7488 // looked up without considering scopes that are outside the
7489 // innermost enclosing non-class scope. For a friend function
7490 // declaration, if there is no prior declaration, the program is
7491 // ill-formed.
7492 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCall8a407372010-10-14 22:22:28 +00007493 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +00007494
John McCall29ae6e52010-10-13 05:45:15 +00007495 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +00007496 DC = CurContext;
7497 while (true) {
7498 // Skip class contexts. If someone can cite chapter and verse
7499 // for this behavior, that would be nice --- it's what GCC and
7500 // EDG do, and it seems like a reasonable intent, but the spec
7501 // really only says that checks for unqualified existing
7502 // declarations should stop at the nearest enclosing namespace,
7503 // not that they should only consider the nearest enclosing
7504 // namespace.
Douglas Gregor182ddf02009-09-28 00:08:27 +00007505 while (DC->isRecord())
7506 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +00007507
John McCall68263142009-11-18 22:49:29 +00007508 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +00007509
7510 // TODO: decide what we think about using declarations.
John McCall29ae6e52010-10-13 05:45:15 +00007511 if (isLocal || !Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +00007512 break;
John McCall29ae6e52010-10-13 05:45:15 +00007513
John McCall8a407372010-10-14 22:22:28 +00007514 if (isTemplateId) {
7515 if (isa<TranslationUnitDecl>(DC)) break;
7516 } else {
7517 if (DC->isFileContext()) break;
7518 }
John McCall67d1a672009-08-06 02:15:43 +00007519 DC = DC->getParent();
7520 }
7521
7522 // C++ [class.friend]p1: A friend of a class is a function or
7523 // class that is not a member of the class . . .
John McCall7f27d922009-08-06 20:49:32 +00007524 // C++0x changes this for both friend types and functions.
7525 // Most C++ 98 compilers do seem to give an error here, so
7526 // we do, too.
John McCall68263142009-11-18 22:49:29 +00007527 if (!Previous.empty() && DC->Equals(CurContext)
7528 && !getLangOptions().CPlusPlus0x)
John McCall67d1a672009-08-06 02:15:43 +00007529 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
John McCall337ec3d2010-10-12 23:13:28 +00007530
John McCall380aaa42010-10-13 06:22:15 +00007531 DCScope = getScopeForDeclContext(S, DC);
John McCall29ae6e52010-10-13 05:45:15 +00007532
John McCall337ec3d2010-10-12 23:13:28 +00007533 // - There's a non-dependent scope specifier, in which case we
7534 // compute it and do a previous lookup there for a function
7535 // or function template.
7536 } else if (!SS.getScopeRep()->isDependent()) {
7537 DC = computeDeclContext(SS);
7538 if (!DC) return 0;
7539
7540 if (RequireCompleteDeclContext(SS, DC)) return 0;
7541
7542 LookupQualifiedName(Previous, DC);
7543
7544 // Ignore things found implicitly in the wrong scope.
7545 // TODO: better diagnostics for this case. Suggesting the right
7546 // qualified scope would be nice...
7547 LookupResult::Filter F = Previous.makeFilter();
7548 while (F.hasNext()) {
7549 NamedDecl *D = F.next();
7550 if (!DC->InEnclosingNamespaceSetOf(
7551 D->getDeclContext()->getRedeclContext()))
7552 F.erase();
7553 }
7554 F.done();
7555
7556 if (Previous.empty()) {
7557 D.setInvalidType();
7558 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
7559 return 0;
7560 }
7561
7562 // C++ [class.friend]p1: A friend of a class is a function or
7563 // class that is not a member of the class . . .
7564 if (DC->Equals(CurContext))
7565 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
7566
7567 // - There's a scope specifier that does not match any template
7568 // parameter lists, in which case we use some arbitrary context,
7569 // create a method or method template, and wait for instantiation.
7570 // - There's a scope specifier that does match some template
7571 // parameter lists, which we don't handle right now.
7572 } else {
7573 DC = CurContext;
7574 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +00007575 }
7576
John McCall29ae6e52010-10-13 05:45:15 +00007577 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +00007578 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00007579 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
7580 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
7581 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +00007582 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +00007583 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
7584 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +00007585 return 0;
John McCall67d1a672009-08-06 02:15:43 +00007586 }
John McCall67d1a672009-08-06 02:15:43 +00007587 }
7588
Douglas Gregor182ddf02009-09-28 00:08:27 +00007589 bool Redeclaration = false;
John McCall380aaa42010-10-13 06:22:15 +00007590 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, T, TInfo, Previous,
Douglas Gregora735b202009-10-13 14:39:41 +00007591 move(TemplateParams),
John McCall3f9a8a62009-08-11 06:59:38 +00007592 IsDefinition,
7593 Redeclaration);
John McCalld226f652010-08-21 09:40:31 +00007594 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +00007595
Douglas Gregor182ddf02009-09-28 00:08:27 +00007596 assert(ND->getDeclContext() == DC);
7597 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +00007598
John McCallab88d972009-08-31 22:39:49 +00007599 // Add the function declaration to the appropriate lookup tables,
7600 // adjusting the redeclarations list as necessary. We don't
7601 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +00007602 //
John McCallab88d972009-08-31 22:39:49 +00007603 // Also update the scope-based lookup if the target context's
7604 // lookup context is in lexical scope.
7605 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00007606 DC = DC->getRedeclContext();
Douglas Gregor182ddf02009-09-28 00:08:27 +00007607 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCallab88d972009-08-31 22:39:49 +00007608 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +00007609 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +00007610 }
John McCall02cace72009-08-28 07:59:38 +00007611
7612 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +00007613 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +00007614 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +00007615 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +00007616 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +00007617
John McCall337ec3d2010-10-12 23:13:28 +00007618 if (ND->isInvalidDecl())
7619 FrD->setInvalidDecl();
John McCall6102ca12010-10-16 06:59:13 +00007620 else {
7621 FunctionDecl *FD;
7622 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
7623 FD = FTD->getTemplatedDecl();
7624 else
7625 FD = cast<FunctionDecl>(ND);
7626
7627 // Mark templated-scope function declarations as unsupported.
7628 if (FD->getNumTemplateParameterLists())
7629 FrD->setUnsupportedFriend(true);
7630 }
John McCall337ec3d2010-10-12 23:13:28 +00007631
John McCalld226f652010-08-21 09:40:31 +00007632 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +00007633}
7634
John McCalld226f652010-08-21 09:40:31 +00007635void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
7636 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +00007637
Sebastian Redl50de12f2009-03-24 22:27:57 +00007638 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
7639 if (!Fn) {
7640 Diag(DelLoc, diag::err_deleted_non_function);
7641 return;
7642 }
7643 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
7644 Diag(DelLoc, diag::err_deleted_decl_not_first);
7645 Diag(Prev->getLocation(), diag::note_previous_declaration);
7646 // If the declaration wasn't the first, we delete the function anyway for
7647 // recovery.
7648 }
Sean Hunt10620eb2011-05-06 20:44:56 +00007649 Fn->setDeletedAsWritten();
Sebastian Redl50de12f2009-03-24 22:27:57 +00007650}
Sebastian Redl13e88542009-04-27 21:33:24 +00007651
7652static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +00007653 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +00007654 Stmt *SubStmt = *CI;
7655 if (!SubStmt)
7656 continue;
7657 if (isa<ReturnStmt>(SubStmt))
7658 Self.Diag(SubStmt->getSourceRange().getBegin(),
7659 diag::err_return_in_constructor_handler);
7660 if (!isa<Expr>(SubStmt))
7661 SearchForReturnInStmt(Self, SubStmt);
7662 }
7663}
7664
7665void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
7666 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
7667 CXXCatchStmt *Handler = TryBlock->getHandler(I);
7668 SearchForReturnInStmt(*this, Handler);
7669 }
7670}
Anders Carlssond7ba27d2009-05-14 01:09:04 +00007671
Mike Stump1eb44332009-09-09 15:08:12 +00007672bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +00007673 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +00007674 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
7675 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +00007676
Chandler Carruth73857792010-02-15 11:53:20 +00007677 if (Context.hasSameType(NewTy, OldTy) ||
7678 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +00007679 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00007680
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007681 // Check if the return types are covariant
7682 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +00007683
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007684 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00007685 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
7686 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007687 NewClassTy = NewPT->getPointeeType();
7688 OldClassTy = OldPT->getPointeeType();
7689 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00007690 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
7691 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
7692 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
7693 NewClassTy = NewRT->getPointeeType();
7694 OldClassTy = OldRT->getPointeeType();
7695 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007696 }
7697 }
Mike Stump1eb44332009-09-09 15:08:12 +00007698
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007699 // The return types aren't either both pointers or references to a class type.
7700 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +00007701 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007702 diag::err_different_return_type_for_overriding_virtual_function)
7703 << New->getDeclName() << NewTy << OldTy;
7704 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +00007705
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007706 return true;
7707 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +00007708
Anders Carlssonbe2e2052009-12-31 18:34:24 +00007709 // C++ [class.virtual]p6:
7710 // If the return type of D::f differs from the return type of B::f, the
7711 // class type in the return type of D::f shall be complete at the point of
7712 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +00007713 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
7714 if (!RT->isBeingDefined() &&
7715 RequireCompleteType(New->getLocation(), NewClassTy,
7716 PDiag(diag::err_covariant_return_incomplete)
7717 << New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +00007718 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +00007719 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +00007720
Douglas Gregora4923eb2009-11-16 21:35:15 +00007721 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007722 // Check if the new class derives from the old class.
7723 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
7724 Diag(New->getLocation(),
7725 diag::err_covariant_return_not_derived)
7726 << New->getDeclName() << NewTy << OldTy;
7727 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
7728 return true;
7729 }
Mike Stump1eb44332009-09-09 15:08:12 +00007730
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007731 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +00007732 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +00007733 diag::err_covariant_return_inaccessible_base,
7734 diag::err_covariant_return_ambiguous_derived_to_base_conv,
7735 // FIXME: Should this point to the return type?
7736 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCalleee1d542011-02-14 07:13:47 +00007737 // FIXME: this note won't trigger for delayed access control
7738 // diagnostics, and it's impossible to get an undelayed error
7739 // here from access control during the original parse because
7740 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007741 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
7742 return true;
7743 }
7744 }
Mike Stump1eb44332009-09-09 15:08:12 +00007745
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007746 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00007747 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007748 Diag(New->getLocation(),
7749 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +00007750 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007751 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
7752 return true;
7753 };
Mike Stump1eb44332009-09-09 15:08:12 +00007754
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007755
7756 // The new class type must have the same or less qualifiers as the old type.
7757 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
7758 Diag(New->getLocation(),
7759 diag::err_covariant_return_type_class_type_more_qualified)
7760 << New->getDeclName() << NewTy << OldTy;
7761 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
7762 return true;
7763 };
Mike Stump1eb44332009-09-09 15:08:12 +00007764
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007765 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +00007766}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00007767
Douglas Gregor4ba31362009-12-01 17:24:26 +00007768/// \brief Mark the given method pure.
7769///
7770/// \param Method the method to be marked pure.
7771///
7772/// \param InitRange the source range that covers the "0" initializer.
7773bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnara796aa442011-03-12 11:17:06 +00007774 SourceLocation EndLoc = InitRange.getEnd();
7775 if (EndLoc.isValid())
7776 Method->setRangeEnd(EndLoc);
7777
Douglas Gregor4ba31362009-12-01 17:24:26 +00007778 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
7779 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +00007780 return false;
Abramo Bagnara796aa442011-03-12 11:17:06 +00007781 }
Douglas Gregor4ba31362009-12-01 17:24:26 +00007782
7783 if (!Method->isInvalidDecl())
7784 Diag(Method->getLocation(), diag::err_non_virtual_pure)
7785 << Method->getDeclName() << InitRange;
7786 return true;
7787}
7788
John McCall731ad842009-12-19 09:28:58 +00007789/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
7790/// an initializer for the out-of-line declaration 'Dcl'. The scope
7791/// is a fresh scope pushed for just this purpose.
7792///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00007793/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
7794/// static data member of class X, names should be looked up in the scope of
7795/// class X.
John McCalld226f652010-08-21 09:40:31 +00007796void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00007797 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +00007798 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00007799
John McCall731ad842009-12-19 09:28:58 +00007800 // We should only get called for declarations with scope specifiers, like:
7801 // int foo::bar;
7802 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +00007803 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00007804}
7805
7806/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +00007807/// initializer for the out-of-line declaration 'D'.
7808void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00007809 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +00007810 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00007811
John McCall731ad842009-12-19 09:28:58 +00007812 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +00007813 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00007814}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00007815
7816/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
7817/// C++ if/switch/while/for statement.
7818/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +00007819DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00007820 // C++ 6.4p2:
7821 // The declarator shall not specify a function or an array.
7822 // The type-specifier-seq shall not contain typedef and shall not declare a
7823 // new class or enumeration.
7824 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
7825 "Parser allowed 'typedef' as storage class of condition decl.");
7826
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00007827 TagDecl *OwnedTag = 0;
John McCallbf1a0282010-06-04 23:28:52 +00007828 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S, &OwnedTag);
7829 QualType Ty = TInfo->getType();
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00007830
7831 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
7832 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
7833 // would be created and CXXConditionDeclExpr wants a VarDecl.
7834 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
7835 << D.getSourceRange();
7836 return DeclResult();
7837 } else if (OwnedTag && OwnedTag->isDefinition()) {
7838 // The type-specifier-seq shall not declare a new class or enumeration.
7839 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
7840 }
7841
John McCalld226f652010-08-21 09:40:31 +00007842 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00007843 if (!Dcl)
7844 return DeclResult();
7845
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00007846 return Dcl;
7847}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00007848
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007849void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
7850 bool DefinitionRequired) {
7851 // Ignore any vtable uses in unevaluated operands or for classes that do
7852 // not have a vtable.
7853 if (!Class->isDynamicClass() || Class->isDependentContext() ||
7854 CurContext->isDependentContext() ||
7855 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolabbf58bb2010-03-10 02:19:29 +00007856 return;
7857
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007858 // Try to insert this class into the map.
7859 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
7860 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
7861 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
7862 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +00007863 // If we already had an entry, check to see if we are promoting this vtable
7864 // to required a definition. If so, we need to reappend to the VTableUses
7865 // list, since we may have already processed the first entry.
7866 if (DefinitionRequired && !Pos.first->second) {
7867 Pos.first->second = true;
7868 } else {
7869 // Otherwise, we can early exit.
7870 return;
7871 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007872 }
7873
7874 // Local classes need to have their virtual members marked
7875 // immediately. For all other classes, we mark their virtual members
7876 // at the end of the translation unit.
7877 if (Class->isLocalClass())
7878 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +00007879 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007880 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +00007881}
7882
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007883bool Sema::DefineUsedVTables() {
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007884 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +00007885 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +00007886
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007887 // Note: The VTableUses vector could grow as a result of marking
7888 // the members of a class as "used", so we check the size each
7889 // time through the loop and prefer indices (with are stable) to
7890 // iterators (which are not).
Douglas Gregor78844032011-04-22 22:25:37 +00007891 bool DefinedAnything = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007892 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +00007893 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007894 if (!Class)
7895 continue;
7896
7897 SourceLocation Loc = VTableUses[I].second;
7898
7899 // If this class has a key function, but that key function is
7900 // defined in another translation unit, we don't need to emit the
7901 // vtable even though we're using it.
7902 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00007903 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007904 switch (KeyFunction->getTemplateSpecializationKind()) {
7905 case TSK_Undeclared:
7906 case TSK_ExplicitSpecialization:
7907 case TSK_ExplicitInstantiationDeclaration:
7908 // The key function is in another translation unit.
7909 continue;
7910
7911 case TSK_ExplicitInstantiationDefinition:
7912 case TSK_ImplicitInstantiation:
7913 // We will be instantiating the key function.
7914 break;
7915 }
7916 } else if (!KeyFunction) {
7917 // If we have a class with no key function that is the subject
7918 // of an explicit instantiation declaration, suppress the
7919 // vtable; it will live with the explicit instantiation
7920 // definition.
7921 bool IsExplicitInstantiationDeclaration
7922 = Class->getTemplateSpecializationKind()
7923 == TSK_ExplicitInstantiationDeclaration;
7924 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
7925 REnd = Class->redecls_end();
7926 R != REnd; ++R) {
7927 TemplateSpecializationKind TSK
7928 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
7929 if (TSK == TSK_ExplicitInstantiationDeclaration)
7930 IsExplicitInstantiationDeclaration = true;
7931 else if (TSK == TSK_ExplicitInstantiationDefinition) {
7932 IsExplicitInstantiationDeclaration = false;
7933 break;
7934 }
7935 }
7936
7937 if (IsExplicitInstantiationDeclaration)
7938 continue;
7939 }
7940
7941 // Mark all of the virtual members of this class as referenced, so
7942 // that we can build a vtable. Then, tell the AST consumer that a
7943 // vtable for this class is required.
Douglas Gregor78844032011-04-22 22:25:37 +00007944 DefinedAnything = true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007945 MarkVirtualMembersReferenced(Loc, Class);
7946 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
7947 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
7948
7949 // Optionally warn if we're emitting a weak vtable.
7950 if (Class->getLinkage() == ExternalLinkage &&
7951 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00007952 if (!KeyFunction || (KeyFunction->hasBody() && KeyFunction->isInlined()))
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007953 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
7954 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00007955 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007956 VTableUses.clear();
7957
Douglas Gregor78844032011-04-22 22:25:37 +00007958 return DefinedAnything;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00007959}
Anders Carlssond6a637f2009-12-07 08:24:59 +00007960
Rafael Espindola3e1ae932010-03-26 00:36:59 +00007961void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
7962 const CXXRecordDecl *RD) {
Anders Carlssond6a637f2009-12-07 08:24:59 +00007963 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
7964 e = RD->method_end(); i != e; ++i) {
7965 CXXMethodDecl *MD = *i;
7966
7967 // C++ [basic.def.odr]p2:
7968 // [...] A virtual member function is used if it is not pure. [...]
7969 if (MD->isVirtual() && !MD->isPure())
7970 MarkDeclarationReferenced(Loc, MD);
7971 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +00007972
7973 // Only classes that have virtual bases need a VTT.
7974 if (RD->getNumVBases() == 0)
7975 return;
7976
7977 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
7978 e = RD->bases_end(); i != e; ++i) {
7979 const CXXRecordDecl *Base =
7980 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +00007981 if (Base->getNumVBases() == 0)
7982 continue;
7983 MarkVirtualMembersReferenced(Loc, Base);
7984 }
Anders Carlssond6a637f2009-12-07 08:24:59 +00007985}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007986
7987/// SetIvarInitializers - This routine builds initialization ASTs for the
7988/// Objective-C implementation whose ivars need be initialized.
7989void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
7990 if (!getLangOptions().CPlusPlus)
7991 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00007992 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007993 llvm::SmallVector<ObjCIvarDecl*, 8> ivars;
7994 CollectIvarsToConstructOrDestruct(OID, ivars);
7995 if (ivars.empty())
7996 return;
Sean Huntcbb67482011-01-08 20:30:50 +00007997 llvm::SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007998 for (unsigned i = 0; i < ivars.size(); i++) {
7999 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +00008000 if (Field->isInvalidDecl())
8001 continue;
8002
Sean Huntcbb67482011-01-08 20:30:50 +00008003 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00008004 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
8005 InitializationKind InitKind =
8006 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
8007
8008 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00008009 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00008010 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregor53c374f2010-12-07 00:41:46 +00008011 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00008012 // Note, MemberInit could actually come back empty if no initialization
8013 // is required (e.g., because it would call a trivial default constructor)
8014 if (!MemberInit.get() || MemberInit.isInvalid())
8015 continue;
John McCallb4eb64d2010-10-08 02:01:28 +00008016
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00008017 Member =
Sean Huntcbb67482011-01-08 20:30:50 +00008018 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
8019 SourceLocation(),
8020 MemberInit.takeAs<Expr>(),
8021 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00008022 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +00008023
8024 // Be sure that the destructor is accessible and is marked as referenced.
8025 if (const RecordType *RecordTy
8026 = Context.getBaseElementType(Field->getType())
8027 ->getAs<RecordType>()) {
8028 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +00008029 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Douglas Gregor68dd3ee2010-05-20 02:24:22 +00008030 MarkDeclarationReferenced(Field->getLocation(), Destructor);
8031 CheckDestructorAccess(Field->getLocation(), Destructor,
8032 PDiag(diag::err_access_dtor_ivar)
8033 << Context.getBaseElementType(Field->getType()));
8034 }
8035 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00008036 }
8037 ObjCImplementation->setIvarInitializers(Context,
8038 AllToInit.data(), AllToInit.size());
8039 }
8040}
Sean Huntfe57eef2011-05-04 05:57:24 +00008041
Sean Huntebcbe1d2011-05-04 23:29:54 +00008042static
8043void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
8044 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
8045 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
8046 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
8047 Sema &S) {
8048 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
8049 CE = Current.end();
8050 if (Ctor->isInvalidDecl())
8051 return;
8052
8053 const FunctionDecl *FNTarget = 0;
8054 CXXConstructorDecl *Target;
8055
8056 // We ignore the result here since if we don't have a body, Target will be
8057 // null below.
8058 (void)Ctor->getTargetConstructor()->hasBody(FNTarget);
8059 Target
8060= const_cast<CXXConstructorDecl*>(cast_or_null<CXXConstructorDecl>(FNTarget));
8061
8062 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
8063 // Avoid dereferencing a null pointer here.
8064 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
8065
8066 if (!Current.insert(Canonical))
8067 return;
8068
8069 // We know that beyond here, we aren't chaining into a cycle.
8070 if (!Target || !Target->isDelegatingConstructor() ||
8071 Target->isInvalidDecl() || Valid.count(TCanonical)) {
8072 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
8073 Valid.insert(*CI);
8074 Current.clear();
8075 // We've hit a cycle.
8076 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
8077 Current.count(TCanonical)) {
8078 // If we haven't diagnosed this cycle yet, do so now.
8079 if (!Invalid.count(TCanonical)) {
8080 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Sean Huntc1598702011-05-05 00:05:47 +00008081 diag::warn_delegating_ctor_cycle)
Sean Huntebcbe1d2011-05-04 23:29:54 +00008082 << Ctor;
8083
8084 // Don't add a note for a function delegating directo to itself.
8085 if (TCanonical != Canonical)
8086 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
8087
8088 CXXConstructorDecl *C = Target;
8089 while (C->getCanonicalDecl() != Canonical) {
8090 (void)C->getTargetConstructor()->hasBody(FNTarget);
8091 assert(FNTarget && "Ctor cycle through bodiless function");
8092
8093 C
8094 = const_cast<CXXConstructorDecl*>(cast<CXXConstructorDecl>(FNTarget));
8095 S.Diag(C->getLocation(), diag::note_which_delegates_to);
8096 }
8097 }
8098
8099 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
8100 Invalid.insert(*CI);
8101 Current.clear();
8102 } else {
8103 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
8104 }
8105}
8106
8107
Sean Huntfe57eef2011-05-04 05:57:24 +00008108void Sema::CheckDelegatingCtorCycles() {
8109 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
8110
Sean Huntebcbe1d2011-05-04 23:29:54 +00008111 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
8112 CE = Current.end();
Sean Huntfe57eef2011-05-04 05:57:24 +00008113
8114 for (llvm::SmallVector<CXXConstructorDecl*, 4>::iterator
Sean Huntebcbe1d2011-05-04 23:29:54 +00008115 I = DelegatingCtorDecls.begin(),
8116 E = DelegatingCtorDecls.end();
8117 I != E; ++I) {
8118 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Sean Huntfe57eef2011-05-04 05:57:24 +00008119 }
Sean Huntebcbe1d2011-05-04 23:29:54 +00008120
8121 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
8122 (*CI)->setInvalidDecl();
Sean Huntfe57eef2011-05-04 05:57:24 +00008123}