blob: 525cb81c8071ae6017575f14adf2e3792395019f [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 Hunt5f802e52011-05-06 00:11:07 +0000966 bool Deleted) {
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
1031
1032 if (SS.isSet() && !SS.isInvalid()) {
1033 // The user provided a superfluous scope specifier inside a class
1034 // definition:
1035 //
1036 // class X {
1037 // int X::member;
1038 // };
1039 DeclContext *DC = 0;
1040 if ((DC = computeDeclContext(SS, false)) && DC->Equals(CurContext))
1041 Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification)
1042 << Name << FixItHint::CreateRemoval(SS.getRange());
1043 else
1044 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1045 << Name << SS.getRange();
1046
1047 SS.clear();
1048 }
1049
Douglas Gregor37b372b2009-08-20 22:52:58 +00001050 // FIXME: Check for template parameters!
Douglas Gregor56c04582010-12-16 00:46:58 +00001051 // FIXME: Check that the name is an identifier!
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001052 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
1053 AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001054 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +00001055 } else {
John McCalld226f652010-08-21 09:40:31 +00001056 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001057 if (!Member) {
John McCalld226f652010-08-21 09:40:31 +00001058 return 0;
Chris Lattner6f8ce142009-03-05 23:03:49 +00001059 }
Chris Lattner8b963ef2009-03-05 23:01:03 +00001060
1061 // Non-instance-fields can't have a bitfield.
1062 if (BitWidth) {
1063 if (Member->isInvalidDecl()) {
1064 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00001065 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00001066 // C++ 9.6p3: A bit-field shall not be a static member.
1067 // "static member 'A' cannot be a bit-field"
1068 Diag(Loc, diag::err_static_not_bitfield)
1069 << Name << BitWidth->getSourceRange();
1070 } else if (isa<TypedefDecl>(Member)) {
1071 // "typedef member 'x' cannot be a bit-field"
1072 Diag(Loc, diag::err_typedef_not_bitfield)
1073 << Name << BitWidth->getSourceRange();
1074 } else {
1075 // A function typedef ("typedef int f(); f a;").
1076 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1077 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +00001078 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +00001079 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +00001080 }
Mike Stump1eb44332009-09-09 15:08:12 +00001081
Chris Lattner8b963ef2009-03-05 23:01:03 +00001082 BitWidth = 0;
1083 Member->setInvalidDecl();
1084 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001085
1086 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +00001087
Douglas Gregor37b372b2009-08-20 22:52:58 +00001088 // If we have declared a member function template, set the access of the
1089 // templated declaration as well.
1090 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1091 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +00001092 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001093
Anders Carlssonaae5af22011-01-20 04:34:22 +00001094 if (VS.isOverrideSpecified()) {
1095 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1096 if (!MD || !MD->isVirtual()) {
1097 Diag(Member->getLocStart(),
1098 diag::override_keyword_only_allowed_on_virtual_member_functions)
1099 << "override" << FixItHint::CreateRemoval(VS.getOverrideLoc());
Anders Carlsson9e682d92011-01-20 05:57:14 +00001100 } else
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001101 MD->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
Anders Carlssonaae5af22011-01-20 04:34:22 +00001102 }
1103 if (VS.isFinalSpecified()) {
1104 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1105 if (!MD || !MD->isVirtual()) {
1106 Diag(Member->getLocStart(),
1107 diag::override_keyword_only_allowed_on_virtual_member_functions)
1108 << "final" << FixItHint::CreateRemoval(VS.getFinalLoc());
Anders Carlsson9e682d92011-01-20 05:57:14 +00001109 } else
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001110 MD->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlssonaae5af22011-01-20 04:34:22 +00001111 }
Anders Carlsson9e682d92011-01-20 05:57:14 +00001112
Douglas Gregorf5251602011-03-08 17:10:18 +00001113 if (VS.getLastLocation().isValid()) {
1114 // Update the end location of a method that has a virt-specifiers.
1115 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1116 MD->setRangeEnd(VS.getLastLocation());
1117 }
1118
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001119 CheckOverrideControl(Member);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001120
Douglas Gregor10bd3682008-11-17 22:58:34 +00001121 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001122
Douglas Gregor021c3b32009-03-11 23:00:04 +00001123 if (Init)
Richard Smith34b41d92011-02-20 03:19:35 +00001124 AddInitializerToDecl(Member, Init, false,
1125 DS.getTypeSpecType() == DeclSpec::TST_auto);
Sebastian Redle2b68332009-04-12 17:16:29 +00001126 if (Deleted) // FIXME: Source location is not very good.
John McCalld226f652010-08-21 09:40:31 +00001127 SetDeclDeleted(Member, D.getSourceRange().getBegin());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001128
Richard Smith483b9f32011-02-21 20:05:19 +00001129 FinalizeDeclaration(Member);
1130
John McCallb25b2952011-02-15 07:12:36 +00001131 if (isInstField)
Douglas Gregor44b43212008-12-11 16:49:14 +00001132 FieldCollector->Add(cast<FieldDecl>(Member));
John McCalld226f652010-08-21 09:40:31 +00001133 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001134}
1135
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001136/// \brief Find the direct and/or virtual base specifiers that
1137/// correspond to the given base type, for use in base initialization
1138/// within a constructor.
1139static bool FindBaseInitializer(Sema &SemaRef,
1140 CXXRecordDecl *ClassDecl,
1141 QualType BaseType,
1142 const CXXBaseSpecifier *&DirectBaseSpec,
1143 const CXXBaseSpecifier *&VirtualBaseSpec) {
1144 // First, check for a direct base class.
1145 DirectBaseSpec = 0;
1146 for (CXXRecordDecl::base_class_const_iterator Base
1147 = ClassDecl->bases_begin();
1148 Base != ClassDecl->bases_end(); ++Base) {
1149 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1150 // We found a direct base of this type. That's what we're
1151 // initializing.
1152 DirectBaseSpec = &*Base;
1153 break;
1154 }
1155 }
1156
1157 // Check for a virtual base class.
1158 // FIXME: We might be able to short-circuit this if we know in advance that
1159 // there are no virtual bases.
1160 VirtualBaseSpec = 0;
1161 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1162 // We haven't found a base yet; search the class hierarchy for a
1163 // virtual base class.
1164 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1165 /*DetectVirtual=*/false);
1166 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1167 BaseType, Paths)) {
1168 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1169 Path != Paths.end(); ++Path) {
1170 if (Path->back().Base->isVirtual()) {
1171 VirtualBaseSpec = Path->back().Base;
1172 break;
1173 }
1174 }
1175 }
1176 }
1177
1178 return DirectBaseSpec || VirtualBaseSpec;
1179}
1180
Douglas Gregor7ad83902008-11-05 04:29:56 +00001181/// ActOnMemInitializer - Handle a C++ member initializer.
John McCallf312b1e2010-08-26 23:41:50 +00001182MemInitResult
John McCalld226f652010-08-21 09:40:31 +00001183Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001184 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001185 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001186 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00001187 ParsedType TemplateTypeTy,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001188 SourceLocation IdLoc,
1189 SourceLocation LParenLoc,
1190 ExprTy **Args, unsigned NumArgs,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001191 SourceLocation RParenLoc,
1192 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001193 if (!ConstructorD)
1194 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001195
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001196 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00001197
1198 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00001199 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001200 if (!Constructor) {
1201 // The user wrote a constructor initializer on a function that is
1202 // not a C++ constructor. Ignore the error for now, because we may
1203 // have more member initializers coming; we'll diagnose it just
1204 // once in ActOnMemInitializers.
1205 return true;
1206 }
1207
1208 CXXRecordDecl *ClassDecl = Constructor->getParent();
1209
1210 // C++ [class.base.init]p2:
1211 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky7663f392010-11-20 01:29:55 +00001212 // constructor's class and, if not found in that scope, are looked
1213 // up in the scope containing the constructor's definition.
1214 // [Note: if the constructor's class contains a member with the
1215 // same name as a direct or virtual base class of the class, a
1216 // mem-initializer-id naming the member or base class and composed
1217 // of a single identifier refers to the class member. A
Douglas Gregor7ad83902008-11-05 04:29:56 +00001218 // mem-initializer-id for the hidden base class may be specified
1219 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00001220 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001221 // Look for a member, first.
1222 FieldDecl *Member = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001223 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001224 = ClassDecl->lookup(MemberOrBase);
Francois Pichet87c2e122010-11-21 06:08:52 +00001225 if (Result.first != Result.second) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001226 Member = dyn_cast<FieldDecl>(*Result.first);
Francois Pichet87c2e122010-11-21 06:08:52 +00001227
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001228 if (Member) {
1229 if (EllipsisLoc.isValid())
1230 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1231 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1232
Francois Pichet00eb3f92010-12-04 09:14:42 +00001233 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
Douglas Gregor802ab452009-12-02 22:36:29 +00001234 LParenLoc, RParenLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001235 }
1236
Francois Pichet00eb3f92010-12-04 09:14:42 +00001237 // Handle anonymous union case.
1238 if (IndirectFieldDecl* IndirectField
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001239 = dyn_cast<IndirectFieldDecl>(*Result.first)) {
1240 if (EllipsisLoc.isValid())
1241 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1242 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1243
Francois Pichet00eb3f92010-12-04 09:14:42 +00001244 return BuildMemberInitializer(IndirectField, (Expr**)Args,
1245 NumArgs, IdLoc,
1246 LParenLoc, RParenLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001247 }
Francois Pichet00eb3f92010-12-04 09:14:42 +00001248 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001249 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001250 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00001251 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00001252 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00001253
1254 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00001255 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
John McCall2b194412009-12-21 10:41:20 +00001256 } else {
1257 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1258 LookupParsedName(R, S, &SS);
1259
1260 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1261 if (!TyD) {
1262 if (R.isAmbiguous()) return true;
1263
John McCallfd225442010-04-09 19:01:14 +00001264 // We don't want access-control diagnostics here.
1265 R.suppressDiagnostics();
1266
Douglas Gregor7a886e12010-01-19 06:46:48 +00001267 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1268 bool NotUnknownSpecialization = false;
1269 DeclContext *DC = computeDeclContext(SS, false);
1270 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1271 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1272
1273 if (!NotUnknownSpecialization) {
1274 // When the scope specifier can refer to a member of an unknown
1275 // specialization, we take it as a type name.
Douglas Gregore29425b2011-02-28 22:42:13 +00001276 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
1277 SS.getWithLocInContext(Context),
1278 *MemberOrBase, IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00001279 if (BaseType.isNull())
1280 return true;
1281
Douglas Gregor7a886e12010-01-19 06:46:48 +00001282 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00001283 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001284 }
1285 }
1286
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001287 // If no results were found, try to correct typos.
Douglas Gregor7a886e12010-01-19 06:46:48 +00001288 if (R.empty() && BaseType.isNull() &&
Douglas Gregoraaf87162010-04-14 20:04:41 +00001289 CorrectTypo(R, S, &SS, ClassDecl, 0, CTC_NoKeywords) &&
1290 R.isSingleResult()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001291 if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00001292 if (Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl)) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001293 // We have found a non-static data member with a similar
1294 // name to what was typed; complain and initialize that
1295 // member.
1296 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1297 << MemberOrBase << true << R.getLookupName()
Douglas Gregor849b2432010-03-31 17:46:05 +00001298 << FixItHint::CreateReplacement(R.getNameLoc(),
1299 R.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +00001300 Diag(Member->getLocation(), diag::note_previous_decl)
1301 << Member->getDeclName();
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001302
1303 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1304 LParenLoc, RParenLoc);
1305 }
1306 } else if (TypeDecl *Type = R.getAsSingle<TypeDecl>()) {
1307 const CXXBaseSpecifier *DirectBaseSpec;
1308 const CXXBaseSpecifier *VirtualBaseSpec;
1309 if (FindBaseInitializer(*this, ClassDecl,
1310 Context.getTypeDeclType(Type),
1311 DirectBaseSpec, VirtualBaseSpec)) {
1312 // We have found a direct or virtual base class with a
1313 // similar name to what was typed; complain and initialize
1314 // that base class.
1315 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1316 << MemberOrBase << false << R.getLookupName()
Douglas Gregor849b2432010-03-31 17:46:05 +00001317 << FixItHint::CreateReplacement(R.getNameLoc(),
1318 R.getLookupName().getAsString());
Douglas Gregor0d535c82010-01-07 00:26:25 +00001319
1320 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1321 : VirtualBaseSpec;
1322 Diag(BaseSpec->getSourceRange().getBegin(),
1323 diag::note_base_class_specified_here)
1324 << BaseSpec->getType()
1325 << BaseSpec->getSourceRange();
1326
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001327 TyD = Type;
1328 }
1329 }
1330 }
1331
Douglas Gregor7a886e12010-01-19 06:46:48 +00001332 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001333 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1334 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1335 return true;
1336 }
John McCall2b194412009-12-21 10:41:20 +00001337 }
1338
Douglas Gregor7a886e12010-01-19 06:46:48 +00001339 if (BaseType.isNull()) {
1340 BaseType = Context.getTypeDeclType(TyD);
1341 if (SS.isSet()) {
1342 NestedNameSpecifier *Qualifier =
1343 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00001344
Douglas Gregor7a886e12010-01-19 06:46:48 +00001345 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001346 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001347 }
John McCall2b194412009-12-21 10:41:20 +00001348 }
1349 }
Mike Stump1eb44332009-09-09 15:08:12 +00001350
John McCalla93c9342009-12-07 02:54:59 +00001351 if (!TInfo)
1352 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001353
John McCalla93c9342009-12-07 02:54:59 +00001354 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001355 LParenLoc, RParenLoc, ClassDecl, EllipsisLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00001356}
1357
John McCallb4190042009-11-04 23:02:40 +00001358/// Checks an initializer expression for use of uninitialized fields, such as
1359/// containing the field that is being initialized. Returns true if there is an
1360/// uninitialized field was used an updates the SourceLocation parameter; false
1361/// otherwise.
Nick Lewycky43ad1822010-06-15 07:32:55 +00001362static bool InitExprContainsUninitializedFields(const Stmt *S,
Francois Pichet00eb3f92010-12-04 09:14:42 +00001363 const ValueDecl *LhsField,
Nick Lewycky43ad1822010-06-15 07:32:55 +00001364 SourceLocation *L) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00001365 assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField));
1366
Nick Lewycky43ad1822010-06-15 07:32:55 +00001367 if (isa<CallExpr>(S)) {
1368 // Do not descend into function calls or constructors, as the use
1369 // of an uninitialized field may be valid. One would have to inspect
1370 // the contents of the function/ctor to determine if it is safe or not.
1371 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1372 // may be safe, depending on what the function/ctor does.
1373 return false;
1374 }
1375 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
1376 const NamedDecl *RhsField = ME->getMemberDecl();
Anders Carlsson175ffbf2010-10-06 02:43:25 +00001377
1378 if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) {
1379 // The member expression points to a static data member.
1380 assert(VD->isStaticDataMember() &&
1381 "Member points to non-static data member!");
Nick Lewyckyedd59112010-10-06 18:37:39 +00001382 (void)VD;
Anders Carlsson175ffbf2010-10-06 02:43:25 +00001383 return false;
1384 }
1385
1386 if (isa<EnumConstantDecl>(RhsField)) {
1387 // The member expression points to an enum.
1388 return false;
1389 }
1390
John McCallb4190042009-11-04 23:02:40 +00001391 if (RhsField == LhsField) {
1392 // Initializing a field with itself. Throw a warning.
1393 // But wait; there are exceptions!
1394 // Exception #1: The field may not belong to this record.
1395 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
Nick Lewycky43ad1822010-06-15 07:32:55 +00001396 const Expr *base = ME->getBase();
John McCallb4190042009-11-04 23:02:40 +00001397 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1398 // Even though the field matches, it does not belong to this record.
1399 return false;
1400 }
1401 // None of the exceptions triggered; return true to indicate an
1402 // uninitialized field was used.
1403 *L = ME->getMemberLoc();
1404 return true;
1405 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001406 } else if (isa<UnaryExprOrTypeTraitExpr>(S)) {
Argyrios Kyrtzidisff8819b2010-09-21 10:47:20 +00001407 // sizeof/alignof doesn't reference contents, do not warn.
1408 return false;
1409 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) {
1410 // address-of doesn't reference contents (the pointer may be dereferenced
1411 // in the same expression but it would be rare; and weird).
1412 if (UOE->getOpcode() == UO_AddrOf)
1413 return false;
John McCallb4190042009-11-04 23:02:40 +00001414 }
John McCall7502c1d2011-02-13 04:07:26 +00001415 for (Stmt::const_child_range it = S->children(); it; ++it) {
Nick Lewycky43ad1822010-06-15 07:32:55 +00001416 if (!*it) {
1417 // An expression such as 'member(arg ?: "")' may trigger this.
John McCallb4190042009-11-04 23:02:40 +00001418 continue;
1419 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00001420 if (InitExprContainsUninitializedFields(*it, LhsField, L))
1421 return true;
John McCallb4190042009-11-04 23:02:40 +00001422 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00001423 return false;
John McCallb4190042009-11-04 23:02:40 +00001424}
1425
John McCallf312b1e2010-08-26 23:41:50 +00001426MemInitResult
Chandler Carruth894aed92010-12-06 09:23:57 +00001427Sema::BuildMemberInitializer(ValueDecl *Member, Expr **Args,
Eli Friedman59c04372009-07-29 19:44:27 +00001428 unsigned NumArgs, SourceLocation IdLoc,
Douglas Gregor802ab452009-12-02 22:36:29 +00001429 SourceLocation LParenLoc,
Eli Friedman59c04372009-07-29 19:44:27 +00001430 SourceLocation RParenLoc) {
Chandler Carruth894aed92010-12-06 09:23:57 +00001431 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
1432 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
1433 assert((DirectMember || IndirectMember) &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00001434 "Member must be a FieldDecl or IndirectFieldDecl");
1435
Douglas Gregor464b2f02010-11-05 22:21:31 +00001436 if (Member->isInvalidDecl())
1437 return true;
Chandler Carruth894aed92010-12-06 09:23:57 +00001438
John McCallb4190042009-11-04 23:02:40 +00001439 // Diagnose value-uses of fields to initialize themselves, e.g.
1440 // foo(foo)
1441 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00001442 // TODO: implement -Wuninitialized and fold this into that framework.
John McCallb4190042009-11-04 23:02:40 +00001443 for (unsigned i = 0; i < NumArgs; ++i) {
1444 SourceLocation L;
1445 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1446 // FIXME: Return true in the case when other fields are used before being
1447 // uninitialized. For example, let this field be the i'th field. When
1448 // initializing the i'th field, throw a warning if any of the >= i'th
1449 // fields are used, as they are not yet initialized.
1450 // Right now we are only handling the case where the i'th field uses
1451 // itself in its initializer.
1452 Diag(L, diag::warn_field_is_uninit);
1453 }
1454 }
1455
Eli Friedman59c04372009-07-29 19:44:27 +00001456 bool HasDependentArg = false;
1457 for (unsigned i = 0; i < NumArgs; i++)
1458 HasDependentArg |= Args[i]->isTypeDependent();
1459
Chandler Carruth894aed92010-12-06 09:23:57 +00001460 Expr *Init;
Eli Friedman0f2b97d2010-07-24 21:19:15 +00001461 if (Member->getType()->isDependentType() || HasDependentArg) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001462 // Can't check initialization for a member of dependent type or when
1463 // any of the arguments are type-dependent expressions.
Chandler Carruth894aed92010-12-06 09:23:57 +00001464 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1465 RParenLoc);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001466
1467 // Erase any temporaries within this evaluation context; we're not
1468 // going to track them in the AST, since we'll be rebuilding the
1469 // ASTs during template instantiation.
1470 ExprTemporaries.erase(
1471 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1472 ExprTemporaries.end());
Chandler Carruth894aed92010-12-06 09:23:57 +00001473 } else {
1474 // Initialize the member.
1475 InitializedEntity MemberEntity =
1476 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
1477 : InitializedEntity::InitializeMember(IndirectMember, 0);
1478 InitializationKind Kind =
1479 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc);
John McCallb4eb64d2010-10-08 02:01:28 +00001480
Chandler Carruth894aed92010-12-06 09:23:57 +00001481 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
1482
1483 ExprResult MemberInit =
1484 InitSeq.Perform(*this, MemberEntity, Kind,
1485 MultiExprArg(*this, Args, NumArgs), 0);
1486 if (MemberInit.isInvalid())
1487 return true;
1488
1489 CheckImplicitConversions(MemberInit.get(), LParenLoc);
1490
1491 // C++0x [class.base.init]p7:
1492 // The initialization of each base and member constitutes a
1493 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00001494 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Chandler Carruth894aed92010-12-06 09:23:57 +00001495 if (MemberInit.isInvalid())
1496 return true;
1497
1498 // If we are in a dependent context, template instantiation will
1499 // perform this type-checking again. Just save the arguments that we
1500 // received in a ParenListExpr.
1501 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1502 // of the information that we have about the member
1503 // initializer. However, deconstructing the ASTs is a dicey process,
1504 // and this approach is far more likely to get the corner cases right.
1505 if (CurContext->isDependentContext())
1506 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1507 RParenLoc);
1508 else
1509 Init = MemberInit.get();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001510 }
1511
Chandler Carruth894aed92010-12-06 09:23:57 +00001512 if (DirectMember) {
Sean Huntcbb67482011-01-08 20:30:50 +00001513 return new (Context) CXXCtorInitializer(Context, DirectMember,
Chandler Carruth894aed92010-12-06 09:23:57 +00001514 IdLoc, LParenLoc, Init,
1515 RParenLoc);
1516 } else {
Sean Huntcbb67482011-01-08 20:30:50 +00001517 return new (Context) CXXCtorInitializer(Context, IndirectMember,
Chandler Carruth894aed92010-12-06 09:23:57 +00001518 IdLoc, LParenLoc, Init,
1519 RParenLoc);
1520 }
Eli Friedman59c04372009-07-29 19:44:27 +00001521}
1522
John McCallf312b1e2010-08-26 23:41:50 +00001523MemInitResult
Sean Hunt97fcc492011-01-08 19:20:43 +00001524Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo,
1525 Expr **Args, unsigned NumArgs,
Sean Hunt41717662011-02-26 19:13:13 +00001526 SourceLocation NameLoc,
Sean Hunt97fcc492011-01-08 19:20:43 +00001527 SourceLocation LParenLoc,
1528 SourceLocation RParenLoc,
Sean Hunt41717662011-02-26 19:13:13 +00001529 CXXRecordDecl *ClassDecl) {
Sean Hunt97fcc492011-01-08 19:20:43 +00001530 SourceLocation Loc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
1531 if (!LangOpts.CPlusPlus0x)
1532 return Diag(Loc, diag::err_delegation_0x_only)
1533 << TInfo->getTypeLoc().getLocalSourceRange();
Sebastian Redlf9c32eb2011-03-12 13:53:51 +00001534
Sean Hunt41717662011-02-26 19:13:13 +00001535 // Initialize the object.
1536 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
1537 QualType(ClassDecl->getTypeForDecl(), 0));
1538 InitializationKind Kind =
1539 InitializationKind::CreateDirect(NameLoc, LParenLoc, RParenLoc);
1540
1541 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs);
1542
1543 ExprResult DelegationInit =
1544 InitSeq.Perform(*this, DelegationEntity, Kind,
1545 MultiExprArg(*this, Args, NumArgs), 0);
1546 if (DelegationInit.isInvalid())
1547 return true;
1548
1549 CXXConstructExpr *ConExpr = cast<CXXConstructExpr>(DelegationInit.get());
Sean Huntfe57eef2011-05-04 05:57:24 +00001550 CXXConstructorDecl *Constructor
1551 = ConExpr->getConstructor();
Sean Hunt41717662011-02-26 19:13:13 +00001552 assert(Constructor && "Delegating constructor with no target?");
1553
1554 CheckImplicitConversions(DelegationInit.get(), LParenLoc);
1555
1556 // C++0x [class.base.init]p7:
1557 // The initialization of each base and member constitutes a
1558 // full-expression.
1559 DelegationInit = MaybeCreateExprWithCleanups(DelegationInit);
1560 if (DelegationInit.isInvalid())
1561 return true;
1562
1563 // If we are in a dependent context, template instantiation will
1564 // perform this type-checking again. Just save the arguments that we
1565 // received in a ParenListExpr.
1566 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1567 // of the information that we have about the base
1568 // initializer. However, deconstructing the ASTs is a dicey process,
1569 // and this approach is far more likely to get the corner cases right.
1570 if (CurContext->isDependentContext()) {
1571 ExprResult Init
1572 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args,
1573 NumArgs, RParenLoc));
1574 return new (Context) CXXCtorInitializer(Context, Loc, LParenLoc,
1575 Constructor, Init.takeAs<Expr>(),
1576 RParenLoc);
1577 }
1578
1579 return new (Context) CXXCtorInitializer(Context, Loc, LParenLoc, Constructor,
1580 DelegationInit.takeAs<Expr>(),
1581 RParenLoc);
Sean Hunt97fcc492011-01-08 19:20:43 +00001582}
1583
1584MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00001585Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Douglas Gregor802ab452009-12-02 22:36:29 +00001586 Expr **Args, unsigned NumArgs,
1587 SourceLocation LParenLoc, SourceLocation RParenLoc,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001588 CXXRecordDecl *ClassDecl,
1589 SourceLocation EllipsisLoc) {
Eli Friedman59c04372009-07-29 19:44:27 +00001590 bool HasDependentArg = false;
1591 for (unsigned i = 0; i < NumArgs; i++)
1592 HasDependentArg |= Args[i]->isTypeDependent();
1593
Douglas Gregor3956b1a2010-06-16 16:03:14 +00001594 SourceLocation BaseLoc
1595 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
1596
1597 if (!BaseType->isDependentType() && !BaseType->isRecordType())
1598 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1599 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
1600
1601 // C++ [class.base.init]p2:
1602 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00001603 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00001604 // of that class, the mem-initializer is ill-formed. A
1605 // mem-initializer-list can initialize a base class using any
1606 // name that denotes that base class type.
1607 bool Dependent = BaseType->isDependentType() || HasDependentArg;
1608
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001609 if (EllipsisLoc.isValid()) {
1610 // This is a pack expansion.
1611 if (!BaseType->containsUnexpandedParameterPack()) {
1612 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1613 << SourceRange(BaseLoc, RParenLoc);
1614
1615 EllipsisLoc = SourceLocation();
1616 }
1617 } else {
1618 // Check for any unexpanded parameter packs.
1619 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
1620 return true;
1621
1622 for (unsigned I = 0; I != NumArgs; ++I)
1623 if (DiagnoseUnexpandedParameterPack(Args[I]))
1624 return true;
1625 }
1626
Douglas Gregor3956b1a2010-06-16 16:03:14 +00001627 // Check for direct and virtual base classes.
1628 const CXXBaseSpecifier *DirectBaseSpec = 0;
1629 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1630 if (!Dependent) {
Sean Hunt97fcc492011-01-08 19:20:43 +00001631 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
1632 BaseType))
Sean Hunt41717662011-02-26 19:13:13 +00001633 return BuildDelegatingInitializer(BaseTInfo, Args, NumArgs, BaseLoc,
1634 LParenLoc, RParenLoc, ClassDecl);
Sean Hunt97fcc492011-01-08 19:20:43 +00001635
Douglas Gregor3956b1a2010-06-16 16:03:14 +00001636 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1637 VirtualBaseSpec);
1638
1639 // C++ [base.class.init]p2:
1640 // Unless the mem-initializer-id names a nonstatic data member of the
1641 // constructor's class or a direct or virtual base of that class, the
1642 // mem-initializer is ill-formed.
1643 if (!DirectBaseSpec && !VirtualBaseSpec) {
1644 // If the class has any dependent bases, then it's possible that
1645 // one of those types will resolve to the same type as
1646 // BaseType. Therefore, just treat this as a dependent base
1647 // class initialization. FIXME: Should we try to check the
1648 // initialization anyway? It seems odd.
1649 if (ClassDecl->hasAnyDependentBases())
1650 Dependent = true;
1651 else
1652 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1653 << BaseType << Context.getTypeDeclType(ClassDecl)
1654 << BaseTInfo->getTypeLoc().getLocalSourceRange();
1655 }
1656 }
1657
1658 if (Dependent) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001659 // Can't check initialization for a base of dependent type or when
1660 // any of the arguments are type-dependent expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00001661 ExprResult BaseInit
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001662 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1663 RParenLoc));
Eli Friedman59c04372009-07-29 19:44:27 +00001664
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001665 // Erase any temporaries within this evaluation context; we're not
1666 // going to track them in the AST, since we'll be rebuilding the
1667 // ASTs during template instantiation.
1668 ExprTemporaries.erase(
1669 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1670 ExprTemporaries.end());
Mike Stump1eb44332009-09-09 15:08:12 +00001671
Sean Huntcbb67482011-01-08 20:30:50 +00001672 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001673 /*IsVirtual=*/false,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001674 LParenLoc,
1675 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001676 RParenLoc,
1677 EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001678 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001679
1680 // C++ [base.class.init]p2:
1681 // If a mem-initializer-id is ambiguous because it designates both
1682 // a direct non-virtual base class and an inherited virtual base
1683 // class, the mem-initializer is ill-formed.
1684 if (DirectBaseSpec && VirtualBaseSpec)
1685 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00001686 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001687
1688 CXXBaseSpecifier *BaseSpec
1689 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
1690 if (!BaseSpec)
1691 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1692
1693 // Initialize the base.
1694 InitializedEntity BaseEntity =
Anders Carlsson711f34a2010-04-21 19:52:01 +00001695 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001696 InitializationKind Kind =
1697 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc);
1698
1699 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
1700
John McCall60d7b3a2010-08-24 06:29:42 +00001701 ExprResult BaseInit =
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001702 InitSeq.Perform(*this, BaseEntity, Kind,
John McCallca0408f2010-08-23 06:44:23 +00001703 MultiExprArg(*this, Args, NumArgs), 0);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001704 if (BaseInit.isInvalid())
1705 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00001706
1707 CheckImplicitConversions(BaseInit.get(), LParenLoc);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001708
1709 // C++0x [class.base.init]p7:
1710 // The initialization of each base and member constitutes a
1711 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00001712 BaseInit = MaybeCreateExprWithCleanups(BaseInit);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001713 if (BaseInit.isInvalid())
1714 return true;
1715
1716 // If we are in a dependent context, template instantiation will
1717 // perform this type-checking again. Just save the arguments that we
1718 // received in a ParenListExpr.
1719 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1720 // of the information that we have about the base
1721 // initializer. However, deconstructing the ASTs is a dicey process,
1722 // and this approach is far more likely to get the corner cases right.
1723 if (CurContext->isDependentContext()) {
John McCall60d7b3a2010-08-24 06:29:42 +00001724 ExprResult Init
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001725 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1726 RParenLoc));
Sean Huntcbb67482011-01-08 20:30:50 +00001727 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001728 BaseSpec->isVirtual(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001729 LParenLoc,
1730 Init.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001731 RParenLoc,
1732 EllipsisLoc);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001733 }
1734
Sean Huntcbb67482011-01-08 20:30:50 +00001735 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001736 BaseSpec->isVirtual(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001737 LParenLoc,
1738 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001739 RParenLoc,
1740 EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001741}
1742
Anders Carlssone5ef7402010-04-23 03:10:23 +00001743/// ImplicitInitializerKind - How an implicit base or member initializer should
1744/// initialize its base or member.
1745enum ImplicitInitializerKind {
1746 IIK_Default,
1747 IIK_Copy,
1748 IIK_Move
1749};
1750
Anders Carlssondefefd22010-04-23 02:00:02 +00001751static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001752BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00001753 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00001754 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00001755 bool IsInheritedVirtualBase,
Sean Huntcbb67482011-01-08 20:30:50 +00001756 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00001757 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00001758 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
1759 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00001760
John McCall60d7b3a2010-08-24 06:29:42 +00001761 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00001762
1763 switch (ImplicitInitKind) {
1764 case IIK_Default: {
1765 InitializationKind InitKind
1766 = InitializationKind::CreateDefault(Constructor->getLocation());
1767 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
1768 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00001769 MultiExprArg(SemaRef, 0, 0));
Anders Carlssone5ef7402010-04-23 03:10:23 +00001770 break;
1771 }
Anders Carlsson84688f22010-04-20 23:11:20 +00001772
Anders Carlssone5ef7402010-04-23 03:10:23 +00001773 case IIK_Copy: {
1774 ParmVarDecl *Param = Constructor->getParamDecl(0);
1775 QualType ParamType = Param->getType().getNonReferenceType();
1776
1777 Expr *CopyCtorArg =
Douglas Gregor40d96a62011-02-28 21:54:11 +00001778 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param,
John McCallf89e55a2010-11-18 06:31:45 +00001779 Constructor->getLocation(), ParamType,
1780 VK_LValue, 0);
Anders Carlssone5ef7402010-04-23 03:10:23 +00001781
Anders Carlssonc7957502010-04-24 22:02:54 +00001782 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00001783 QualType ArgTy =
1784 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
1785 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00001786
1787 CXXCastPath BasePath;
1788 BasePath.push_back(BaseSpec);
John Wiegley429bb272011-04-08 18:41:53 +00001789 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
1790 CK_UncheckedDerivedToBase,
1791 VK_LValue, &BasePath).take();
Anders Carlssonc7957502010-04-24 22:02:54 +00001792
Anders Carlssone5ef7402010-04-23 03:10:23 +00001793 InitializationKind InitKind
1794 = InitializationKind::CreateDirect(Constructor->getLocation(),
1795 SourceLocation(), SourceLocation());
1796 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
1797 &CopyCtorArg, 1);
1798 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00001799 MultiExprArg(&CopyCtorArg, 1));
Anders Carlssone5ef7402010-04-23 03:10:23 +00001800 break;
1801 }
Anders Carlsson84688f22010-04-20 23:11:20 +00001802
Anders Carlssone5ef7402010-04-23 03:10:23 +00001803 case IIK_Move:
1804 assert(false && "Unhandled initializer kind!");
1805 }
John McCall9ae2f072010-08-23 23:25:46 +00001806
Douglas Gregor53c374f2010-12-07 00:41:46 +00001807 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00001808 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00001809 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00001810
Anders Carlssondefefd22010-04-23 02:00:02 +00001811 CXXBaseInit =
Sean Huntcbb67482011-01-08 20:30:50 +00001812 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlsson84688f22010-04-20 23:11:20 +00001813 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
1814 SourceLocation()),
1815 BaseSpec->isVirtual(),
1816 SourceLocation(),
1817 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001818 SourceLocation(),
Anders Carlsson84688f22010-04-20 23:11:20 +00001819 SourceLocation());
1820
Anders Carlssondefefd22010-04-23 02:00:02 +00001821 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00001822}
1823
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001824static bool
1825BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00001826 ImplicitInitializerKind ImplicitInitKind,
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001827 FieldDecl *Field,
Sean Huntcbb67482011-01-08 20:30:50 +00001828 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00001829 if (Field->isInvalidDecl())
1830 return true;
1831
Chandler Carruthf186b542010-06-29 23:50:44 +00001832 SourceLocation Loc = Constructor->getLocation();
1833
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001834 if (ImplicitInitKind == IIK_Copy) {
1835 ParmVarDecl *Param = Constructor->getParamDecl(0);
1836 QualType ParamType = Param->getType().getNonReferenceType();
1837
1838 Expr *MemberExprBase =
Douglas Gregor40d96a62011-02-28 21:54:11 +00001839 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param,
John McCallf89e55a2010-11-18 06:31:45 +00001840 Loc, ParamType, VK_LValue, 0);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001841
1842 // Build a reference to this field within the parameter.
1843 CXXScopeSpec SS;
1844 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
1845 Sema::LookupMemberName);
1846 MemberLookup.addDecl(Field, AS_public);
1847 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00001848 ExprResult CopyCtorArg
John McCall9ae2f072010-08-23 23:25:46 +00001849 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001850 ParamType, Loc,
1851 /*IsArrow=*/false,
1852 SS,
1853 /*FirstQualifierInScope=*/0,
1854 MemberLookup,
1855 /*TemplateArgs=*/0);
1856 if (CopyCtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001857 return true;
1858
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001859 // When the field we are copying is an array, create index variables for
1860 // each dimension of the array. We use these index variables to subscript
1861 // the source array, and other clients (e.g., CodeGen) will perform the
1862 // necessary iteration with these index variables.
1863 llvm::SmallVector<VarDecl *, 4> IndexVariables;
1864 QualType BaseType = Field->getType();
1865 QualType SizeType = SemaRef.Context.getSizeType();
1866 while (const ConstantArrayType *Array
1867 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
1868 // Create the iteration variable for this array index.
1869 IdentifierInfo *IterationVarName = 0;
1870 {
1871 llvm::SmallString<8> Str;
1872 llvm::raw_svector_ostream OS(Str);
1873 OS << "__i" << IndexVariables.size();
1874 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
1875 }
1876 VarDecl *IterationVar
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001877 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001878 IterationVarName, SizeType,
1879 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00001880 SC_None, SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001881 IndexVariables.push_back(IterationVar);
1882
1883 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00001884 ExprResult IterationVarRef
John McCallf89e55a2010-11-18 06:31:45 +00001885 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001886 assert(!IterationVarRef.isInvalid() &&
1887 "Reference to invented variable cannot fail!");
1888
1889 // Subscript the array with this iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00001890 CopyCtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CopyCtorArg.take(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001891 Loc,
John McCall9ae2f072010-08-23 23:25:46 +00001892 IterationVarRef.take(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001893 Loc);
1894 if (CopyCtorArg.isInvalid())
1895 return true;
1896
1897 BaseType = Array->getElementType();
1898 }
1899
1900 // Construct the entity that we will be initializing. For an array, this
1901 // will be first element in the array, which may require several levels
1902 // of array-subscript entities.
1903 llvm::SmallVector<InitializedEntity, 4> Entities;
1904 Entities.reserve(1 + IndexVariables.size());
1905 Entities.push_back(InitializedEntity::InitializeMember(Field));
1906 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
1907 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
1908 0,
1909 Entities.back()));
1910
1911 // Direct-initialize to use the copy constructor.
1912 InitializationKind InitKind =
1913 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
1914
1915 Expr *CopyCtorArgE = CopyCtorArg.takeAs<Expr>();
1916 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
1917 &CopyCtorArgE, 1);
1918
John McCall60d7b3a2010-08-24 06:29:42 +00001919 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001920 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00001921 MultiExprArg(&CopyCtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00001922 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001923 if (MemberInit.isInvalid())
1924 return true;
1925
1926 CXXMemberInit
Sean Huntcbb67482011-01-08 20:30:50 +00001927 = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001928 MemberInit.takeAs<Expr>(), Loc,
1929 IndexVariables.data(),
1930 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00001931 return false;
1932 }
1933
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001934 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
1935
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001936 QualType FieldBaseElementType =
1937 SemaRef.Context.getBaseElementType(Field->getType());
1938
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001939 if (FieldBaseElementType->isRecordType()) {
1940 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001941 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00001942 InitializationKind::CreateDefault(Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001943
1944 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00001945 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00001946 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCall9ae2f072010-08-23 23:25:46 +00001947
Douglas Gregor53c374f2010-12-07 00:41:46 +00001948 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001949 if (MemberInit.isInvalid())
1950 return true;
1951
1952 CXXMemberInit =
Sean Huntcbb67482011-01-08 20:30:50 +00001953 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Chandler Carruthf186b542010-06-29 23:50:44 +00001954 Field, Loc, Loc,
John McCall9ae2f072010-08-23 23:25:46 +00001955 MemberInit.get(),
Chandler Carruthf186b542010-06-29 23:50:44 +00001956 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001957 return false;
1958 }
Anders Carlsson114a2972010-04-23 03:07:47 +00001959
1960 if (FieldBaseElementType->isReferenceType()) {
1961 SemaRef.Diag(Constructor->getLocation(),
1962 diag::err_uninitialized_member_in_ctor)
1963 << (int)Constructor->isImplicit()
1964 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1965 << 0 << Field->getDeclName();
1966 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1967 return true;
1968 }
1969
1970 if (FieldBaseElementType.isConstQualified()) {
1971 SemaRef.Diag(Constructor->getLocation(),
1972 diag::err_uninitialized_member_in_ctor)
1973 << (int)Constructor->isImplicit()
1974 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1975 << 1 << Field->getDeclName();
1976 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1977 return true;
1978 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001979
1980 // Nothing to initialize.
1981 CXXMemberInit = 0;
1982 return false;
1983}
John McCallf1860e52010-05-20 23:23:51 +00001984
1985namespace {
1986struct BaseAndFieldInfo {
1987 Sema &S;
1988 CXXConstructorDecl *Ctor;
1989 bool AnyErrorsInInits;
1990 ImplicitInitializerKind IIK;
Sean Huntcbb67482011-01-08 20:30:50 +00001991 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
1992 llvm::SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallf1860e52010-05-20 23:23:51 +00001993
1994 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
1995 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
1996 // FIXME: Handle implicit move constructors.
1997 if (Ctor->isImplicit() && Ctor->isCopyConstructor())
1998 IIK = IIK_Copy;
1999 else
2000 IIK = IIK_Default;
2001 }
2002};
2003}
2004
2005static bool CollectFieldInitializer(BaseAndFieldInfo &Info,
2006 FieldDecl *Top, FieldDecl *Field) {
2007
Chandler Carruthe861c602010-06-30 02:59:29 +00002008 // Overwhelmingly common case: we have a direct initializer for this field.
Sean Huntcbb67482011-01-08 20:30:50 +00002009 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002010 Info.AllToInit.push_back(Init);
John McCallf1860e52010-05-20 23:23:51 +00002011 return false;
2012 }
2013
2014 if (Info.IIK == IIK_Default && Field->isAnonymousStructOrUnion()) {
2015 const RecordType *FieldClassType = Field->getType()->getAs<RecordType>();
2016 assert(FieldClassType && "anonymous struct/union without record type");
John McCallf1860e52010-05-20 23:23:51 +00002017 CXXRecordDecl *FieldClassDecl
2018 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Chandler Carruthe861c602010-06-30 02:59:29 +00002019
2020 // Even though union members never have non-trivial default
2021 // constructions in C++03, we still build member initializers for aggregate
2022 // record types which can be union members, and C++0x allows non-trivial
2023 // default constructors for union members, so we ensure that only one
2024 // member is initialized for these.
2025 if (FieldClassDecl->isUnion()) {
2026 // First check for an explicit initializer for one field.
2027 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
2028 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
Sean Huntcbb67482011-01-08 20:30:50 +00002029 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(*FA)) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002030 Info.AllToInit.push_back(Init);
Chandler Carruthe861c602010-06-30 02:59:29 +00002031
2032 // Once we've initialized a field of an anonymous union, the union
2033 // field in the class is also initialized, so exit immediately.
2034 return false;
Argyrios Kyrtzidis881b36c2010-08-16 17:27:13 +00002035 } else if ((*FA)->isAnonymousStructOrUnion()) {
2036 if (CollectFieldInitializer(Info, Top, *FA))
2037 return true;
Chandler Carruthe861c602010-06-30 02:59:29 +00002038 }
2039 }
2040
2041 // Fallthrough and construct a default initializer for the union as
2042 // a whole, which can call its default constructor if such a thing exists
2043 // (C++0x perhaps). FIXME: It's not clear that this is the correct
2044 // behavior going forward with C++0x, when anonymous unions there are
2045 // finalized, we should revisit this.
2046 } else {
2047 // For structs, we simply descend through to initialize all members where
2048 // necessary.
2049 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
2050 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
2051 if (CollectFieldInitializer(Info, Top, *FA))
2052 return true;
2053 }
2054 }
John McCallf1860e52010-05-20 23:23:51 +00002055 }
2056
2057 // Don't try to build an implicit initializer if there were semantic
2058 // errors in any of the initializers (and therefore we might be
2059 // missing some that the user actually wrote).
2060 if (Info.AnyErrorsInInits)
2061 return false;
2062
Sean Huntcbb67482011-01-08 20:30:50 +00002063 CXXCtorInitializer *Init = 0;
John McCallf1860e52010-05-20 23:23:51 +00002064 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, Init))
2065 return true;
John McCallf1860e52010-05-20 23:23:51 +00002066
Francois Pichet00eb3f92010-12-04 09:14:42 +00002067 if (Init)
2068 Info.AllToInit.push_back(Init);
2069
John McCallf1860e52010-05-20 23:23:51 +00002070 return false;
2071}
Sean Hunt059ce0d2011-05-01 07:04:31 +00002072
2073bool
2074Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
2075 CXXCtorInitializer *Initializer) {
Sean Huntfe57eef2011-05-04 05:57:24 +00002076 assert(Initializer->isDelegatingInitializer());
Sean Hunt01aacc02011-05-03 20:43:02 +00002077 Constructor->setNumCtorInitializers(1);
2078 CXXCtorInitializer **initializer =
2079 new (Context) CXXCtorInitializer*[1];
2080 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
2081 Constructor->setCtorInitializers(initializer);
2082
Sean Huntb76af9c2011-05-03 23:05:34 +00002083 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
2084 MarkDeclarationReferenced(Initializer->getSourceLocation(), Dtor);
2085 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
2086 }
2087
Sean Huntc1598702011-05-05 00:05:47 +00002088 DelegatingCtorDecls.push_back(Constructor);
Sean Huntfe57eef2011-05-04 05:57:24 +00002089
Sean Hunt059ce0d2011-05-01 07:04:31 +00002090 return false;
2091}
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002092
Eli Friedman80c30da2009-11-09 19:20:36 +00002093bool
Sean Huntcbb67482011-01-08 20:30:50 +00002094Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
2095 CXXCtorInitializer **Initializers,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002096 unsigned NumInitializers,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002097 bool AnyErrors) {
John McCalld6ca8da2010-04-10 07:37:23 +00002098 if (Constructor->getDeclContext()->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002099 // Just store the initializers as written, they will be checked during
2100 // instantiation.
2101 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00002102 Constructor->setNumCtorInitializers(NumInitializers);
2103 CXXCtorInitializer **baseOrMemberInitializers =
2104 new (Context) CXXCtorInitializer*[NumInitializers];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002105 memcpy(baseOrMemberInitializers, Initializers,
Sean Huntcbb67482011-01-08 20:30:50 +00002106 NumInitializers * sizeof(CXXCtorInitializer*));
2107 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002108 }
2109
2110 return false;
2111 }
2112
John McCallf1860e52010-05-20 23:23:51 +00002113 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00002114
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002115 // We need to build the initializer AST according to order of construction
2116 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00002117 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00002118 if (!ClassDecl)
2119 return true;
2120
Eli Friedman80c30da2009-11-09 19:20:36 +00002121 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002122
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002123 for (unsigned i = 0; i < NumInitializers; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00002124 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002125
2126 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00002127 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002128 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00002129 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002130 }
2131
Anders Carlsson711f34a2010-04-21 19:52:01 +00002132 // Keep track of the direct virtual bases.
2133 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
2134 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
2135 E = ClassDecl->bases_end(); I != E; ++I) {
2136 if (I->isVirtual())
2137 DirectVBases.insert(I);
2138 }
2139
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002140 // Push virtual bases before others.
2141 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2142 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2143
Sean Huntcbb67482011-01-08 20:30:50 +00002144 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00002145 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
2146 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002147 } else if (!AnyErrors) {
Anders Carlsson711f34a2010-04-21 19:52:01 +00002148 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00002149 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00002150 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002151 VBase, IsInheritedVirtualBase,
2152 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002153 HadError = true;
2154 continue;
2155 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002156
John McCallf1860e52010-05-20 23:23:51 +00002157 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002158 }
2159 }
Mike Stump1eb44332009-09-09 15:08:12 +00002160
John McCallf1860e52010-05-20 23:23:51 +00002161 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002162 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2163 E = ClassDecl->bases_end(); Base != E; ++Base) {
2164 // Virtuals are in the virtual base list and already constructed.
2165 if (Base->isVirtual())
2166 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00002167
Sean Huntcbb67482011-01-08 20:30:50 +00002168 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00002169 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
2170 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002171 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00002172 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00002173 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002174 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00002175 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002176 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002177 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002178 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00002179
John McCallf1860e52010-05-20 23:23:51 +00002180 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002181 }
2182 }
Mike Stump1eb44332009-09-09 15:08:12 +00002183
John McCallf1860e52010-05-20 23:23:51 +00002184 // Fields.
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002185 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00002186 E = ClassDecl->field_end(); Field != E; ++Field) {
2187 if ((*Field)->getType()->isIncompleteArrayType()) {
2188 assert(ClassDecl->hasFlexibleArrayMember() &&
2189 "Incomplete array type is not valid");
2190 continue;
2191 }
John McCallf1860e52010-05-20 23:23:51 +00002192 if (CollectFieldInitializer(Info, *Field, *Field))
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002193 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00002194 }
Mike Stump1eb44332009-09-09 15:08:12 +00002195
John McCallf1860e52010-05-20 23:23:51 +00002196 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002197 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00002198 Constructor->setNumCtorInitializers(NumInitializers);
2199 CXXCtorInitializer **baseOrMemberInitializers =
2200 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00002201 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00002202 NumInitializers * sizeof(CXXCtorInitializer*));
2203 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00002204
John McCallef027fe2010-03-16 21:39:52 +00002205 // Constructors implicitly reference the base and member
2206 // destructors.
2207 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
2208 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002209 }
Eli Friedman80c30da2009-11-09 19:20:36 +00002210
2211 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002212}
2213
Eli Friedman6347f422009-07-21 19:28:10 +00002214static void *GetKeyForTopLevelField(FieldDecl *Field) {
2215 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00002216 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00002217 if (RT->getDecl()->isAnonymousStructOrUnion())
2218 return static_cast<void *>(RT->getDecl());
2219 }
2220 return static_cast<void *>(Field);
2221}
2222
Anders Carlssonea356fb2010-04-02 05:42:15 +00002223static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCallf4c73712011-01-19 06:33:43 +00002224 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssoncdc83c72009-09-01 06:22:14 +00002225}
2226
Anders Carlssonea356fb2010-04-02 05:42:15 +00002227static void *GetKeyForMember(ASTContext &Context,
Sean Huntcbb67482011-01-08 20:30:50 +00002228 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002229 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00002230 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00002231
Eli Friedman6347f422009-07-21 19:28:10 +00002232 // For fields injected into the class via declaration of an anonymous union,
2233 // use its anonymous union class declaration as the unique key.
Francois Pichet00eb3f92010-12-04 09:14:42 +00002234 FieldDecl *Field = Member->getAnyMember();
2235
John McCall3c3ccdb2010-04-10 09:28:51 +00002236 // If the field is a member of an anonymous struct or union, our key
2237 // is the anonymous record decl that's a direct child of the class.
Anders Carlssonee11b2d2010-03-30 16:19:37 +00002238 RecordDecl *RD = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00002239 if (RD->isAnonymousStructOrUnion()) {
2240 while (true) {
2241 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
2242 if (Parent->isAnonymousStructOrUnion())
2243 RD = Parent;
2244 else
2245 break;
2246 }
2247
Anders Carlssonee11b2d2010-03-30 16:19:37 +00002248 return static_cast<void *>(RD);
John McCall3c3ccdb2010-04-10 09:28:51 +00002249 }
Mike Stump1eb44332009-09-09 15:08:12 +00002250
Anders Carlsson8f1a2402010-03-30 15:39:27 +00002251 return static_cast<void *>(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00002252}
2253
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002254static void
2255DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson071d6102010-04-02 03:38:04 +00002256 const CXXConstructorDecl *Constructor,
Sean Huntcbb67482011-01-08 20:30:50 +00002257 CXXCtorInitializer **Inits,
John McCalld6ca8da2010-04-10 07:37:23 +00002258 unsigned NumInits) {
2259 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00002260 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002261
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00002262 // Don't check initializers order unless the warning is enabled at the
2263 // location of at least one initializer.
2264 bool ShouldCheckOrder = false;
2265 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00002266 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00002267 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
2268 Init->getSourceLocation())
2269 != Diagnostic::Ignored) {
2270 ShouldCheckOrder = true;
2271 break;
2272 }
2273 }
2274 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002275 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002276
John McCalld6ca8da2010-04-10 07:37:23 +00002277 // Build the list of bases and members in the order that they'll
2278 // actually be initialized. The explicit initializers should be in
2279 // this same order but may be missing things.
2280 llvm::SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00002281
Anders Carlsson071d6102010-04-02 03:38:04 +00002282 const CXXRecordDecl *ClassDecl = Constructor->getParent();
2283
John McCalld6ca8da2010-04-10 07:37:23 +00002284 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00002285 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002286 ClassDecl->vbases_begin(),
2287 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00002288 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002289
John McCalld6ca8da2010-04-10 07:37:23 +00002290 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00002291 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002292 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002293 if (Base->isVirtual())
2294 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00002295 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002296 }
Mike Stump1eb44332009-09-09 15:08:12 +00002297
John McCalld6ca8da2010-04-10 07:37:23 +00002298 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002299 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2300 E = ClassDecl->field_end(); Field != E; ++Field)
John McCalld6ca8da2010-04-10 07:37:23 +00002301 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Mike Stump1eb44332009-09-09 15:08:12 +00002302
John McCalld6ca8da2010-04-10 07:37:23 +00002303 unsigned NumIdealInits = IdealInitKeys.size();
2304 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00002305
Sean Huntcbb67482011-01-08 20:30:50 +00002306 CXXCtorInitializer *PrevInit = 0;
John McCalld6ca8da2010-04-10 07:37:23 +00002307 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00002308 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichet00eb3f92010-12-04 09:14:42 +00002309 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00002310
2311 // Scan forward to try to find this initializer in the idealized
2312 // initializers list.
2313 for (; IdealIndex != NumIdealInits; ++IdealIndex)
2314 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002315 break;
John McCalld6ca8da2010-04-10 07:37:23 +00002316
2317 // If we didn't find this initializer, it must be because we
2318 // scanned past it on a previous iteration. That can only
2319 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00002320 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00002321 Sema::SemaDiagnosticBuilder D =
2322 SemaRef.Diag(PrevInit->getSourceLocation(),
2323 diag::warn_initializer_out_of_order);
2324
Francois Pichet00eb3f92010-12-04 09:14:42 +00002325 if (PrevInit->isAnyMemberInitializer())
2326 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00002327 else
2328 D << 1 << PrevInit->getBaseClassInfo()->getType();
2329
Francois Pichet00eb3f92010-12-04 09:14:42 +00002330 if (Init->isAnyMemberInitializer())
2331 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00002332 else
2333 D << 1 << Init->getBaseClassInfo()->getType();
2334
2335 // Move back to the initializer's location in the ideal list.
2336 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
2337 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002338 break;
John McCalld6ca8da2010-04-10 07:37:23 +00002339
2340 assert(IdealIndex != NumIdealInits &&
2341 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00002342 }
John McCalld6ca8da2010-04-10 07:37:23 +00002343
2344 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00002345 }
Anders Carlssona7b35212009-03-25 02:58:17 +00002346}
2347
John McCall3c3ccdb2010-04-10 09:28:51 +00002348namespace {
2349bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00002350 CXXCtorInitializer *Init,
2351 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00002352 if (!PrevInit) {
2353 PrevInit = Init;
2354 return false;
2355 }
2356
2357 if (FieldDecl *Field = Init->getMember())
2358 S.Diag(Init->getSourceLocation(),
2359 diag::err_multiple_mem_initialization)
2360 << Field->getDeclName()
2361 << Init->getSourceRange();
2362 else {
John McCallf4c73712011-01-19 06:33:43 +00002363 const Type *BaseClass = Init->getBaseClass();
John McCall3c3ccdb2010-04-10 09:28:51 +00002364 assert(BaseClass && "neither field nor base");
2365 S.Diag(Init->getSourceLocation(),
2366 diag::err_multiple_base_initialization)
2367 << QualType(BaseClass, 0)
2368 << Init->getSourceRange();
2369 }
2370 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
2371 << 0 << PrevInit->getSourceRange();
2372
2373 return true;
2374}
2375
Sean Huntcbb67482011-01-08 20:30:50 +00002376typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00002377typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
2378
2379bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00002380 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00002381 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002382 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00002383 RecordDecl *Parent = Field->getParent();
2384 if (!Parent->isAnonymousStructOrUnion())
2385 return false;
2386
2387 NamedDecl *Child = Field;
2388 do {
2389 if (Parent->isUnion()) {
2390 UnionEntry &En = Unions[Parent];
2391 if (En.first && En.first != Child) {
2392 S.Diag(Init->getSourceLocation(),
2393 diag::err_multiple_mem_union_initialization)
2394 << Field->getDeclName()
2395 << Init->getSourceRange();
2396 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
2397 << 0 << En.second->getSourceRange();
2398 return true;
2399 } else if (!En.first) {
2400 En.first = Child;
2401 En.second = Init;
2402 }
2403 }
2404
2405 Child = Parent;
2406 Parent = cast<RecordDecl>(Parent->getDeclContext());
2407 } while (Parent->isAnonymousStructOrUnion());
2408
2409 return false;
2410}
2411}
2412
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002413/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00002414void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002415 SourceLocation ColonLoc,
2416 MemInitTy **meminits, unsigned NumMemInits,
2417 bool AnyErrors) {
2418 if (!ConstructorDecl)
2419 return;
2420
2421 AdjustDeclIfTemplate(ConstructorDecl);
2422
2423 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002424 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002425
2426 if (!Constructor) {
2427 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
2428 return;
2429 }
2430
Sean Huntcbb67482011-01-08 20:30:50 +00002431 CXXCtorInitializer **MemInits =
2432 reinterpret_cast<CXXCtorInitializer **>(meminits);
John McCall3c3ccdb2010-04-10 09:28:51 +00002433
2434 // Mapping for the duplicate initializers check.
2435 // For member initializers, this is keyed with a FieldDecl*.
2436 // For base initializers, this is keyed with a Type*.
Sean Huntcbb67482011-01-08 20:30:50 +00002437 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00002438
2439 // Mapping for the inconsistent anonymous-union initializers check.
2440 RedundantUnionMap MemberUnions;
2441
Anders Carlssonea356fb2010-04-02 05:42:15 +00002442 bool HadError = false;
2443 for (unsigned i = 0; i < NumMemInits; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00002444 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002445
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00002446 // Set the source order index.
2447 Init->setSourceOrder(i);
2448
Francois Pichet00eb3f92010-12-04 09:14:42 +00002449 if (Init->isAnyMemberInitializer()) {
2450 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00002451 if (CheckRedundantInit(*this, Init, Members[Field]) ||
2452 CheckRedundantUnionInit(*this, Init, MemberUnions))
2453 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00002454 } else if (Init->isBaseInitializer()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00002455 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
2456 if (CheckRedundantInit(*this, Init, Members[Key]))
2457 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00002458 } else {
2459 assert(Init->isDelegatingInitializer());
2460 // This must be the only initializer
2461 if (i != 0 || NumMemInits > 1) {
2462 Diag(MemInits[0]->getSourceLocation(),
2463 diag::err_delegating_initializer_alone)
2464 << MemInits[0]->getSourceRange();
2465 HadError = true;
Sean Hunt059ce0d2011-05-01 07:04:31 +00002466 // We will treat this as being the only initializer.
Sean Hunt41717662011-02-26 19:13:13 +00002467 }
Sean Huntfe57eef2011-05-04 05:57:24 +00002468 SetDelegatingInitializer(Constructor, MemInits[i]);
Sean Hunt059ce0d2011-05-01 07:04:31 +00002469 // Return immediately as the initializer is set.
2470 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002471 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002472 }
2473
Anders Carlssonea356fb2010-04-02 05:42:15 +00002474 if (HadError)
2475 return;
2476
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002477 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00002478
Sean Huntcbb67482011-01-08 20:30:50 +00002479 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002480}
2481
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002482void
John McCallef027fe2010-03-16 21:39:52 +00002483Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
2484 CXXRecordDecl *ClassDecl) {
2485 // Ignore dependent contexts.
2486 if (ClassDecl->isDependentContext())
Anders Carlsson9f853df2009-11-17 04:44:12 +00002487 return;
John McCall58e6f342010-03-16 05:22:47 +00002488
2489 // FIXME: all the access-control diagnostics are positioned on the
2490 // field/base declaration. That's probably good; that said, the
2491 // user might reasonably want to know why the destructor is being
2492 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00002493
Anders Carlsson9f853df2009-11-17 04:44:12 +00002494 // Non-static data members.
2495 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
2496 E = ClassDecl->field_end(); I != E; ++I) {
2497 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00002498 if (Field->isInvalidDecl())
2499 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00002500 QualType FieldType = Context.getBaseElementType(Field->getType());
2501
2502 const RecordType* RT = FieldType->getAs<RecordType>();
2503 if (!RT)
2504 continue;
2505
2506 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002507 if (FieldClassDecl->isInvalidDecl())
2508 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00002509 if (FieldClassDecl->hasTrivialDestructor())
2510 continue;
2511
Douglas Gregordb89f282010-07-01 22:47:18 +00002512 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002513 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00002514 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002515 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00002516 << Field->getDeclName()
2517 << FieldType);
2518
John McCallef027fe2010-03-16 21:39:52 +00002519 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00002520 }
2521
John McCall58e6f342010-03-16 05:22:47 +00002522 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
2523
Anders Carlsson9f853df2009-11-17 04:44:12 +00002524 // Bases.
2525 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2526 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00002527 // Bases are always records in a well-formed non-dependent class.
2528 const RecordType *RT = Base->getType()->getAs<RecordType>();
2529
2530 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00002531 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00002532 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00002533
John McCall58e6f342010-03-16 05:22:47 +00002534 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002535 // If our base class is invalid, we probably can't get its dtor anyway.
2536 if (BaseClassDecl->isInvalidDecl())
2537 continue;
2538 // Ignore trivial destructors.
Anders Carlsson9f853df2009-11-17 04:44:12 +00002539 if (BaseClassDecl->hasTrivialDestructor())
2540 continue;
John McCall58e6f342010-03-16 05:22:47 +00002541
Douglas Gregordb89f282010-07-01 22:47:18 +00002542 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002543 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00002544
2545 // FIXME: caret should be on the start of the class name
2546 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002547 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00002548 << Base->getType()
2549 << Base->getSourceRange());
Anders Carlsson9f853df2009-11-17 04:44:12 +00002550
John McCallef027fe2010-03-16 21:39:52 +00002551 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00002552 }
2553
2554 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002555 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2556 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00002557
2558 // Bases are always records in a well-formed non-dependent class.
2559 const RecordType *RT = VBase->getType()->getAs<RecordType>();
2560
2561 // Ignore direct virtual bases.
2562 if (DirectVirtualBases.count(RT))
2563 continue;
2564
John McCall58e6f342010-03-16 05:22:47 +00002565 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002566 // If our base class is invalid, we probably can't get its dtor anyway.
2567 if (BaseClassDecl->isInvalidDecl())
2568 continue;
2569 // Ignore trivial destructors.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002570 if (BaseClassDecl->hasTrivialDestructor())
2571 continue;
John McCall58e6f342010-03-16 05:22:47 +00002572
Douglas Gregordb89f282010-07-01 22:47:18 +00002573 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002574 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00002575 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002576 PDiag(diag::err_access_dtor_vbase)
John McCall58e6f342010-03-16 05:22:47 +00002577 << VBase->getType());
2578
John McCallef027fe2010-03-16 21:39:52 +00002579 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002580 }
2581}
2582
John McCalld226f652010-08-21 09:40:31 +00002583void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00002584 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00002585 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002586
Mike Stump1eb44332009-09-09 15:08:12 +00002587 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002588 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Sean Huntcbb67482011-01-08 20:30:50 +00002589 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00002590}
2591
Mike Stump1eb44332009-09-09 15:08:12 +00002592bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00002593 unsigned DiagID, AbstractDiagSelID SelID) {
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002594 if (SelID == -1)
John McCall94c3b562010-08-18 09:41:07 +00002595 return RequireNonAbstractType(Loc, T, PDiag(DiagID));
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002596 else
John McCall94c3b562010-08-18 09:41:07 +00002597 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
Mike Stump1eb44332009-09-09 15:08:12 +00002598}
2599
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002600bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00002601 const PartialDiagnostic &PD) {
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002602 if (!getLangOptions().CPlusPlus)
2603 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002604
Anders Carlsson11f21a02009-03-23 19:10:31 +00002605 if (const ArrayType *AT = Context.getAsArrayType(T))
John McCall94c3b562010-08-18 09:41:07 +00002606 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Mike Stump1eb44332009-09-09 15:08:12 +00002607
Ted Kremenek6217b802009-07-29 21:53:49 +00002608 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002609 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00002610 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002611 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00002612
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002613 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
John McCall94c3b562010-08-18 09:41:07 +00002614 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002615 }
Mike Stump1eb44332009-09-09 15:08:12 +00002616
Ted Kremenek6217b802009-07-29 21:53:49 +00002617 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002618 if (!RT)
2619 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002620
John McCall86ff3082010-02-04 22:26:26 +00002621 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002622
John McCall94c3b562010-08-18 09:41:07 +00002623 // We can't answer whether something is abstract until it has a
2624 // definition. If it's currently being defined, we'll walk back
2625 // over all the declarations when we have a full definition.
2626 const CXXRecordDecl *Def = RD->getDefinition();
2627 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00002628 return false;
2629
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002630 if (!RD->isAbstract())
2631 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002632
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002633 Diag(Loc, PD) << RD->getDeclName();
John McCall94c3b562010-08-18 09:41:07 +00002634 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00002635
John McCall94c3b562010-08-18 09:41:07 +00002636 return true;
2637}
2638
2639void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
2640 // Check if we've already emitted the list of pure virtual functions
2641 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002642 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00002643 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002644
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002645 CXXFinalOverriderMap FinalOverriders;
2646 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00002647
Anders Carlssonffdb2d22010-06-03 01:00:02 +00002648 // Keep a set of seen pure methods so we won't diagnose the same method
2649 // more than once.
2650 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
2651
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002652 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2653 MEnd = FinalOverriders.end();
2654 M != MEnd;
2655 ++M) {
2656 for (OverridingMethods::iterator SO = M->second.begin(),
2657 SOEnd = M->second.end();
2658 SO != SOEnd; ++SO) {
2659 // C++ [class.abstract]p4:
2660 // A class is abstract if it contains or inherits at least one
2661 // pure virtual function for which the final overrider is pure
2662 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00002663
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002664 //
2665 if (SO->second.size() != 1)
2666 continue;
2667
2668 if (!SO->second.front().Method->isPure())
2669 continue;
2670
Anders Carlssonffdb2d22010-06-03 01:00:02 +00002671 if (!SeenPureMethods.insert(SO->second.front().Method))
2672 continue;
2673
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002674 Diag(SO->second.front().Method->getLocation(),
2675 diag::note_pure_virtual_function)
Chandler Carruth45f11b72011-02-18 23:59:51 +00002676 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002677 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002678 }
2679
2680 if (!PureVirtualClassDiagSet)
2681 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2682 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002683}
2684
Anders Carlsson8211eff2009-03-24 01:19:16 +00002685namespace {
John McCall94c3b562010-08-18 09:41:07 +00002686struct AbstractUsageInfo {
2687 Sema &S;
2688 CXXRecordDecl *Record;
2689 CanQualType AbstractType;
2690 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00002691
John McCall94c3b562010-08-18 09:41:07 +00002692 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
2693 : S(S), Record(Record),
2694 AbstractType(S.Context.getCanonicalType(
2695 S.Context.getTypeDeclType(Record))),
2696 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00002697
John McCall94c3b562010-08-18 09:41:07 +00002698 void DiagnoseAbstractType() {
2699 if (Invalid) return;
2700 S.DiagnoseAbstractType(Record);
2701 Invalid = true;
2702 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00002703
John McCall94c3b562010-08-18 09:41:07 +00002704 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
2705};
2706
2707struct CheckAbstractUsage {
2708 AbstractUsageInfo &Info;
2709 const NamedDecl *Ctx;
2710
2711 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
2712 : Info(Info), Ctx(Ctx) {}
2713
2714 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2715 switch (TL.getTypeLocClass()) {
2716#define ABSTRACT_TYPELOC(CLASS, PARENT)
2717#define TYPELOC(CLASS, PARENT) \
2718 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
2719#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00002720 }
John McCall94c3b562010-08-18 09:41:07 +00002721 }
Mike Stump1eb44332009-09-09 15:08:12 +00002722
John McCall94c3b562010-08-18 09:41:07 +00002723 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2724 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
2725 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor70191862011-02-22 23:21:06 +00002726 if (!TL.getArg(I))
2727 continue;
2728
John McCall94c3b562010-08-18 09:41:07 +00002729 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
2730 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00002731 }
John McCall94c3b562010-08-18 09:41:07 +00002732 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00002733
John McCall94c3b562010-08-18 09:41:07 +00002734 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2735 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
2736 }
Mike Stump1eb44332009-09-09 15:08:12 +00002737
John McCall94c3b562010-08-18 09:41:07 +00002738 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2739 // Visit the type parameters from a permissive context.
2740 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2741 TemplateArgumentLoc TAL = TL.getArgLoc(I);
2742 if (TAL.getArgument().getKind() == TemplateArgument::Type)
2743 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
2744 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
2745 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00002746 }
John McCall94c3b562010-08-18 09:41:07 +00002747 }
Mike Stump1eb44332009-09-09 15:08:12 +00002748
John McCall94c3b562010-08-18 09:41:07 +00002749 // Visit pointee types from a permissive context.
2750#define CheckPolymorphic(Type) \
2751 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
2752 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
2753 }
2754 CheckPolymorphic(PointerTypeLoc)
2755 CheckPolymorphic(ReferenceTypeLoc)
2756 CheckPolymorphic(MemberPointerTypeLoc)
2757 CheckPolymorphic(BlockPointerTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00002758
John McCall94c3b562010-08-18 09:41:07 +00002759 /// Handle all the types we haven't given a more specific
2760 /// implementation for above.
2761 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2762 // Every other kind of type that we haven't called out already
2763 // that has an inner type is either (1) sugar or (2) contains that
2764 // inner type in some way as a subobject.
2765 if (TypeLoc Next = TL.getNextTypeLoc())
2766 return Visit(Next, Sel);
2767
2768 // If there's no inner type and we're in a permissive context,
2769 // don't diagnose.
2770 if (Sel == Sema::AbstractNone) return;
2771
2772 // Check whether the type matches the abstract type.
2773 QualType T = TL.getType();
2774 if (T->isArrayType()) {
2775 Sel = Sema::AbstractArrayType;
2776 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00002777 }
John McCall94c3b562010-08-18 09:41:07 +00002778 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
2779 if (CT != Info.AbstractType) return;
2780
2781 // It matched; do some magic.
2782 if (Sel == Sema::AbstractArrayType) {
2783 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
2784 << T << TL.getSourceRange();
2785 } else {
2786 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
2787 << Sel << T << TL.getSourceRange();
2788 }
2789 Info.DiagnoseAbstractType();
2790 }
2791};
2792
2793void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
2794 Sema::AbstractDiagSelID Sel) {
2795 CheckAbstractUsage(*this, D).Visit(TL, Sel);
2796}
2797
2798}
2799
2800/// Check for invalid uses of an abstract type in a method declaration.
2801static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2802 CXXMethodDecl *MD) {
2803 // No need to do the check on definitions, which require that
2804 // the return/param types be complete.
2805 if (MD->isThisDeclarationADefinition())
2806 return;
2807
2808 // For safety's sake, just ignore it if we don't have type source
2809 // information. This should never happen for non-implicit methods,
2810 // but...
2811 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
2812 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
2813}
2814
2815/// Check for invalid uses of an abstract type within a class definition.
2816static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2817 CXXRecordDecl *RD) {
2818 for (CXXRecordDecl::decl_iterator
2819 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
2820 Decl *D = *I;
2821 if (D->isImplicit()) continue;
2822
2823 // Methods and method templates.
2824 if (isa<CXXMethodDecl>(D)) {
2825 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
2826 } else if (isa<FunctionTemplateDecl>(D)) {
2827 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
2828 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
2829
2830 // Fields and static variables.
2831 } else if (isa<FieldDecl>(D)) {
2832 FieldDecl *FD = cast<FieldDecl>(D);
2833 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
2834 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
2835 } else if (isa<VarDecl>(D)) {
2836 VarDecl *VD = cast<VarDecl>(D);
2837 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
2838 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
2839
2840 // Nested classes and class templates.
2841 } else if (isa<CXXRecordDecl>(D)) {
2842 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
2843 } else if (isa<ClassTemplateDecl>(D)) {
2844 CheckAbstractClassUsage(Info,
2845 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
2846 }
2847 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00002848}
2849
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002850/// \brief Perform semantic checks on a class definition that has been
2851/// completing, introducing implicitly-declared members, checking for
2852/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00002853void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00002854 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002855 return;
2856
John McCall94c3b562010-08-18 09:41:07 +00002857 if (Record->isAbstract() && !Record->isInvalidDecl()) {
2858 AbstractUsageInfo Info(*this, Record);
2859 CheckAbstractClassUsage(Info, Record);
2860 }
Douglas Gregor325e5932010-04-15 00:00:53 +00002861
2862 // If this is not an aggregate type and has no user-declared constructor,
2863 // complain about any non-static data members of reference or const scalar
2864 // type, since they will never get initializers.
2865 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
2866 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
2867 bool Complained = false;
2868 for (RecordDecl::field_iterator F = Record->field_begin(),
2869 FEnd = Record->field_end();
2870 F != FEnd; ++F) {
2871 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00002872 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00002873 if (!Complained) {
2874 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
2875 << Record->getTagKind() << Record;
2876 Complained = true;
2877 }
2878
2879 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
2880 << F->getType()->isReferenceType()
2881 << F->getDeclName();
2882 }
2883 }
2884 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002885
Anders Carlssona5c6c2a2011-01-25 18:08:22 +00002886 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002887 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00002888
2889 if (Record->getIdentifier()) {
2890 // C++ [class.mem]p13:
2891 // If T is the name of a class, then each of the following shall have a
2892 // name different from T:
2893 // - every member of every anonymous union that is a member of class T.
2894 //
2895 // C++ [class.mem]p14:
2896 // In addition, if class T has a user-declared constructor (12.1), every
2897 // non-static data member of class T shall have a name different from T.
2898 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
Francois Pichet87c2e122010-11-21 06:08:52 +00002899 R.first != R.second; ++R.first) {
2900 NamedDecl *D = *R.first;
2901 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
2902 isa<IndirectFieldDecl>(D)) {
2903 Diag(D->getLocation(), diag::err_member_name_of_class)
2904 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00002905 break;
2906 }
Francois Pichet87c2e122010-11-21 06:08:52 +00002907 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00002908 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00002909
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00002910 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregorf4b793c2011-02-19 19:14:36 +00002911 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00002912 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00002913 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00002914 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
2915 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
2916 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00002917
2918 // See if a method overloads virtual methods in a base
2919 /// class without overriding any.
2920 if (!Record->isDependentType()) {
2921 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
2922 MEnd = Record->method_end();
2923 M != MEnd; ++M) {
Argyrios Kyrtzidis0266aa32011-03-03 22:58:57 +00002924 if (!(*M)->isStatic())
2925 DiagnoseHiddenVirtualMethods(Record, *M);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00002926 }
2927 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00002928
2929 // Declare inherited constructors. We do this eagerly here because:
2930 // - The standard requires an eager diagnostic for conflicting inherited
2931 // constructors from different classes.
2932 // - The lazy declaration of the other implicit constructors is so as to not
2933 // waste space and performance on classes that are not meant to be
2934 // instantiated (e.g. meta-functions). This doesn't apply to classes that
2935 // have inherited constructors.
Sebastian Redlcaa35e42011-03-12 13:44:32 +00002936 DeclareInheritedConstructors(Record);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00002937}
2938
2939/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramerc54061a2011-03-04 13:12:48 +00002940namespace {
2941 struct FindHiddenVirtualMethodData {
2942 Sema *S;
2943 CXXMethodDecl *Method;
2944 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
2945 llvm::SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
2946 };
2947}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00002948
2949/// \brief Member lookup function that determines whether a given C++
2950/// method overloads virtual methods in a base class without overriding any,
2951/// to be used with CXXRecordDecl::lookupInBases().
2952static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
2953 CXXBasePath &Path,
2954 void *UserData) {
2955 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
2956
2957 FindHiddenVirtualMethodData &Data
2958 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
2959
2960 DeclarationName Name = Data.Method->getDeclName();
2961 assert(Name.getNameKind() == DeclarationName::Identifier);
2962
2963 bool foundSameNameMethod = false;
2964 llvm::SmallVector<CXXMethodDecl *, 8> overloadedMethods;
2965 for (Path.Decls = BaseRecord->lookup(Name);
2966 Path.Decls.first != Path.Decls.second;
2967 ++Path.Decls.first) {
2968 NamedDecl *D = *Path.Decls.first;
2969 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00002970 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00002971 foundSameNameMethod = true;
2972 // Interested only in hidden virtual methods.
2973 if (!MD->isVirtual())
2974 continue;
2975 // If the method we are checking overrides a method from its base
2976 // don't warn about the other overloaded methods.
2977 if (!Data.S->IsOverload(Data.Method, MD, false))
2978 return true;
2979 // Collect the overload only if its hidden.
2980 if (!Data.OverridenAndUsingBaseMethods.count(MD))
2981 overloadedMethods.push_back(MD);
2982 }
2983 }
2984
2985 if (foundSameNameMethod)
2986 Data.OverloadedMethods.append(overloadedMethods.begin(),
2987 overloadedMethods.end());
2988 return foundSameNameMethod;
2989}
2990
2991/// \brief See if a method overloads virtual methods in a base class without
2992/// overriding any.
2993void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
2994 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
2995 MD->getLocation()) == Diagnostic::Ignored)
2996 return;
2997 if (MD->getDeclName().getNameKind() != DeclarationName::Identifier)
2998 return;
2999
3000 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
3001 /*bool RecordPaths=*/false,
3002 /*bool DetectVirtual=*/false);
3003 FindHiddenVirtualMethodData Data;
3004 Data.Method = MD;
3005 Data.S = this;
3006
3007 // Keep the base methods that were overriden or introduced in the subclass
3008 // by 'using' in a set. A base method not in this set is hidden.
3009 for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
3010 res.first != res.second; ++res.first) {
3011 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first))
3012 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
3013 E = MD->end_overridden_methods();
3014 I != E; ++I)
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00003015 Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003016 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
3017 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl()))
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00003018 Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003019 }
3020
3021 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
3022 !Data.OverloadedMethods.empty()) {
3023 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
3024 << MD << (Data.OverloadedMethods.size() > 1);
3025
3026 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
3027 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
3028 Diag(overloadedMD->getLocation(),
3029 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
3030 }
3031 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003032}
3033
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00003034void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00003035 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00003036 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00003037 SourceLocation RBrac,
3038 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00003039 if (!TagDecl)
3040 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003041
Douglas Gregor42af25f2009-05-11 19:58:34 +00003042 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003043
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00003044 ActOnFields(S, RLoc, TagDecl,
John McCalld226f652010-08-21 09:40:31 +00003045 // strict aliasing violation!
3046 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00003047 FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00003048
Douglas Gregor23c94db2010-07-02 17:43:08 +00003049 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00003050 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00003051}
3052
Douglas Gregord92ec472010-07-01 05:10:53 +00003053namespace {
3054 /// \brief Helper class that collects exception specifications for
3055 /// implicitly-declared special member functions.
3056 class ImplicitExceptionSpecification {
3057 ASTContext &Context;
Sebastian Redl60618fa2011-03-12 11:50:43 +00003058 // We order exception specifications thus:
3059 // noexcept is the most restrictive, but is only used in C++0x.
3060 // throw() comes next.
3061 // Then a throw(collected exceptions)
3062 // Finally no specification.
3063 // throw(...) is used instead if any called function uses it.
3064 ExceptionSpecificationType ComputedEST;
Douglas Gregord92ec472010-07-01 05:10:53 +00003065 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
3066 llvm::SmallVector<QualType, 4> Exceptions;
Sebastian Redl60618fa2011-03-12 11:50:43 +00003067
3068 void ClearExceptions() {
3069 ExceptionsSeen.clear();
3070 Exceptions.clear();
3071 }
3072
Douglas Gregord92ec472010-07-01 05:10:53 +00003073 public:
3074 explicit ImplicitExceptionSpecification(ASTContext &Context)
Sebastian Redl60618fa2011-03-12 11:50:43 +00003075 : Context(Context), ComputedEST(EST_BasicNoexcept) {
3076 if (!Context.getLangOptions().CPlusPlus0x)
3077 ComputedEST = EST_DynamicNone;
Douglas Gregord92ec472010-07-01 05:10:53 +00003078 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00003079
3080 /// \brief Get the computed exception specification type.
3081 ExceptionSpecificationType getExceptionSpecType() const {
3082 assert(ComputedEST != EST_ComputedNoexcept &&
3083 "noexcept(expr) should not be a possible result");
3084 return ComputedEST;
Douglas Gregord92ec472010-07-01 05:10:53 +00003085 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00003086
Douglas Gregord92ec472010-07-01 05:10:53 +00003087 /// \brief The number of exceptions in the exception specification.
3088 unsigned size() const { return Exceptions.size(); }
Sebastian Redl60618fa2011-03-12 11:50:43 +00003089
Douglas Gregord92ec472010-07-01 05:10:53 +00003090 /// \brief The set of exceptions in the exception specification.
3091 const QualType *data() const { return Exceptions.data(); }
Sebastian Redl60618fa2011-03-12 11:50:43 +00003092
3093 /// \brief Integrate another called method into the collected data.
Douglas Gregord92ec472010-07-01 05:10:53 +00003094 void CalledDecl(CXXMethodDecl *Method) {
Sebastian Redl60618fa2011-03-12 11:50:43 +00003095 // If we have an MSAny spec already, don't bother.
3096 if (!Method || ComputedEST == EST_MSAny)
Douglas Gregord92ec472010-07-01 05:10:53 +00003097 return;
Sebastian Redl60618fa2011-03-12 11:50:43 +00003098
Douglas Gregord92ec472010-07-01 05:10:53 +00003099 const FunctionProtoType *Proto
3100 = Method->getType()->getAs<FunctionProtoType>();
Sebastian Redl60618fa2011-03-12 11:50:43 +00003101
3102 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
3103
Douglas Gregord92ec472010-07-01 05:10:53 +00003104 // If this function can throw any exceptions, make a note of that.
Sebastian Redl60618fa2011-03-12 11:50:43 +00003105 if (EST == EST_MSAny || EST == EST_None) {
3106 ClearExceptions();
3107 ComputedEST = EST;
Douglas Gregord92ec472010-07-01 05:10:53 +00003108 return;
3109 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00003110
3111 // If this function has a basic noexcept, it doesn't affect the outcome.
3112 if (EST == EST_BasicNoexcept)
3113 return;
3114
3115 // If we have a throw-all spec at this point, ignore the function.
3116 if (ComputedEST == EST_None)
3117 return;
3118
3119 // If we're still at noexcept(true) and there's a nothrow() callee,
3120 // change to that specification.
3121 if (EST == EST_DynamicNone) {
3122 if (ComputedEST == EST_BasicNoexcept)
3123 ComputedEST = EST_DynamicNone;
3124 return;
3125 }
3126
3127 // Check out noexcept specs.
3128 if (EST == EST_ComputedNoexcept) {
Sebastian Redl8026f6d2011-03-13 17:09:40 +00003129 FunctionProtoType::NoexceptResult NR = Proto->getNoexceptSpec(Context);
Sebastian Redl60618fa2011-03-12 11:50:43 +00003130 assert(NR != FunctionProtoType::NR_NoNoexcept &&
3131 "Must have noexcept result for EST_ComputedNoexcept.");
3132 assert(NR != FunctionProtoType::NR_Dependent &&
3133 "Should not generate implicit declarations for dependent cases, "
3134 "and don't know how to handle them anyway.");
3135
3136 // noexcept(false) -> no spec on the new function
3137 if (NR == FunctionProtoType::NR_Throw) {
3138 ClearExceptions();
3139 ComputedEST = EST_None;
3140 }
3141 // noexcept(true) won't change anything either.
3142 return;
3143 }
3144
3145 assert(EST == EST_Dynamic && "EST case not considered earlier.");
3146 assert(ComputedEST != EST_None &&
3147 "Shouldn't collect exceptions when throw-all is guaranteed.");
3148 ComputedEST = EST_Dynamic;
Douglas Gregord92ec472010-07-01 05:10:53 +00003149 // Record the exceptions in this function's exception specification.
3150 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
3151 EEnd = Proto->exception_end();
Sebastian Redl60618fa2011-03-12 11:50:43 +00003152 E != EEnd; ++E)
Douglas Gregord92ec472010-07-01 05:10:53 +00003153 if (ExceptionsSeen.insert(Context.getCanonicalType(*E)))
3154 Exceptions.push_back(*E);
3155 }
3156 };
3157}
3158
3159
Douglas Gregor396b7cd2008-11-03 17:51:48 +00003160/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
3161/// special functions, such as the default constructor, copy
3162/// constructor, or destructor, to the given C++ class (C++
3163/// [special]p1). This routine can only be executed just before the
3164/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00003165void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00003166 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00003167 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00003168
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00003169 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregor22584312010-07-02 23:41:54 +00003170 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00003171
Douglas Gregora376d102010-07-02 21:50:04 +00003172 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
3173 ++ASTContext::NumImplicitCopyAssignmentOperators;
3174
3175 // If we have a dynamic class, then the copy assignment operator may be
3176 // virtual, so we have to declare it immediately. This ensures that, e.g.,
3177 // it shows up in the right place in the vtable and that we diagnose
3178 // problems with the implicit exception specification.
3179 if (ClassDecl->isDynamicClass())
3180 DeclareImplicitCopyAssignment(ClassDecl);
3181 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00003182
Douglas Gregor4923aa22010-07-02 20:37:36 +00003183 if (!ClassDecl->hasUserDeclaredDestructor()) {
3184 ++ASTContext::NumImplicitDestructors;
3185
3186 // If we have a dynamic class, then the destructor may be virtual, so we
3187 // have to declare the destructor immediately. This ensures that, e.g., it
3188 // shows up in the right place in the vtable and that we diagnose problems
3189 // with the implicit exception specification.
3190 if (ClassDecl->isDynamicClass())
3191 DeclareImplicitDestructor(ClassDecl);
3192 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00003193}
3194
Francois Pichet8387e2a2011-04-22 22:18:13 +00003195void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
3196 if (!D)
3197 return;
3198
3199 int NumParamList = D->getNumTemplateParameterLists();
3200 for (int i = 0; i < NumParamList; i++) {
3201 TemplateParameterList* Params = D->getTemplateParameterList(i);
3202 for (TemplateParameterList::iterator Param = Params->begin(),
3203 ParamEnd = Params->end();
3204 Param != ParamEnd; ++Param) {
3205 NamedDecl *Named = cast<NamedDecl>(*Param);
3206 if (Named->getDeclName()) {
3207 S->AddDecl(Named);
3208 IdResolver.AddDecl(Named);
3209 }
3210 }
3211 }
3212}
3213
John McCalld226f652010-08-21 09:40:31 +00003214void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00003215 if (!D)
3216 return;
3217
3218 TemplateParameterList *Params = 0;
3219 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
3220 Params = Template->getTemplateParameters();
3221 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
3222 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
3223 Params = PartialSpec->getTemplateParameters();
3224 else
Douglas Gregor6569d682009-05-27 23:11:45 +00003225 return;
3226
Douglas Gregor6569d682009-05-27 23:11:45 +00003227 for (TemplateParameterList::iterator Param = Params->begin(),
3228 ParamEnd = Params->end();
3229 Param != ParamEnd; ++Param) {
3230 NamedDecl *Named = cast<NamedDecl>(*Param);
3231 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00003232 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00003233 IdResolver.AddDecl(Named);
3234 }
3235 }
3236}
3237
John McCalld226f652010-08-21 09:40:31 +00003238void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00003239 if (!RecordD) return;
3240 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00003241 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00003242 PushDeclContext(S, Record);
3243}
3244
John McCalld226f652010-08-21 09:40:31 +00003245void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00003246 if (!RecordD) return;
3247 PopDeclContext();
3248}
3249
Douglas Gregor72b505b2008-12-16 21:30:33 +00003250/// ActOnStartDelayedCXXMethodDeclaration - We have completed
3251/// parsing a top-level (non-nested) C++ class, and we are now
3252/// parsing those parts of the given Method declaration that could
3253/// not be parsed earlier (C++ [class.mem]p2), such as default
3254/// arguments. This action should enter the scope of the given
3255/// Method declaration as if we had just parsed the qualified method
3256/// name. However, it should not bring the parameters into scope;
3257/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00003258void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00003259}
3260
3261/// ActOnDelayedCXXMethodParameter - We've already started a delayed
3262/// C++ method declaration. We're (re-)introducing the given
3263/// function parameter into scope for use in parsing later parts of
3264/// the method declaration. For example, we could see an
3265/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00003266void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00003267 if (!ParamD)
3268 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003269
John McCalld226f652010-08-21 09:40:31 +00003270 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00003271
3272 // If this parameter has an unparsed default argument, clear it out
3273 // to make way for the parsed default argument.
3274 if (Param->hasUnparsedDefaultArg())
3275 Param->setDefaultArg(0);
3276
John McCalld226f652010-08-21 09:40:31 +00003277 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00003278 if (Param->getDeclName())
3279 IdResolver.AddDecl(Param);
3280}
3281
3282/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
3283/// processing the delayed method declaration for Method. The method
3284/// declaration is now considered finished. There may be a separate
3285/// ActOnStartOfFunctionDef action later (not necessarily
3286/// immediately!) for this method, if it was also defined inside the
3287/// class body.
John McCalld226f652010-08-21 09:40:31 +00003288void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00003289 if (!MethodD)
3290 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003291
Douglas Gregorefd5bda2009-08-24 11:57:43 +00003292 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00003293
John McCalld226f652010-08-21 09:40:31 +00003294 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00003295
3296 // Now that we have our default arguments, check the constructor
3297 // again. It could produce additional diagnostics or affect whether
3298 // the class has implicitly-declared destructors, among other
3299 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00003300 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
3301 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00003302
3303 // Check the default arguments, which we may have added.
3304 if (!Method->isInvalidDecl())
3305 CheckCXXDefaultArguments(Method);
3306}
3307
Douglas Gregor42a552f2008-11-05 20:51:48 +00003308/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00003309/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00003310/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00003311/// emit diagnostics and set the invalid bit to true. In any case, the type
3312/// will be updated to reflect a well-formed type for the constructor and
3313/// returned.
3314QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00003315 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00003316 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00003317
3318 // C++ [class.ctor]p3:
3319 // A constructor shall not be virtual (10.3) or static (9.4). A
3320 // constructor can be invoked for a const, volatile or const
3321 // volatile object. A constructor shall not be declared const,
3322 // volatile, or const volatile (9.3.2).
3323 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00003324 if (!D.isInvalidType())
3325 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
3326 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
3327 << SourceRange(D.getIdentifierLoc());
3328 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00003329 }
John McCalld931b082010-08-26 03:08:43 +00003330 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00003331 if (!D.isInvalidType())
3332 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
3333 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
3334 << SourceRange(D.getIdentifierLoc());
3335 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00003336 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00003337 }
Mike Stump1eb44332009-09-09 15:08:12 +00003338
Abramo Bagnara075f8f12010-12-10 16:29:40 +00003339 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00003340 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00003341 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003342 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
3343 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00003344 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003345 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
3346 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00003347 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003348 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
3349 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00003350 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00003351 }
Mike Stump1eb44332009-09-09 15:08:12 +00003352
Douglas Gregorc938c162011-01-26 05:01:58 +00003353 // C++0x [class.ctor]p4:
3354 // A constructor shall not be declared with a ref-qualifier.
3355 if (FTI.hasRefQualifier()) {
3356 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
3357 << FTI.RefQualifierIsLValueRef
3358 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
3359 D.setInvalidType();
3360 }
3361
Douglas Gregor42a552f2008-11-05 20:51:48 +00003362 // Rebuild the function type "R" without any type qualifiers (in
3363 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00003364 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00003365 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00003366 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
3367 return R;
3368
3369 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3370 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00003371 EPI.RefQualifier = RQ_None;
3372
Chris Lattner65401802009-04-25 08:28:21 +00003373 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00003374 Proto->getNumArgs(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00003375}
3376
Douglas Gregor72b505b2008-12-16 21:30:33 +00003377/// CheckConstructor - Checks a fully-formed constructor for
3378/// well-formedness, issuing any diagnostics required. Returns true if
3379/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00003380void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00003381 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00003382 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
3383 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00003384 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00003385
3386 // C++ [class.copy]p3:
3387 // A declaration of a constructor for a class X is ill-formed if
3388 // its first parameter is of type (optionally cv-qualified) X and
3389 // either there are no other parameters or else all other
3390 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00003391 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00003392 ((Constructor->getNumParams() == 1) ||
3393 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00003394 Constructor->getParamDecl(1)->hasDefaultArg())) &&
3395 Constructor->getTemplateSpecializationKind()
3396 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00003397 QualType ParamType = Constructor->getParamDecl(0)->getType();
3398 QualType ClassTy = Context.getTagDeclType(ClassDecl);
3399 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00003400 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00003401 const char *ConstRef
3402 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
3403 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00003404 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00003405 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00003406
3407 // FIXME: Rather that making the constructor invalid, we should endeavor
3408 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00003409 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00003410 }
3411 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00003412}
3413
John McCall15442822010-08-04 01:04:25 +00003414/// CheckDestructor - Checks a fully-formed destructor definition for
3415/// well-formedness, issuing any diagnostics required. Returns true
3416/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00003417bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00003418 CXXRecordDecl *RD = Destructor->getParent();
3419
3420 if (Destructor->isVirtual()) {
3421 SourceLocation Loc;
3422
3423 if (!Destructor->isImplicit())
3424 Loc = Destructor->getLocation();
3425 else
3426 Loc = RD->getLocation();
3427
3428 // If we have a virtual destructor, look up the deallocation function
3429 FunctionDecl *OperatorDelete = 0;
3430 DeclarationName Name =
3431 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00003432 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00003433 return true;
John McCall5efd91a2010-07-03 18:33:00 +00003434
3435 MarkDeclarationReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00003436
3437 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00003438 }
Anders Carlsson37909802009-11-30 21:24:50 +00003439
3440 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00003441}
3442
Mike Stump1eb44332009-09-09 15:08:12 +00003443static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00003444FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
3445 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
3446 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00003447 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00003448}
3449
Douglas Gregor42a552f2008-11-05 20:51:48 +00003450/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
3451/// the well-formednes of the destructor declarator @p D with type @p
3452/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00003453/// emit diagnostics and set the declarator to invalid. Even if this happens,
3454/// will be updated to reflect a well-formed type for the destructor and
3455/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00003456QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00003457 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00003458 // C++ [class.dtor]p1:
3459 // [...] A typedef-name that names a class is a class-name
3460 // (7.1.3); however, a typedef-name that names a class shall not
3461 // be used as the identifier in the declarator for a destructor
3462 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00003463 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smith162e1c12011-04-15 14:24:37 +00003464 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner65401802009-04-25 08:28:21 +00003465 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smith162e1c12011-04-15 14:24:37 +00003466 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00003467 else if (const TemplateSpecializationType *TST =
3468 DeclaratorType->getAs<TemplateSpecializationType>())
3469 if (TST->isTypeAlias())
3470 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
3471 << DeclaratorType << 1;
Douglas Gregor42a552f2008-11-05 20:51:48 +00003472
3473 // C++ [class.dtor]p2:
3474 // A destructor is used to destroy objects of its class type. A
3475 // destructor takes no parameters, and no return type can be
3476 // specified for it (not even void). The address of a destructor
3477 // shall not be taken. A destructor shall not be static. A
3478 // destructor can be invoked for a const, volatile or const
3479 // volatile object. A destructor shall not be declared const,
3480 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00003481 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00003482 if (!D.isInvalidType())
3483 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
3484 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00003485 << SourceRange(D.getIdentifierLoc())
3486 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
3487
John McCalld931b082010-08-26 03:08:43 +00003488 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00003489 }
Chris Lattner65401802009-04-25 08:28:21 +00003490 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00003491 // Destructors don't have return types, but the parser will
3492 // happily parse something like:
3493 //
3494 // class X {
3495 // float ~X();
3496 // };
3497 //
3498 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003499 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
3500 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3501 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00003502 }
Mike Stump1eb44332009-09-09 15:08:12 +00003503
Abramo Bagnara075f8f12010-12-10 16:29:40 +00003504 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00003505 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00003506 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003507 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3508 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00003509 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003510 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3511 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00003512 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003513 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3514 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00003515 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00003516 }
3517
Douglas Gregorc938c162011-01-26 05:01:58 +00003518 // C++0x [class.dtor]p2:
3519 // A destructor shall not be declared with a ref-qualifier.
3520 if (FTI.hasRefQualifier()) {
3521 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
3522 << FTI.RefQualifierIsLValueRef
3523 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
3524 D.setInvalidType();
3525 }
3526
Douglas Gregor42a552f2008-11-05 20:51:48 +00003527 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00003528 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00003529 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
3530
3531 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00003532 FTI.freeArgs();
3533 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00003534 }
3535
Mike Stump1eb44332009-09-09 15:08:12 +00003536 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00003537 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00003538 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00003539 D.setInvalidType();
3540 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00003541
3542 // Rebuild the function type "R" without any type qualifiers or
3543 // parameters (in case any of the errors above fired) and with
3544 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00003545 // types.
John McCalle23cf432010-12-14 08:05:40 +00003546 if (!D.isInvalidType())
3547 return R;
3548
Douglas Gregord92ec472010-07-01 05:10:53 +00003549 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00003550 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3551 EPI.Variadic = false;
3552 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00003553 EPI.RefQualifier = RQ_None;
John McCalle23cf432010-12-14 08:05:40 +00003554 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00003555}
3556
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003557/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
3558/// well-formednes of the conversion function declarator @p D with
3559/// type @p R. If there are any errors in the declarator, this routine
3560/// will emit diagnostics and return true. Otherwise, it will return
3561/// false. Either way, the type @p R will be updated to reflect a
3562/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00003563void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00003564 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003565 // C++ [class.conv.fct]p1:
3566 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00003567 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00003568 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00003569 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00003570 if (!D.isInvalidType())
3571 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
3572 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
3573 << SourceRange(D.getIdentifierLoc());
3574 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00003575 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003576 }
John McCalla3f81372010-04-13 00:04:31 +00003577
3578 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
3579
Chris Lattner6e475012009-04-25 08:35:12 +00003580 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003581 // Conversion functions don't have return types, but the parser will
3582 // happily parse something like:
3583 //
3584 // class X {
3585 // float operator bool();
3586 // };
3587 //
3588 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003589 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
3590 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3591 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00003592 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003593 }
3594
John McCalla3f81372010-04-13 00:04:31 +00003595 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
3596
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003597 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00003598 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003599 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
3600
3601 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00003602 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00003603 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00003604 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003605 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00003606 D.setInvalidType();
3607 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003608
John McCalla3f81372010-04-13 00:04:31 +00003609 // Diagnose "&operator bool()" and other such nonsense. This
3610 // is actually a gcc extension which we don't support.
3611 if (Proto->getResultType() != ConvType) {
3612 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
3613 << Proto->getResultType();
3614 D.setInvalidType();
3615 ConvType = Proto->getResultType();
3616 }
3617
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003618 // C++ [class.conv.fct]p4:
3619 // The conversion-type-id shall not represent a function type nor
3620 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003621 if (ConvType->isArrayType()) {
3622 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
3623 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00003624 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003625 } else if (ConvType->isFunctionType()) {
3626 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
3627 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00003628 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003629 }
3630
3631 // Rebuild the function type "R" without any parameters (in case any
3632 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00003633 // return type.
John McCalle23cf432010-12-14 08:05:40 +00003634 if (D.isInvalidType())
3635 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003636
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003637 // C++0x explicit conversion operators.
3638 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump1eb44332009-09-09 15:08:12 +00003639 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003640 diag::warn_explicit_conversion_functions)
3641 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003642}
3643
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003644/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
3645/// the declaration of the given C++ conversion function. This routine
3646/// is responsible for recording the conversion function in the C++
3647/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00003648Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003649 assert(Conversion && "Expected to receive a conversion function declaration");
3650
Douglas Gregor9d350972008-12-12 08:25:50 +00003651 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003652
3653 // Make sure we aren't redeclaring the conversion function.
3654 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003655
3656 // C++ [class.conv.fct]p1:
3657 // [...] A conversion function is never used to convert a
3658 // (possibly cv-qualified) object to the (possibly cv-qualified)
3659 // same object type (or a reference to it), to a (possibly
3660 // cv-qualified) base class of that type (or a reference to it),
3661 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00003662 // FIXME: Suppress this warning if the conversion function ends up being a
3663 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00003664 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003665 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00003666 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003667 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00003668 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
3669 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00003670 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00003671 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003672 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
3673 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00003674 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00003675 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003676 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00003677 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00003678 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003679 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00003680 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00003681 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003682 }
3683
Douglas Gregore80622f2010-09-29 04:25:11 +00003684 if (FunctionTemplateDecl *ConversionTemplate
3685 = Conversion->getDescribedFunctionTemplate())
3686 return ConversionTemplate;
3687
John McCalld226f652010-08-21 09:40:31 +00003688 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003689}
3690
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003691//===----------------------------------------------------------------------===//
3692// Namespace Handling
3693//===----------------------------------------------------------------------===//
3694
John McCallea318642010-08-26 09:15:37 +00003695
3696
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003697/// ActOnStartNamespaceDef - This is called at the start of a namespace
3698/// definition.
John McCalld226f652010-08-21 09:40:31 +00003699Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00003700 SourceLocation InlineLoc,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00003701 SourceLocation NamespaceLoc,
John McCallea318642010-08-26 09:15:37 +00003702 SourceLocation IdentLoc,
3703 IdentifierInfo *II,
3704 SourceLocation LBrace,
3705 AttributeList *AttrList) {
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00003706 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
3707 // For anonymous namespace, take the location of the left brace.
3708 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregor21e09b62010-08-19 20:55:47 +00003709 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00003710 StartLoc, Loc, II);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00003711 Namespc->setInline(InlineLoc.isValid());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003712
3713 Scope *DeclRegionScope = NamespcScope->getParent();
3714
Anders Carlsson2a3503d2010-02-07 01:09:23 +00003715 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
3716
John McCall90f14502010-12-10 02:59:44 +00003717 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
3718 PushNamespaceVisibilityAttr(Attr);
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00003719
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003720 if (II) {
3721 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00003722 // The identifier in an original-namespace-definition shall not
3723 // have been previously defined in the declarative region in
3724 // which the original-namespace-definition appears. The
3725 // identifier in an original-namespace-definition is the name of
3726 // the namespace. Subsequently in that declarative region, it is
3727 // treated as an original-namespace-name.
3728 //
3729 // Since namespace names are unique in their scope, and we don't
3730 // look through using directives, just
3731 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
3732 NamedDecl *PrevDecl = R.first == R.second? 0 : *R.first;
Mike Stump1eb44332009-09-09 15:08:12 +00003733
Douglas Gregor44b43212008-12-11 16:49:14 +00003734 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
3735 // This is an extended namespace definition.
Sebastian Redl4e4d5702010-08-31 00:36:36 +00003736 if (Namespc->isInline() != OrigNS->isInline()) {
3737 // inline-ness must match
3738 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
3739 << Namespc->isInline();
3740 Diag(OrigNS->getLocation(), diag::note_previous_definition);
3741 Namespc->setInvalidDecl();
3742 // Recover by ignoring the new namespace's inline status.
3743 Namespc->setInline(OrigNS->isInline());
3744 }
3745
Douglas Gregor44b43212008-12-11 16:49:14 +00003746 // Attach this namespace decl to the chain of extended namespace
3747 // definitions.
3748 OrigNS->setNextNamespace(Namespc);
3749 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003750
Mike Stump1eb44332009-09-09 15:08:12 +00003751 // Remove the previous declaration from the scope.
John McCalld226f652010-08-21 09:40:31 +00003752 if (DeclRegionScope->isDeclScope(OrigNS)) {
Douglas Gregore267ff32008-12-11 20:41:00 +00003753 IdResolver.RemoveDecl(OrigNS);
John McCalld226f652010-08-21 09:40:31 +00003754 DeclRegionScope->RemoveDecl(OrigNS);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003755 }
Douglas Gregor44b43212008-12-11 16:49:14 +00003756 } else if (PrevDecl) {
3757 // This is an invalid name redefinition.
3758 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
3759 << Namespc->getDeclName();
3760 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3761 Namespc->setInvalidDecl();
3762 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor7adb10f2009-09-15 22:30:29 +00003763 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00003764 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00003765 // This is the first "real" definition of the namespace "std", so update
3766 // our cache of the "std" namespace to point at this definition.
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00003767 if (NamespaceDecl *StdNS = getStdNamespace()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00003768 // We had already defined a dummy namespace "std". Link this new
3769 // namespace definition to the dummy namespace "std".
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00003770 StdNS->setNextNamespace(Namespc);
3771 StdNS->setLocation(IdentLoc);
3772 Namespc->setOriginalNamespace(StdNS->getOriginalNamespace());
Douglas Gregor7adb10f2009-09-15 22:30:29 +00003773 }
3774
3775 // Make our StdNamespace cache point at the first real definition of the
3776 // "std" namespace.
3777 StdNamespace = Namespc;
Mike Stump1eb44332009-09-09 15:08:12 +00003778 }
Douglas Gregor44b43212008-12-11 16:49:14 +00003779
3780 PushOnScopeChains(Namespc, DeclRegionScope);
3781 } else {
John McCall9aeed322009-10-01 00:25:31 +00003782 // Anonymous namespaces.
John McCall5fdd7642009-12-16 02:06:49 +00003783 assert(Namespc->isAnonymousNamespace());
John McCall5fdd7642009-12-16 02:06:49 +00003784
3785 // Link the anonymous namespace into its parent.
3786 NamespaceDecl *PrevDecl;
Sebastian Redl7a126a42010-08-31 00:36:30 +00003787 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00003788 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
3789 PrevDecl = TU->getAnonymousNamespace();
3790 TU->setAnonymousNamespace(Namespc);
3791 } else {
3792 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
3793 PrevDecl = ND->getAnonymousNamespace();
3794 ND->setAnonymousNamespace(Namespc);
3795 }
3796
3797 // Link the anonymous namespace with its previous declaration.
3798 if (PrevDecl) {
3799 assert(PrevDecl->isAnonymousNamespace());
3800 assert(!PrevDecl->getNextNamespace());
3801 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
3802 PrevDecl->setNextNamespace(Namespc);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00003803
3804 if (Namespc->isInline() != PrevDecl->isInline()) {
3805 // inline-ness must match
3806 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
3807 << Namespc->isInline();
3808 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3809 Namespc->setInvalidDecl();
3810 // Recover by ignoring the new namespace's inline status.
3811 Namespc->setInline(PrevDecl->isInline());
3812 }
John McCall5fdd7642009-12-16 02:06:49 +00003813 }
John McCall9aeed322009-10-01 00:25:31 +00003814
Douglas Gregora4181472010-03-24 00:46:35 +00003815 CurContext->addDecl(Namespc);
3816
John McCall9aeed322009-10-01 00:25:31 +00003817 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
3818 // behaves as if it were replaced by
3819 // namespace unique { /* empty body */ }
3820 // using namespace unique;
3821 // namespace unique { namespace-body }
3822 // where all occurrences of 'unique' in a translation unit are
3823 // replaced by the same identifier and this identifier differs
3824 // from all other identifiers in the entire program.
3825
3826 // We just create the namespace with an empty name and then add an
3827 // implicit using declaration, just like the standard suggests.
3828 //
3829 // CodeGen enforces the "universally unique" aspect by giving all
3830 // declarations semantically contained within an anonymous
3831 // namespace internal linkage.
3832
John McCall5fdd7642009-12-16 02:06:49 +00003833 if (!PrevDecl) {
3834 UsingDirectiveDecl* UD
3835 = UsingDirectiveDecl::Create(Context, CurContext,
3836 /* 'using' */ LBrace,
3837 /* 'namespace' */ SourceLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00003838 /* qualifier */ NestedNameSpecifierLoc(),
John McCall5fdd7642009-12-16 02:06:49 +00003839 /* identifier */ SourceLocation(),
3840 Namespc,
3841 /* Ancestor */ CurContext);
3842 UD->setImplicit();
3843 CurContext->addDecl(UD);
3844 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003845 }
3846
3847 // Although we could have an invalid decl (i.e. the namespace name is a
3848 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00003849 // FIXME: We should be able to push Namespc here, so that the each DeclContext
3850 // for the namespace has the declarations that showed up in that particular
3851 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00003852 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00003853 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003854}
3855
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003856/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
3857/// is a namespace alias, returns the namespace it points to.
3858static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
3859 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
3860 return AD->getNamespace();
3861 return dyn_cast_or_null<NamespaceDecl>(D);
3862}
3863
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003864/// ActOnFinishNamespaceDef - This callback is called after a namespace is
3865/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00003866void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003867 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
3868 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00003869 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003870 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00003871 if (Namespc->hasAttr<VisibilityAttr>())
3872 PopPragmaVisibility();
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003873}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003874
John McCall384aff82010-08-25 07:42:41 +00003875CXXRecordDecl *Sema::getStdBadAlloc() const {
3876 return cast_or_null<CXXRecordDecl>(
3877 StdBadAlloc.get(Context.getExternalSource()));
3878}
3879
3880NamespaceDecl *Sema::getStdNamespace() const {
3881 return cast_or_null<NamespaceDecl>(
3882 StdNamespace.get(Context.getExternalSource()));
3883}
3884
Douglas Gregor66992202010-06-29 17:53:46 +00003885/// \brief Retrieve the special "std" namespace, which may require us to
3886/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00003887NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00003888 if (!StdNamespace) {
3889 // The "std" namespace has not yet been defined, so build one implicitly.
3890 StdNamespace = NamespaceDecl::Create(Context,
3891 Context.getTranslationUnitDecl(),
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00003892 SourceLocation(), SourceLocation(),
Douglas Gregor66992202010-06-29 17:53:46 +00003893 &PP.getIdentifierTable().get("std"));
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00003894 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00003895 }
3896
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00003897 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00003898}
3899
Douglas Gregor9172aa62011-03-26 22:25:30 +00003900/// \brief Determine whether a using statement is in a context where it will be
3901/// apply in all contexts.
3902static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
3903 switch (CurContext->getDeclKind()) {
3904 case Decl::TranslationUnit:
3905 return true;
3906 case Decl::LinkageSpec:
3907 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
3908 default:
3909 return false;
3910 }
3911}
3912
John McCalld226f652010-08-21 09:40:31 +00003913Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00003914 SourceLocation UsingLoc,
3915 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003916 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00003917 SourceLocation IdentLoc,
3918 IdentifierInfo *NamespcName,
3919 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00003920 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3921 assert(NamespcName && "Invalid NamespcName.");
3922 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00003923
3924 // This can only happen along a recovery path.
3925 while (S->getFlags() & Scope::TemplateParamScope)
3926 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003927 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00003928
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003929 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00003930 NestedNameSpecifier *Qualifier = 0;
3931 if (SS.isSet())
3932 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3933
Douglas Gregoreb11cd02009-01-14 22:20:51 +00003934 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00003935 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
3936 LookupParsedName(R, S, &SS);
3937 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00003938 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00003939
Douglas Gregor66992202010-06-29 17:53:46 +00003940 if (R.empty()) {
3941 // Allow "using namespace std;" or "using namespace ::std;" even if
3942 // "std" hasn't been defined yet, for GCC compatibility.
3943 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
3944 NamespcName->isStr("std")) {
3945 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00003946 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00003947 R.resolveKind();
3948 }
3949 // Otherwise, attempt typo correction.
3950 else if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
3951 CTC_NoKeywords, 0)) {
3952 if (R.getAsSingle<NamespaceDecl>() ||
3953 R.getAsSingle<NamespaceAliasDecl>()) {
3954 if (DeclContext *DC = computeDeclContext(SS, false))
3955 Diag(IdentLoc, diag::err_using_directive_member_suggest)
3956 << NamespcName << DC << Corrected << SS.getRange()
3957 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3958 else
3959 Diag(IdentLoc, diag::err_using_directive_suggest)
3960 << NamespcName << Corrected
3961 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3962 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
3963 << Corrected;
3964
3965 NamespcName = Corrected.getAsIdentifierInfo();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00003966 } else {
3967 R.clear();
3968 R.setLookupName(NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00003969 }
3970 }
3971 }
3972
John McCallf36e02d2009-10-09 21:13:30 +00003973 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003974 NamedDecl *Named = R.getFoundDecl();
3975 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
3976 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003977 // C++ [namespace.udir]p1:
3978 // A using-directive specifies that the names in the nominated
3979 // namespace can be used in the scope in which the
3980 // using-directive appears after the using-directive. During
3981 // unqualified name lookup (3.4.1), the names appear as if they
3982 // were declared in the nearest enclosing namespace which
3983 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00003984 // namespace. [Note: in this context, "contains" means "contains
3985 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003986
3987 // Find enclosing context containing both using-directive and
3988 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003989 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003990 DeclContext *CommonAncestor = cast<DeclContext>(NS);
3991 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
3992 CommonAncestor = CommonAncestor->getParent();
3993
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003994 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregordb992412011-02-25 16:33:46 +00003995 SS.getWithLocInContext(Context),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003996 IdentLoc, Named, CommonAncestor);
Douglas Gregord6a49bb2011-03-18 16:10:52 +00003997
Douglas Gregor9172aa62011-03-26 22:25:30 +00003998 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Nico Weber21669482011-04-02 19:45:15 +00003999 !SourceMgr.isFromMainFile(SourceMgr.getInstantiationLoc(IdentLoc))) {
Douglas Gregord6a49bb2011-03-18 16:10:52 +00004000 Diag(IdentLoc, diag::warn_using_directive_in_header);
4001 }
4002
Douglas Gregor2a3009a2009-02-03 19:21:40 +00004003 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00004004 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00004005 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00004006 }
4007
Douglas Gregor2a3009a2009-02-03 19:21:40 +00004008 // FIXME: We ignore attributes for now.
John McCalld226f652010-08-21 09:40:31 +00004009 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00004010}
4011
4012void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
4013 // If scope has associated entity, then using directive is at namespace
4014 // or translation unit scope. We add UsingDirectiveDecls, into
4015 // it's lookup structure.
4016 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004017 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00004018 else
4019 // Otherwise it is block-sope. using-directives will affect lookup
4020 // only to the end of scope.
John McCalld226f652010-08-21 09:40:31 +00004021 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00004022}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004023
Douglas Gregor9cfbe482009-06-20 00:51:54 +00004024
John McCalld226f652010-08-21 09:40:31 +00004025Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00004026 AccessSpecifier AS,
4027 bool HasUsingKeyword,
4028 SourceLocation UsingLoc,
4029 CXXScopeSpec &SS,
4030 UnqualifiedId &Name,
4031 AttributeList *AttrList,
4032 bool IsTypeName,
4033 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00004034 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00004035
Douglas Gregor12c118a2009-11-04 16:30:06 +00004036 switch (Name.getKind()) {
4037 case UnqualifiedId::IK_Identifier:
4038 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00004039 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00004040 case UnqualifiedId::IK_ConversionFunctionId:
4041 break;
4042
4043 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00004044 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall604e7f12009-12-08 07:46:18 +00004045 // C++0x inherited constructors.
4046 if (getLangOptions().CPlusPlus0x) break;
4047
Douglas Gregor12c118a2009-11-04 16:30:06 +00004048 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
4049 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00004050 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00004051
4052 case UnqualifiedId::IK_DestructorName:
4053 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
4054 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00004055 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00004056
4057 case UnqualifiedId::IK_TemplateId:
4058 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
4059 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00004060 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00004061 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00004062
4063 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
4064 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00004065 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00004066 return 0;
John McCall604e7f12009-12-08 07:46:18 +00004067
John McCall60fa3cf2009-12-11 02:10:03 +00004068 // Warn about using declarations.
4069 // TODO: store that the declaration was written without 'using' and
4070 // talk about access decls instead of using decls in the
4071 // diagnostics.
4072 if (!HasUsingKeyword) {
4073 UsingLoc = Name.getSourceRange().getBegin();
4074
4075 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00004076 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00004077 }
4078
Douglas Gregor56c04582010-12-16 00:46:58 +00004079 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
4080 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
4081 return 0;
4082
John McCall9488ea12009-11-17 05:59:44 +00004083 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00004084 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00004085 /* IsInstantiation */ false,
4086 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00004087 if (UD)
4088 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00004089
John McCalld226f652010-08-21 09:40:31 +00004090 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00004091}
4092
Douglas Gregor09acc982010-07-07 23:08:52 +00004093/// \brief Determine whether a using declaration considers the given
4094/// declarations as "equivalent", e.g., if they are redeclarations of
4095/// the same entity or are both typedefs of the same type.
4096static bool
4097IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
4098 bool &SuppressRedeclaration) {
4099 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
4100 SuppressRedeclaration = false;
4101 return true;
4102 }
4103
Richard Smith162e1c12011-04-15 14:24:37 +00004104 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
4105 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor09acc982010-07-07 23:08:52 +00004106 SuppressRedeclaration = true;
4107 return Context.hasSameType(TD1->getUnderlyingType(),
4108 TD2->getUnderlyingType());
4109 }
4110
4111 return false;
4112}
4113
4114
John McCall9f54ad42009-12-10 09:41:52 +00004115/// Determines whether to create a using shadow decl for a particular
4116/// decl, given the set of decls existing prior to this using lookup.
4117bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
4118 const LookupResult &Previous) {
4119 // Diagnose finding a decl which is not from a base class of the
4120 // current class. We do this now because there are cases where this
4121 // function will silently decide not to build a shadow decl, which
4122 // will pre-empt further diagnostics.
4123 //
4124 // We don't need to do this in C++0x because we do the check once on
4125 // the qualifier.
4126 //
4127 // FIXME: diagnose the following if we care enough:
4128 // struct A { int foo; };
4129 // struct B : A { using A::foo; };
4130 // template <class T> struct C : A {};
4131 // template <class T> struct D : C<T> { using B::foo; } // <---
4132 // This is invalid (during instantiation) in C++03 because B::foo
4133 // resolves to the using decl in B, which is not a base class of D<T>.
4134 // We can't diagnose it immediately because C<T> is an unknown
4135 // specialization. The UsingShadowDecl in D<T> then points directly
4136 // to A::foo, which will look well-formed when we instantiate.
4137 // The right solution is to not collapse the shadow-decl chain.
4138 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
4139 DeclContext *OrigDC = Orig->getDeclContext();
4140
4141 // Handle enums and anonymous structs.
4142 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
4143 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
4144 while (OrigRec->isAnonymousStructOrUnion())
4145 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
4146
4147 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
4148 if (OrigDC == CurContext) {
4149 Diag(Using->getLocation(),
4150 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregordc355712011-02-25 00:36:19 +00004151 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00004152 Diag(Orig->getLocation(), diag::note_using_decl_target);
4153 return true;
4154 }
4155
Douglas Gregordc355712011-02-25 00:36:19 +00004156 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall9f54ad42009-12-10 09:41:52 +00004157 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregordc355712011-02-25 00:36:19 +00004158 << Using->getQualifier()
John McCall9f54ad42009-12-10 09:41:52 +00004159 << cast<CXXRecordDecl>(CurContext)
Douglas Gregordc355712011-02-25 00:36:19 +00004160 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00004161 Diag(Orig->getLocation(), diag::note_using_decl_target);
4162 return true;
4163 }
4164 }
4165
4166 if (Previous.empty()) return false;
4167
4168 NamedDecl *Target = Orig;
4169 if (isa<UsingShadowDecl>(Target))
4170 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
4171
John McCalld7533ec2009-12-11 02:33:26 +00004172 // If the target happens to be one of the previous declarations, we
4173 // don't have a conflict.
4174 //
4175 // FIXME: but we might be increasing its access, in which case we
4176 // should redeclare it.
4177 NamedDecl *NonTag = 0, *Tag = 0;
4178 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4179 I != E; ++I) {
4180 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00004181 bool Result;
4182 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
4183 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00004184
4185 (isa<TagDecl>(D) ? Tag : NonTag) = D;
4186 }
4187
John McCall9f54ad42009-12-10 09:41:52 +00004188 if (Target->isFunctionOrFunctionTemplate()) {
4189 FunctionDecl *FD;
4190 if (isa<FunctionTemplateDecl>(Target))
4191 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
4192 else
4193 FD = cast<FunctionDecl>(Target);
4194
4195 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00004196 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00004197 case Ovl_Overload:
4198 return false;
4199
4200 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00004201 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00004202 break;
4203
4204 // We found a decl with the exact signature.
4205 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00004206 // If we're in a record, we want to hide the target, so we
4207 // return true (without a diagnostic) to tell the caller not to
4208 // build a shadow decl.
4209 if (CurContext->isRecord())
4210 return true;
4211
4212 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00004213 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00004214 break;
4215 }
4216
4217 Diag(Target->getLocation(), diag::note_using_decl_target);
4218 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
4219 return true;
4220 }
4221
4222 // Target is not a function.
4223
John McCall9f54ad42009-12-10 09:41:52 +00004224 if (isa<TagDecl>(Target)) {
4225 // No conflict between a tag and a non-tag.
4226 if (!Tag) return false;
4227
John McCall41ce66f2009-12-10 19:51:03 +00004228 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00004229 Diag(Target->getLocation(), diag::note_using_decl_target);
4230 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
4231 return true;
4232 }
4233
4234 // No conflict between a tag and a non-tag.
4235 if (!NonTag) return false;
4236
John McCall41ce66f2009-12-10 19:51:03 +00004237 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00004238 Diag(Target->getLocation(), diag::note_using_decl_target);
4239 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
4240 return true;
4241}
4242
John McCall9488ea12009-11-17 05:59:44 +00004243/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00004244UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00004245 UsingDecl *UD,
4246 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00004247
4248 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00004249 NamedDecl *Target = Orig;
4250 if (isa<UsingShadowDecl>(Target)) {
4251 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
4252 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00004253 }
4254
4255 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00004256 = UsingShadowDecl::Create(Context, CurContext,
4257 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00004258 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00004259
4260 Shadow->setAccess(UD->getAccess());
4261 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
4262 Shadow->setInvalidDecl();
4263
John McCall9488ea12009-11-17 05:59:44 +00004264 if (S)
John McCall604e7f12009-12-08 07:46:18 +00004265 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00004266 else
John McCall604e7f12009-12-08 07:46:18 +00004267 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00004268
John McCall604e7f12009-12-08 07:46:18 +00004269
John McCall9f54ad42009-12-10 09:41:52 +00004270 return Shadow;
4271}
John McCall604e7f12009-12-08 07:46:18 +00004272
John McCall9f54ad42009-12-10 09:41:52 +00004273/// Hides a using shadow declaration. This is required by the current
4274/// using-decl implementation when a resolvable using declaration in a
4275/// class is followed by a declaration which would hide or override
4276/// one or more of the using decl's targets; for example:
4277///
4278/// struct Base { void foo(int); };
4279/// struct Derived : Base {
4280/// using Base::foo;
4281/// void foo(int);
4282/// };
4283///
4284/// The governing language is C++03 [namespace.udecl]p12:
4285///
4286/// When a using-declaration brings names from a base class into a
4287/// derived class scope, member functions in the derived class
4288/// override and/or hide member functions with the same name and
4289/// parameter types in a base class (rather than conflicting).
4290///
4291/// There are two ways to implement this:
4292/// (1) optimistically create shadow decls when they're not hidden
4293/// by existing declarations, or
4294/// (2) don't create any shadow decls (or at least don't make them
4295/// visible) until we've fully parsed/instantiated the class.
4296/// The problem with (1) is that we might have to retroactively remove
4297/// a shadow decl, which requires several O(n) operations because the
4298/// decl structures are (very reasonably) not designed for removal.
4299/// (2) avoids this but is very fiddly and phase-dependent.
4300void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00004301 if (Shadow->getDeclName().getNameKind() ==
4302 DeclarationName::CXXConversionFunctionName)
4303 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
4304
John McCall9f54ad42009-12-10 09:41:52 +00004305 // Remove it from the DeclContext...
4306 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00004307
John McCall9f54ad42009-12-10 09:41:52 +00004308 // ...and the scope, if applicable...
4309 if (S) {
John McCalld226f652010-08-21 09:40:31 +00004310 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00004311 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00004312 }
4313
John McCall9f54ad42009-12-10 09:41:52 +00004314 // ...and the using decl.
4315 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
4316
4317 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00004318 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00004319}
4320
John McCall7ba107a2009-11-18 02:36:19 +00004321/// Builds a using declaration.
4322///
4323/// \param IsInstantiation - Whether this call arises from an
4324/// instantiation of an unresolved using declaration. We treat
4325/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00004326NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
4327 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00004328 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00004329 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00004330 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00004331 bool IsInstantiation,
4332 bool IsTypeName,
4333 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00004334 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00004335 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00004336 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00004337
Anders Carlsson550b14b2009-08-28 05:49:21 +00004338 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00004339
Anders Carlssoncf9f9212009-08-28 03:16:11 +00004340 if (SS.isEmpty()) {
4341 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00004342 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00004343 }
Mike Stump1eb44332009-09-09 15:08:12 +00004344
John McCall9f54ad42009-12-10 09:41:52 +00004345 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00004346 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00004347 ForRedeclaration);
4348 Previous.setHideTags(false);
4349 if (S) {
4350 LookupName(Previous, S);
4351
4352 // It is really dumb that we have to do this.
4353 LookupResult::Filter F = Previous.makeFilter();
4354 while (F.hasNext()) {
4355 NamedDecl *D = F.next();
4356 if (!isDeclInScope(D, CurContext, S))
4357 F.erase();
4358 }
4359 F.done();
4360 } else {
4361 assert(IsInstantiation && "no scope in non-instantiation");
4362 assert(CurContext->isRecord() && "scope not record in instantiation");
4363 LookupQualifiedName(Previous, CurContext);
4364 }
4365
John McCall9f54ad42009-12-10 09:41:52 +00004366 // Check for invalid redeclarations.
4367 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
4368 return 0;
4369
4370 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00004371 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
4372 return 0;
4373
John McCallaf8e6ed2009-11-12 03:15:40 +00004374 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00004375 NamedDecl *D;
Douglas Gregordc355712011-02-25 00:36:19 +00004376 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallaf8e6ed2009-11-12 03:15:40 +00004377 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00004378 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00004379 // FIXME: not all declaration name kinds are legal here
4380 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
4381 UsingLoc, TypenameLoc,
Douglas Gregordc355712011-02-25 00:36:19 +00004382 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00004383 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00004384 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00004385 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
4386 QualifierLoc, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00004387 }
John McCalled976492009-12-04 22:46:56 +00004388 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00004389 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
4390 NameInfo, IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00004391 }
John McCalled976492009-12-04 22:46:56 +00004392 D->setAccess(AS);
4393 CurContext->addDecl(D);
4394
4395 if (!LookupContext) return D;
4396 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00004397
John McCall77bb1aa2010-05-01 00:40:08 +00004398 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00004399 UD->setInvalidDecl();
4400 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00004401 }
4402
Sebastian Redlf677ea32011-02-05 19:23:19 +00004403 // Constructor inheriting using decls get special treatment.
4404 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Sebastian Redlcaa35e42011-03-12 13:44:32 +00004405 if (CheckInheritedConstructorUsingDecl(UD))
4406 UD->setInvalidDecl();
Sebastian Redlf677ea32011-02-05 19:23:19 +00004407 return UD;
4408 }
4409
4410 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00004411
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00004412 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00004413
John McCall604e7f12009-12-08 07:46:18 +00004414 // Unlike most lookups, we don't always want to hide tag
4415 // declarations: tag names are visible through the using declaration
4416 // even if hidden by ordinary names, *except* in a dependent context
4417 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00004418 if (!IsInstantiation)
4419 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00004420
John McCalla24dc2e2009-11-17 02:14:36 +00004421 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00004422
John McCallf36e02d2009-10-09 21:13:30 +00004423 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00004424 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00004425 << NameInfo.getName() << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00004426 UD->setInvalidDecl();
4427 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00004428 }
4429
John McCalled976492009-12-04 22:46:56 +00004430 if (R.isAmbiguous()) {
4431 UD->setInvalidDecl();
4432 return UD;
4433 }
Mike Stump1eb44332009-09-09 15:08:12 +00004434
John McCall7ba107a2009-11-18 02:36:19 +00004435 if (IsTypeName) {
4436 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00004437 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00004438 Diag(IdentLoc, diag::err_using_typename_non_type);
4439 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
4440 Diag((*I)->getUnderlyingDecl()->getLocation(),
4441 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00004442 UD->setInvalidDecl();
4443 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00004444 }
4445 } else {
4446 // If we asked for a non-typename and we got a type, error out,
4447 // but only if this is an instantiation of an unresolved using
4448 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00004449 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00004450 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
4451 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00004452 UD->setInvalidDecl();
4453 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00004454 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00004455 }
4456
Anders Carlsson73b39cf2009-08-28 03:35:18 +00004457 // C++0x N2914 [namespace.udecl]p6:
4458 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00004459 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00004460 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
4461 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00004462 UD->setInvalidDecl();
4463 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00004464 }
Mike Stump1eb44332009-09-09 15:08:12 +00004465
John McCall9f54ad42009-12-10 09:41:52 +00004466 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
4467 if (!CheckUsingShadowDecl(UD, *I, Previous))
4468 BuildUsingShadowDecl(S, UD, *I);
4469 }
John McCall9488ea12009-11-17 05:59:44 +00004470
4471 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00004472}
4473
Sebastian Redlf677ea32011-02-05 19:23:19 +00004474/// Additional checks for a using declaration referring to a constructor name.
4475bool Sema::CheckInheritedConstructorUsingDecl(UsingDecl *UD) {
4476 if (UD->isTypeName()) {
4477 // FIXME: Cannot specify typename when specifying constructor
4478 return true;
4479 }
4480
Douglas Gregordc355712011-02-25 00:36:19 +00004481 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redlf677ea32011-02-05 19:23:19 +00004482 assert(SourceType &&
4483 "Using decl naming constructor doesn't have type in scope spec.");
4484 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
4485
4486 // Check whether the named type is a direct base class.
4487 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
4488 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
4489 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
4490 BaseIt != BaseE; ++BaseIt) {
4491 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
4492 if (CanonicalSourceType == BaseType)
4493 break;
4494 }
4495
4496 if (BaseIt == BaseE) {
4497 // Did not find SourceType in the bases.
4498 Diag(UD->getUsingLocation(),
4499 diag::err_using_decl_constructor_not_in_direct_base)
4500 << UD->getNameInfo().getSourceRange()
4501 << QualType(SourceType, 0) << TargetClass;
4502 return true;
4503 }
4504
4505 BaseIt->setInheritConstructors();
4506
4507 return false;
4508}
4509
John McCall9f54ad42009-12-10 09:41:52 +00004510/// Checks that the given using declaration is not an invalid
4511/// redeclaration. Note that this is checking only for the using decl
4512/// itself, not for any ill-formedness among the UsingShadowDecls.
4513bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
4514 bool isTypeName,
4515 const CXXScopeSpec &SS,
4516 SourceLocation NameLoc,
4517 const LookupResult &Prev) {
4518 // C++03 [namespace.udecl]p8:
4519 // C++0x [namespace.udecl]p10:
4520 // A using-declaration is a declaration and can therefore be used
4521 // repeatedly where (and only where) multiple declarations are
4522 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00004523 //
John McCall8a726212010-11-29 18:01:58 +00004524 // That's in non-member contexts.
4525 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00004526 return false;
4527
4528 NestedNameSpecifier *Qual
4529 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
4530
4531 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
4532 NamedDecl *D = *I;
4533
4534 bool DTypename;
4535 NestedNameSpecifier *DQual;
4536 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
4537 DTypename = UD->isTypeName();
Douglas Gregordc355712011-02-25 00:36:19 +00004538 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00004539 } else if (UnresolvedUsingValueDecl *UD
4540 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
4541 DTypename = false;
Douglas Gregordc355712011-02-25 00:36:19 +00004542 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00004543 } else if (UnresolvedUsingTypenameDecl *UD
4544 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
4545 DTypename = true;
Douglas Gregordc355712011-02-25 00:36:19 +00004546 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00004547 } else continue;
4548
4549 // using decls differ if one says 'typename' and the other doesn't.
4550 // FIXME: non-dependent using decls?
4551 if (isTypeName != DTypename) continue;
4552
4553 // using decls differ if they name different scopes (but note that
4554 // template instantiation can cause this check to trigger when it
4555 // didn't before instantiation).
4556 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
4557 Context.getCanonicalNestedNameSpecifier(DQual))
4558 continue;
4559
4560 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00004561 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00004562 return true;
4563 }
4564
4565 return false;
4566}
4567
John McCall604e7f12009-12-08 07:46:18 +00004568
John McCalled976492009-12-04 22:46:56 +00004569/// Checks that the given nested-name qualifier used in a using decl
4570/// in the current context is appropriately related to the current
4571/// scope. If an error is found, diagnoses it and returns true.
4572bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
4573 const CXXScopeSpec &SS,
4574 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00004575 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00004576
John McCall604e7f12009-12-08 07:46:18 +00004577 if (!CurContext->isRecord()) {
4578 // C++03 [namespace.udecl]p3:
4579 // C++0x [namespace.udecl]p8:
4580 // A using-declaration for a class member shall be a member-declaration.
4581
4582 // If we weren't able to compute a valid scope, it must be a
4583 // dependent class scope.
4584 if (!NamedContext || NamedContext->isRecord()) {
4585 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
4586 << SS.getRange();
4587 return true;
4588 }
4589
4590 // Otherwise, everything is known to be fine.
4591 return false;
4592 }
4593
4594 // The current scope is a record.
4595
4596 // If the named context is dependent, we can't decide much.
4597 if (!NamedContext) {
4598 // FIXME: in C++0x, we can diagnose if we can prove that the
4599 // nested-name-specifier does not refer to a base class, which is
4600 // still possible in some cases.
4601
4602 // Otherwise we have to conservatively report that things might be
4603 // okay.
4604 return false;
4605 }
4606
4607 if (!NamedContext->isRecord()) {
4608 // Ideally this would point at the last name in the specifier,
4609 // but we don't have that level of source info.
4610 Diag(SS.getRange().getBegin(),
4611 diag::err_using_decl_nested_name_specifier_is_not_class)
4612 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
4613 return true;
4614 }
4615
Douglas Gregor6fb07292010-12-21 07:41:49 +00004616 if (!NamedContext->isDependentContext() &&
4617 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
4618 return true;
4619
John McCall604e7f12009-12-08 07:46:18 +00004620 if (getLangOptions().CPlusPlus0x) {
4621 // C++0x [namespace.udecl]p3:
4622 // In a using-declaration used as a member-declaration, the
4623 // nested-name-specifier shall name a base class of the class
4624 // being defined.
4625
4626 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
4627 cast<CXXRecordDecl>(NamedContext))) {
4628 if (CurContext == NamedContext) {
4629 Diag(NameLoc,
4630 diag::err_using_decl_nested_name_specifier_is_current_class)
4631 << SS.getRange();
4632 return true;
4633 }
4634
4635 Diag(SS.getRange().getBegin(),
4636 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4637 << (NestedNameSpecifier*) SS.getScopeRep()
4638 << cast<CXXRecordDecl>(CurContext)
4639 << SS.getRange();
4640 return true;
4641 }
4642
4643 return false;
4644 }
4645
4646 // C++03 [namespace.udecl]p4:
4647 // A using-declaration used as a member-declaration shall refer
4648 // to a member of a base class of the class being defined [etc.].
4649
4650 // Salient point: SS doesn't have to name a base class as long as
4651 // lookup only finds members from base classes. Therefore we can
4652 // diagnose here only if we can prove that that can't happen,
4653 // i.e. if the class hierarchies provably don't intersect.
4654
4655 // TODO: it would be nice if "definitely valid" results were cached
4656 // in the UsingDecl and UsingShadowDecl so that these checks didn't
4657 // need to be repeated.
4658
4659 struct UserData {
4660 llvm::DenseSet<const CXXRecordDecl*> Bases;
4661
4662 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
4663 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4664 Data->Bases.insert(Base);
4665 return true;
4666 }
4667
4668 bool hasDependentBases(const CXXRecordDecl *Class) {
4669 return !Class->forallBases(collect, this);
4670 }
4671
4672 /// Returns true if the base is dependent or is one of the
4673 /// accumulated base classes.
4674 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
4675 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4676 return !Data->Bases.count(Base);
4677 }
4678
4679 bool mightShareBases(const CXXRecordDecl *Class) {
4680 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
4681 }
4682 };
4683
4684 UserData Data;
4685
4686 // Returns false if we find a dependent base.
4687 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
4688 return false;
4689
4690 // Returns false if the class has a dependent base or if it or one
4691 // of its bases is present in the base set of the current context.
4692 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
4693 return false;
4694
4695 Diag(SS.getRange().getBegin(),
4696 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4697 << (NestedNameSpecifier*) SS.getScopeRep()
4698 << cast<CXXRecordDecl>(CurContext)
4699 << SS.getRange();
4700
4701 return true;
John McCalled976492009-12-04 22:46:56 +00004702}
4703
Richard Smith162e1c12011-04-15 14:24:37 +00004704Decl *Sema::ActOnAliasDeclaration(Scope *S,
4705 AccessSpecifier AS,
Richard Smith3e4c6c42011-05-05 21:57:07 +00004706 MultiTemplateParamsArg TemplateParamLists,
Richard Smith162e1c12011-04-15 14:24:37 +00004707 SourceLocation UsingLoc,
4708 UnqualifiedId &Name,
4709 TypeResult Type) {
Richard Smith3e4c6c42011-05-05 21:57:07 +00004710 // Skip up to the relevant declaration scope.
4711 while (S->getFlags() & Scope::TemplateParamScope)
4712 S = S->getParent();
Richard Smith162e1c12011-04-15 14:24:37 +00004713 assert((S->getFlags() & Scope::DeclScope) &&
4714 "got alias-declaration outside of declaration scope");
4715
4716 if (Type.isInvalid())
4717 return 0;
4718
4719 bool Invalid = false;
4720 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
4721 TypeSourceInfo *TInfo = 0;
Nick Lewyckyb79bf1d2011-05-02 01:07:19 +00004722 GetTypeFromParser(Type.get(), &TInfo);
Richard Smith162e1c12011-04-15 14:24:37 +00004723
4724 if (DiagnoseClassNameShadow(CurContext, NameInfo))
4725 return 0;
4726
4727 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3e4c6c42011-05-05 21:57:07 +00004728 UPPC_DeclarationType)) {
Richard Smith162e1c12011-04-15 14:24:37 +00004729 Invalid = true;
Richard Smith3e4c6c42011-05-05 21:57:07 +00004730 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
4731 TInfo->getTypeLoc().getBeginLoc());
4732 }
Richard Smith162e1c12011-04-15 14:24:37 +00004733
4734 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
4735 LookupName(Previous, S);
4736
4737 // Warn about shadowing the name of a template parameter.
4738 if (Previous.isSingleResult() &&
4739 Previous.getFoundDecl()->isTemplateParameter()) {
4740 if (DiagnoseTemplateParameterShadow(Name.StartLocation,
4741 Previous.getFoundDecl()))
4742 Invalid = true;
4743 Previous.clear();
4744 }
4745
4746 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
4747 "name in alias declaration must be an identifier");
4748 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
4749 Name.StartLocation,
4750 Name.Identifier, TInfo);
4751
4752 NewTD->setAccess(AS);
4753
4754 if (Invalid)
4755 NewTD->setInvalidDecl();
4756
Richard Smith3e4c6c42011-05-05 21:57:07 +00004757 CheckTypedefForVariablyModifiedType(S, NewTD);
4758 Invalid |= NewTD->isInvalidDecl();
4759
Richard Smith162e1c12011-04-15 14:24:37 +00004760 bool Redeclaration = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00004761
4762 NamedDecl *NewND;
4763 if (TemplateParamLists.size()) {
4764 TypeAliasTemplateDecl *OldDecl = 0;
4765 TemplateParameterList *OldTemplateParams = 0;
4766
4767 if (TemplateParamLists.size() != 1) {
4768 Diag(UsingLoc, diag::err_alias_template_extra_headers)
4769 << SourceRange(TemplateParamLists.get()[1]->getTemplateLoc(),
4770 TemplateParamLists.get()[TemplateParamLists.size()-1]->getRAngleLoc());
4771 }
4772 TemplateParameterList *TemplateParams = TemplateParamLists.get()[0];
4773
4774 // Only consider previous declarations in the same scope.
4775 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
4776 /*ExplicitInstantiationOrSpecialization*/false);
4777 if (!Previous.empty()) {
4778 Redeclaration = true;
4779
4780 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
4781 if (!OldDecl && !Invalid) {
4782 Diag(UsingLoc, diag::err_redefinition_different_kind)
4783 << Name.Identifier;
4784
4785 NamedDecl *OldD = Previous.getRepresentativeDecl();
4786 if (OldD->getLocation().isValid())
4787 Diag(OldD->getLocation(), diag::note_previous_definition);
4788
4789 Invalid = true;
4790 }
4791
4792 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
4793 if (TemplateParameterListsAreEqual(TemplateParams,
4794 OldDecl->getTemplateParameters(),
4795 /*Complain=*/true,
4796 TPL_TemplateMatch))
4797 OldTemplateParams = OldDecl->getTemplateParameters();
4798 else
4799 Invalid = true;
4800
4801 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
4802 if (!Invalid &&
4803 !Context.hasSameType(OldTD->getUnderlyingType(),
4804 NewTD->getUnderlyingType())) {
4805 // FIXME: The C++0x standard does not clearly say this is ill-formed,
4806 // but we can't reasonably accept it.
4807 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
4808 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
4809 if (OldTD->getLocation().isValid())
4810 Diag(OldTD->getLocation(), diag::note_previous_definition);
4811 Invalid = true;
4812 }
4813 }
4814 }
4815
4816 // Merge any previous default template arguments into our parameters,
4817 // and check the parameter list.
4818 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
4819 TPC_TypeAliasTemplate))
4820 return 0;
4821
4822 TypeAliasTemplateDecl *NewDecl =
4823 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
4824 Name.Identifier, TemplateParams,
4825 NewTD);
4826
4827 NewDecl->setAccess(AS);
4828
4829 if (Invalid)
4830 NewDecl->setInvalidDecl();
4831 else if (OldDecl)
4832 NewDecl->setPreviousDeclaration(OldDecl);
4833
4834 NewND = NewDecl;
4835 } else {
4836 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
4837 NewND = NewTD;
4838 }
Richard Smith162e1c12011-04-15 14:24:37 +00004839
4840 if (!Redeclaration)
Richard Smith3e4c6c42011-05-05 21:57:07 +00004841 PushOnScopeChains(NewND, S);
Richard Smith162e1c12011-04-15 14:24:37 +00004842
Richard Smith3e4c6c42011-05-05 21:57:07 +00004843 return NewND;
Richard Smith162e1c12011-04-15 14:24:37 +00004844}
4845
John McCalld226f652010-08-21 09:40:31 +00004846Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00004847 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00004848 SourceLocation AliasLoc,
4849 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00004850 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00004851 SourceLocation IdentLoc,
4852 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00004853
Anders Carlsson81c85c42009-03-28 23:53:49 +00004854 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00004855 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
4856 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00004857
Anders Carlsson8d7ba402009-03-28 06:23:46 +00004858 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00004859 NamedDecl *PrevDecl
4860 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
4861 ForRedeclaration);
4862 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
4863 PrevDecl = 0;
4864
4865 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00004866 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00004867 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00004868 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00004869 // FIXME: At some point, we'll want to create the (redundant)
4870 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00004871 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00004872 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00004873 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00004874 }
Mike Stump1eb44332009-09-09 15:08:12 +00004875
Anders Carlsson8d7ba402009-03-28 06:23:46 +00004876 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
4877 diag::err_redefinition_different_kind;
4878 Diag(AliasLoc, DiagID) << Alias;
4879 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00004880 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00004881 }
4882
John McCalla24dc2e2009-11-17 02:14:36 +00004883 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00004884 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004885
John McCallf36e02d2009-10-09 21:13:30 +00004886 if (R.empty()) {
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00004887 if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
4888 CTC_NoKeywords, 0)) {
4889 if (R.getAsSingle<NamespaceDecl>() ||
4890 R.getAsSingle<NamespaceAliasDecl>()) {
4891 if (DeclContext *DC = computeDeclContext(SS, false))
4892 Diag(IdentLoc, diag::err_using_directive_member_suggest)
4893 << Ident << DC << Corrected << SS.getRange()
4894 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4895 else
4896 Diag(IdentLoc, diag::err_using_directive_suggest)
4897 << Ident << Corrected
4898 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4899
4900 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
4901 << Corrected;
4902
4903 Ident = Corrected.getAsIdentifierInfo();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00004904 } else {
4905 R.clear();
4906 R.setLookupName(Ident);
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00004907 }
4908 }
4909
4910 if (R.empty()) {
4911 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00004912 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00004913 }
Anders Carlsson5721c682009-03-28 06:42:02 +00004914 }
Mike Stump1eb44332009-09-09 15:08:12 +00004915
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00004916 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00004917 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00004918 Alias, SS.getWithLocInContext(Context),
John McCallf36e02d2009-10-09 21:13:30 +00004919 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00004920
John McCall3dbd3d52010-02-16 06:53:13 +00004921 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00004922 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00004923}
4924
Douglas Gregor39957dc2010-05-01 15:04:51 +00004925namespace {
4926 /// \brief Scoped object used to handle the state changes required in Sema
4927 /// to implicitly define the body of a C++ member function;
4928 class ImplicitlyDefinedFunctionScope {
4929 Sema &S;
John McCalleee1d542011-02-14 07:13:47 +00004930 Sema::ContextRAII SavedContext;
Douglas Gregor39957dc2010-05-01 15:04:51 +00004931
4932 public:
4933 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
John McCalleee1d542011-02-14 07:13:47 +00004934 : S(S), SavedContext(S, Method)
Douglas Gregor39957dc2010-05-01 15:04:51 +00004935 {
Douglas Gregor39957dc2010-05-01 15:04:51 +00004936 S.PushFunctionScope();
4937 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
4938 }
4939
4940 ~ImplicitlyDefinedFunctionScope() {
4941 S.PopExpressionEvaluationContext();
4942 S.PopFunctionOrBlockScope();
Douglas Gregor39957dc2010-05-01 15:04:51 +00004943 }
4944 };
4945}
4946
Sebastian Redl751025d2010-09-13 22:02:47 +00004947static CXXConstructorDecl *getDefaultConstructorUnsafe(Sema &Self,
4948 CXXRecordDecl *D) {
4949 ASTContext &Context = Self.Context;
4950 QualType ClassType = Context.getTypeDeclType(D);
4951 DeclarationName ConstructorName
4952 = Context.DeclarationNames.getCXXConstructorName(
4953 Context.getCanonicalType(ClassType.getUnqualifiedType()));
4954
4955 DeclContext::lookup_const_iterator Con, ConEnd;
4956 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
4957 Con != ConEnd; ++Con) {
4958 // FIXME: In C++0x, a constructor template can be a default constructor.
4959 if (isa<FunctionTemplateDecl>(*Con))
4960 continue;
4961
4962 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
4963 if (Constructor->isDefaultConstructor())
4964 return Constructor;
4965 }
4966 return 0;
4967}
4968
Douglas Gregor23c94db2010-07-02 17:43:08 +00004969CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
4970 CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00004971 // C++ [class.ctor]p5:
4972 // A default constructor for a class X is a constructor of class X
4973 // that can be called without an argument. If there is no
4974 // user-declared constructor for class X, a default constructor is
4975 // implicitly declared. An implicitly-declared default constructor
4976 // is an inline public member of its class.
Douglas Gregor18274032010-07-03 00:47:00 +00004977 assert(!ClassDecl->hasUserDeclaredConstructor() &&
4978 "Should not build implicit default constructor!");
4979
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004980 // C++ [except.spec]p14:
4981 // An implicitly declared special member function (Clause 12) shall have an
4982 // exception-specification. [...]
4983 ImplicitExceptionSpecification ExceptSpec(Context);
4984
Sebastian Redl60618fa2011-03-12 11:50:43 +00004985 // Direct base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004986 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4987 BEnd = ClassDecl->bases_end();
4988 B != BEnd; ++B) {
4989 if (B->isVirtual()) // Handled below.
4990 continue;
4991
Douglas Gregor18274032010-07-03 00:47:00 +00004992 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
4993 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4994 if (!BaseClassDecl->hasDeclaredDefaultConstructor())
4995 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
Sebastian Redl751025d2010-09-13 22:02:47 +00004996 else if (CXXConstructorDecl *Constructor
4997 = getDefaultConstructorUnsafe(*this, BaseClassDecl))
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004998 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00004999 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00005000 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00005001
5002 // Virtual base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00005003 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
5004 BEnd = ClassDecl->vbases_end();
5005 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00005006 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
5007 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
5008 if (!BaseClassDecl->hasDeclaredDefaultConstructor())
5009 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
5010 else if (CXXConstructorDecl *Constructor
Sebastian Redl751025d2010-09-13 22:02:47 +00005011 = getDefaultConstructorUnsafe(*this, BaseClassDecl))
Douglas Gregoreb8c6702010-07-01 22:31:05 +00005012 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00005013 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00005014 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00005015
5016 // Field constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00005017 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
5018 FEnd = ClassDecl->field_end();
5019 F != FEnd; ++F) {
5020 if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00005021 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
5022 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
5023 if (!FieldClassDecl->hasDeclaredDefaultConstructor())
5024 ExceptSpec.CalledDecl(
5025 DeclareImplicitDefaultConstructor(FieldClassDecl));
5026 else if (CXXConstructorDecl *Constructor
Sebastian Redl751025d2010-09-13 22:02:47 +00005027 = getDefaultConstructorUnsafe(*this, FieldClassDecl))
Douglas Gregoreb8c6702010-07-01 22:31:05 +00005028 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00005029 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00005030 }
John McCalle23cf432010-12-14 08:05:40 +00005031
5032 FunctionProtoType::ExtProtoInfo EPI;
Sebastian Redl60618fa2011-03-12 11:50:43 +00005033 EPI.ExceptionSpecType = ExceptSpec.getExceptionSpecType();
John McCalle23cf432010-12-14 08:05:40 +00005034 EPI.NumExceptions = ExceptSpec.size();
5035 EPI.Exceptions = ExceptSpec.data();
Sebastian Redl8b5b4092011-03-06 10:52:04 +00005036
Douglas Gregoreb8c6702010-07-01 22:31:05 +00005037 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00005038 CanQualType ClassType
5039 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005040 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor32df23e2010-07-01 22:02:46 +00005041 DeclarationName Name
5042 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005043 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregor32df23e2010-07-01 22:02:46 +00005044 CXXConstructorDecl *DefaultCon
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005045 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Douglas Gregor32df23e2010-07-01 22:02:46 +00005046 Context.getFunctionType(Context.VoidTy,
John McCalle23cf432010-12-14 08:05:40 +00005047 0, 0, EPI),
Douglas Gregor32df23e2010-07-01 22:02:46 +00005048 /*TInfo=*/0,
5049 /*isExplicit=*/false,
5050 /*isInline=*/true,
Sean Hunt5f802e52011-05-06 00:11:07 +00005051 /*isImplicitlyDeclared=*/true);
Douglas Gregor32df23e2010-07-01 22:02:46 +00005052 DefaultCon->setAccess(AS_public);
5053 DefaultCon->setImplicit();
5054 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Douglas Gregor18274032010-07-03 00:47:00 +00005055
5056 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00005057 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
5058
Douglas Gregor23c94db2010-07-02 17:43:08 +00005059 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00005060 PushOnScopeChains(DefaultCon, S, false);
5061 ClassDecl->addDecl(DefaultCon);
5062
Douglas Gregor32df23e2010-07-01 22:02:46 +00005063 return DefaultCon;
5064}
5065
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00005066void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
5067 CXXConstructorDecl *Constructor) {
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00005068 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
Douglas Gregorc070cc62010-06-17 23:14:26 +00005069 !Constructor->isUsed(false)) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00005070 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00005071
Anders Carlssonf6513ed2010-04-23 16:04:08 +00005072 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00005073 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00005074
Douglas Gregor39957dc2010-05-01 15:04:51 +00005075 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00005076 DiagnosticErrorTrap Trap(Diags);
Sean Huntcbb67482011-01-08 20:30:50 +00005077 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00005078 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00005079 Diag(CurrentLocation, diag::note_member_synthesized_at)
Anders Carlsson3b8c53b2010-04-22 05:40:53 +00005080 << CXXConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00005081 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00005082 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00005083 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00005084
5085 SourceLocation Loc = Constructor->getLocation();
5086 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
5087
5088 Constructor->setUsed();
5089 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00005090
5091 if (ASTMutationListener *L = getASTMutationListener()) {
5092 L->CompletedImplicitDefinition(Constructor);
5093 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00005094}
5095
Sebastian Redlf677ea32011-02-05 19:23:19 +00005096void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
5097 // We start with an initial pass over the base classes to collect those that
5098 // inherit constructors from. If there are none, we can forgo all further
5099 // processing.
5100 typedef llvm::SmallVector<const RecordType *, 4> BasesVector;
5101 BasesVector BasesToInheritFrom;
5102 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
5103 BaseE = ClassDecl->bases_end();
5104 BaseIt != BaseE; ++BaseIt) {
5105 if (BaseIt->getInheritConstructors()) {
5106 QualType Base = BaseIt->getType();
5107 if (Base->isDependentType()) {
5108 // If we inherit constructors from anything that is dependent, just
5109 // abort processing altogether. We'll get another chance for the
5110 // instantiations.
5111 return;
5112 }
5113 BasesToInheritFrom.push_back(Base->castAs<RecordType>());
5114 }
5115 }
5116 if (BasesToInheritFrom.empty())
5117 return;
5118
5119 // Now collect the constructors that we already have in the current class.
5120 // Those take precedence over inherited constructors.
5121 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
5122 // unless there is a user-declared constructor with the same signature in
5123 // the class where the using-declaration appears.
5124 llvm::SmallSet<const Type *, 8> ExistingConstructors;
5125 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
5126 CtorE = ClassDecl->ctor_end();
5127 CtorIt != CtorE; ++CtorIt) {
5128 ExistingConstructors.insert(
5129 Context.getCanonicalType(CtorIt->getType()).getTypePtr());
5130 }
5131
5132 Scope *S = getScopeForContext(ClassDecl);
5133 DeclarationName CreatedCtorName =
5134 Context.DeclarationNames.getCXXConstructorName(
5135 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
5136
5137 // Now comes the true work.
5138 // First, we keep a map from constructor types to the base that introduced
5139 // them. Needed for finding conflicting constructors. We also keep the
5140 // actually inserted declarations in there, for pretty diagnostics.
5141 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
5142 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
5143 ConstructorToSourceMap InheritedConstructors;
5144 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
5145 BaseE = BasesToInheritFrom.end();
5146 BaseIt != BaseE; ++BaseIt) {
5147 const RecordType *Base = *BaseIt;
5148 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
5149 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
5150 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
5151 CtorE = BaseDecl->ctor_end();
5152 CtorIt != CtorE; ++CtorIt) {
5153 // Find the using declaration for inheriting this base's constructors.
5154 DeclarationName Name =
5155 Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
5156 UsingDecl *UD = dyn_cast_or_null<UsingDecl>(
5157 LookupSingleName(S, Name,SourceLocation(), LookupUsingDeclName));
5158 SourceLocation UsingLoc = UD ? UD->getLocation() :
5159 ClassDecl->getLocation();
5160
5161 // C++0x [class.inhctor]p1: The candidate set of inherited constructors
5162 // from the class X named in the using-declaration consists of actual
5163 // constructors and notional constructors that result from the
5164 // transformation of defaulted parameters as follows:
5165 // - all non-template default constructors of X, and
5166 // - for each non-template constructor of X that has at least one
5167 // parameter with a default argument, the set of constructors that
5168 // results from omitting any ellipsis parameter specification and
5169 // successively omitting parameters with a default argument from the
5170 // end of the parameter-type-list.
5171 CXXConstructorDecl *BaseCtor = *CtorIt;
5172 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
5173 const FunctionProtoType *BaseCtorType =
5174 BaseCtor->getType()->getAs<FunctionProtoType>();
5175
5176 for (unsigned params = BaseCtor->getMinRequiredArguments(),
5177 maxParams = BaseCtor->getNumParams();
5178 params <= maxParams; ++params) {
5179 // Skip default constructors. They're never inherited.
5180 if (params == 0)
5181 continue;
5182 // Skip copy and move constructors for the same reason.
5183 if (CanBeCopyOrMove && params == 1)
5184 continue;
5185
5186 // Build up a function type for this particular constructor.
5187 // FIXME: The working paper does not consider that the exception spec
5188 // for the inheriting constructor might be larger than that of the
5189 // source. This code doesn't yet, either.
5190 const Type *NewCtorType;
5191 if (params == maxParams)
5192 NewCtorType = BaseCtorType;
5193 else {
5194 llvm::SmallVector<QualType, 16> Args;
5195 for (unsigned i = 0; i < params; ++i) {
5196 Args.push_back(BaseCtorType->getArgType(i));
5197 }
5198 FunctionProtoType::ExtProtoInfo ExtInfo =
5199 BaseCtorType->getExtProtoInfo();
5200 ExtInfo.Variadic = false;
5201 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
5202 Args.data(), params, ExtInfo)
5203 .getTypePtr();
5204 }
5205 const Type *CanonicalNewCtorType =
5206 Context.getCanonicalType(NewCtorType);
5207
5208 // Now that we have the type, first check if the class already has a
5209 // constructor with this signature.
5210 if (ExistingConstructors.count(CanonicalNewCtorType))
5211 continue;
5212
5213 // Then we check if we have already declared an inherited constructor
5214 // with this signature.
5215 std::pair<ConstructorToSourceMap::iterator, bool> result =
5216 InheritedConstructors.insert(std::make_pair(
5217 CanonicalNewCtorType,
5218 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
5219 if (!result.second) {
5220 // Already in the map. If it came from a different class, that's an
5221 // error. Not if it's from the same.
5222 CanQualType PreviousBase = result.first->second.first;
5223 if (CanonicalBase != PreviousBase) {
5224 const CXXConstructorDecl *PrevCtor = result.first->second.second;
5225 const CXXConstructorDecl *PrevBaseCtor =
5226 PrevCtor->getInheritedConstructor();
5227 assert(PrevBaseCtor && "Conflicting constructor was not inherited");
5228
5229 Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
5230 Diag(BaseCtor->getLocation(),
5231 diag::note_using_decl_constructor_conflict_current_ctor);
5232 Diag(PrevBaseCtor->getLocation(),
5233 diag::note_using_decl_constructor_conflict_previous_ctor);
5234 Diag(PrevCtor->getLocation(),
5235 diag::note_using_decl_constructor_conflict_previous_using);
5236 }
5237 continue;
5238 }
5239
5240 // OK, we're there, now add the constructor.
5241 // C++0x [class.inhctor]p8: [...] that would be performed by a
5242 // user-writtern inline constructor [...]
5243 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
5244 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005245 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
5246 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
Sean Hunt5f802e52011-05-06 00:11:07 +00005247 /*ImplicitlyDeclared=*/true);
Sebastian Redlf677ea32011-02-05 19:23:19 +00005248 NewCtor->setAccess(BaseCtor->getAccess());
5249
5250 // Build up the parameter decls and add them.
5251 llvm::SmallVector<ParmVarDecl *, 16> ParamDecls;
5252 for (unsigned i = 0; i < params; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005253 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
5254 UsingLoc, UsingLoc,
Sebastian Redlf677ea32011-02-05 19:23:19 +00005255 /*IdentifierInfo=*/0,
5256 BaseCtorType->getArgType(i),
5257 /*TInfo=*/0, SC_None,
5258 SC_None, /*DefaultArg=*/0));
5259 }
5260 NewCtor->setParams(ParamDecls.data(), ParamDecls.size());
5261 NewCtor->setInheritedConstructor(BaseCtor);
5262
5263 PushOnScopeChains(NewCtor, S, false);
5264 ClassDecl->addDecl(NewCtor);
5265 result.first->second.second = NewCtor;
5266 }
5267 }
5268 }
5269}
5270
Douglas Gregor23c94db2010-07-02 17:43:08 +00005271CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
Douglas Gregorfabd43a2010-07-01 19:09:28 +00005272 // C++ [class.dtor]p2:
5273 // If a class has no user-declared destructor, a destructor is
5274 // declared implicitly. An implicitly-declared destructor is an
5275 // inline public member of its class.
5276
5277 // C++ [except.spec]p14:
5278 // An implicitly declared special member function (Clause 12) shall have
5279 // an exception-specification.
5280 ImplicitExceptionSpecification ExceptSpec(Context);
5281
5282 // Direct base-class destructors.
5283 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
5284 BEnd = ClassDecl->bases_end();
5285 B != BEnd; ++B) {
5286 if (B->isVirtual()) // Handled below.
5287 continue;
5288
5289 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
5290 ExceptSpec.CalledDecl(
Douglas Gregordb89f282010-07-01 22:47:18 +00005291 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00005292 }
5293
5294 // Virtual base-class destructors.
5295 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
5296 BEnd = ClassDecl->vbases_end();
5297 B != BEnd; ++B) {
5298 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
5299 ExceptSpec.CalledDecl(
Douglas Gregordb89f282010-07-01 22:47:18 +00005300 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00005301 }
5302
5303 // Field destructors.
5304 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
5305 FEnd = ClassDecl->field_end();
5306 F != FEnd; ++F) {
5307 if (const RecordType *RecordTy
5308 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
5309 ExceptSpec.CalledDecl(
Douglas Gregordb89f282010-07-01 22:47:18 +00005310 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00005311 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00005312
Douglas Gregor4923aa22010-07-02 20:37:36 +00005313 // Create the actual destructor declaration.
John McCalle23cf432010-12-14 08:05:40 +00005314 FunctionProtoType::ExtProtoInfo EPI;
Sebastian Redl60618fa2011-03-12 11:50:43 +00005315 EPI.ExceptionSpecType = ExceptSpec.getExceptionSpecType();
John McCalle23cf432010-12-14 08:05:40 +00005316 EPI.NumExceptions = ExceptSpec.size();
5317 EPI.Exceptions = ExceptSpec.data();
5318 QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Sebastian Redl60618fa2011-03-12 11:50:43 +00005319
Douglas Gregorfabd43a2010-07-01 19:09:28 +00005320 CanQualType ClassType
5321 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005322 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00005323 DeclarationName Name
5324 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005325 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00005326 CXXDestructorDecl *Destructor
Sebastian Redl60618fa2011-03-12 11:50:43 +00005327 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, Ty, 0,
5328 /*isInline=*/true,
5329 /*isImplicitlyDeclared=*/true);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00005330 Destructor->setAccess(AS_public);
5331 Destructor->setImplicit();
5332 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor4923aa22010-07-02 20:37:36 +00005333
5334 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00005335 ++ASTContext::NumImplicitDestructorsDeclared;
5336
5337 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00005338 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00005339 PushOnScopeChains(Destructor, S, false);
5340 ClassDecl->addDecl(Destructor);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00005341
5342 // This could be uniqued if it ever proves significant.
5343 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
5344
5345 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor4923aa22010-07-02 20:37:36 +00005346
Douglas Gregorfabd43a2010-07-01 19:09:28 +00005347 return Destructor;
5348}
5349
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00005350void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00005351 CXXDestructorDecl *Destructor) {
Douglas Gregorc070cc62010-06-17 23:14:26 +00005352 assert((Destructor->isImplicit() && !Destructor->isUsed(false)) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00005353 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00005354 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00005355 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005356
Douglas Gregorc63d2c82010-05-12 16:39:35 +00005357 if (Destructor->isInvalidDecl())
5358 return;
5359
Douglas Gregor39957dc2010-05-01 15:04:51 +00005360 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005361
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00005362 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00005363 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
5364 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00005365
Douglas Gregorc63d2c82010-05-12 16:39:35 +00005366 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00005367 Diag(CurrentLocation, diag::note_member_synthesized_at)
5368 << CXXDestructor << Context.getTagDeclType(ClassDecl);
5369
5370 Destructor->setInvalidDecl();
5371 return;
5372 }
5373
Douglas Gregor4ada9d32010-09-20 16:48:21 +00005374 SourceLocation Loc = Destructor->getLocation();
5375 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
5376
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00005377 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00005378 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00005379
5380 if (ASTMutationListener *L = getASTMutationListener()) {
5381 L->CompletedImplicitDefinition(Destructor);
5382 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00005383}
5384
Douglas Gregor06a9f362010-05-01 20:49:11 +00005385/// \brief Builds a statement that copies the given entity from \p From to
5386/// \c To.
5387///
5388/// This routine is used to copy the members of a class with an
5389/// implicitly-declared copy assignment operator. When the entities being
5390/// copied are arrays, this routine builds for loops to copy them.
5391///
5392/// \param S The Sema object used for type-checking.
5393///
5394/// \param Loc The location where the implicit copy is being generated.
5395///
5396/// \param T The type of the expressions being copied. Both expressions must
5397/// have this type.
5398///
5399/// \param To The expression we are copying to.
5400///
5401/// \param From The expression we are copying from.
5402///
Douglas Gregor6cdc1612010-05-04 15:20:55 +00005403/// \param CopyingBaseSubobject Whether we're copying a base subobject.
5404/// Otherwise, it's a non-static member subobject.
5405///
Douglas Gregor06a9f362010-05-01 20:49:11 +00005406/// \param Depth Internal parameter recording the depth of the recursion.
5407///
5408/// \returns A statement or a loop that copies the expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00005409static StmtResult
Douglas Gregor06a9f362010-05-01 20:49:11 +00005410BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCall9ae2f072010-08-23 23:25:46 +00005411 Expr *To, Expr *From,
Douglas Gregor6cdc1612010-05-04 15:20:55 +00005412 bool CopyingBaseSubobject, unsigned Depth = 0) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00005413 // C++0x [class.copy]p30:
5414 // Each subobject is assigned in the manner appropriate to its type:
5415 //
5416 // - if the subobject is of class type, the copy assignment operator
5417 // for the class is used (as if by explicit qualification; that is,
5418 // ignoring any possible virtual overriding functions in more derived
5419 // classes);
5420 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
5421 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
5422
5423 // Look for operator=.
5424 DeclarationName Name
5425 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
5426 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
5427 S.LookupQualifiedName(OpLookup, ClassDecl, false);
5428
5429 // Filter out any result that isn't a copy-assignment operator.
5430 LookupResult::Filter F = OpLookup.makeFilter();
5431 while (F.hasNext()) {
5432 NamedDecl *D = F.next();
5433 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
5434 if (Method->isCopyAssignmentOperator())
5435 continue;
5436
5437 F.erase();
John McCallb0207482010-03-16 06:11:48 +00005438 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00005439 F.done();
5440
Douglas Gregor6cdc1612010-05-04 15:20:55 +00005441 // Suppress the protected check (C++ [class.protected]) for each of the
5442 // assignment operators we found. This strange dance is required when
5443 // we're assigning via a base classes's copy-assignment operator. To
5444 // ensure that we're getting the right base class subobject (without
5445 // ambiguities), we need to cast "this" to that subobject type; to
5446 // ensure that we don't go through the virtual call mechanism, we need
5447 // to qualify the operator= name with the base class (see below). However,
5448 // this means that if the base class has a protected copy assignment
5449 // operator, the protected member access check will fail. So, we
5450 // rewrite "protected" access to "public" access in this case, since we
5451 // know by construction that we're calling from a derived class.
5452 if (CopyingBaseSubobject) {
5453 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
5454 L != LEnd; ++L) {
5455 if (L.getAccess() == AS_protected)
5456 L.setAccess(AS_public);
5457 }
5458 }
5459
Douglas Gregor06a9f362010-05-01 20:49:11 +00005460 // Create the nested-name-specifier that will be used to qualify the
5461 // reference to operator=; this is required to suppress the virtual
5462 // call mechanism.
5463 CXXScopeSpec SS;
Douglas Gregorc34348a2011-02-24 17:54:50 +00005464 SS.MakeTrivial(S.Context,
5465 NestedNameSpecifier::Create(S.Context, 0, false,
5466 T.getTypePtr()),
5467 Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005468
5469 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00005470 ExprResult OpEqualRef
John McCall9ae2f072010-08-23 23:25:46 +00005471 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Douglas Gregor06a9f362010-05-01 20:49:11 +00005472 /*FirstQualifierInScope=*/0, OpLookup,
5473 /*TemplateArgs=*/0,
5474 /*SuppressQualifierCheck=*/true);
5475 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005476 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00005477
5478 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00005479
John McCall60d7b3a2010-08-24 06:29:42 +00005480 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00005481 OpEqualRef.takeAs<Expr>(),
5482 Loc, &From, 1, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005483 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005484 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00005485
5486 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00005487 }
John McCallb0207482010-03-16 06:11:48 +00005488
Douglas Gregor06a9f362010-05-01 20:49:11 +00005489 // - if the subobject is of scalar type, the built-in assignment
5490 // operator is used.
5491 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
5492 if (!ArrayTy) {
John McCall2de56d12010-08-25 11:45:40 +00005493 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005494 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005495 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00005496
5497 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00005498 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00005499
5500 // - if the subobject is an array, each element is assigned, in the
5501 // manner appropriate to the element type;
5502
5503 // Construct a loop over the array bounds, e.g.,
5504 //
5505 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
5506 //
5507 // that will copy each of the array elements.
5508 QualType SizeType = S.Context.getSizeType();
5509
5510 // Create the iteration variable.
5511 IdentifierInfo *IterationVarName = 0;
5512 {
5513 llvm::SmallString<8> Str;
5514 llvm::raw_svector_ostream OS(Str);
5515 OS << "__i" << Depth;
5516 IterationVarName = &S.Context.Idents.get(OS.str());
5517 }
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005518 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00005519 IterationVarName, SizeType,
5520 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00005521 SC_None, SC_None);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005522
5523 // Initialize the iteration variable to zero.
5524 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00005525 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00005526
5527 // Create a reference to the iteration variable; we'll use this several
5528 // times throughout.
5529 Expr *IterationVarRef
John McCallf89e55a2010-11-18 06:31:45 +00005530 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00005531 assert(IterationVarRef && "Reference to invented variable cannot fail!");
5532
5533 // Create the DeclStmt that holds the iteration variable.
5534 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
5535
5536 // Create the comparison against the array bound.
Jay Foad9f71a8f2010-12-07 08:25:34 +00005537 llvm::APInt Upper
5538 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCall9ae2f072010-08-23 23:25:46 +00005539 Expr *Comparison
John McCall3fa5cae2010-10-26 07:05:15 +00005540 = new (S.Context) BinaryOperator(IterationVarRef,
John McCallf89e55a2010-11-18 06:31:45 +00005541 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
5542 BO_NE, S.Context.BoolTy,
5543 VK_RValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005544
5545 // Create the pre-increment of the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00005546 Expr *Increment
John McCallf89e55a2010-11-18 06:31:45 +00005547 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
5548 VK_LValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005549
5550 // Subscript the "from" and "to" expressions with the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00005551 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
5552 IterationVarRef, Loc));
5553 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
5554 IterationVarRef, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00005555
5556 // Build the copy for an individual element of the array.
John McCallf89e55a2010-11-18 06:31:45 +00005557 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
5558 To, From, CopyingBaseSubobject,
5559 Depth + 1);
Douglas Gregorff331c12010-07-25 18:17:45 +00005560 if (Copy.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005561 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00005562
5563 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00005564 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00005565 S.MakeFullExpr(Comparison),
John McCalld226f652010-08-21 09:40:31 +00005566 0, S.MakeFullExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00005567 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00005568}
5569
Douglas Gregora376d102010-07-02 21:50:04 +00005570/// \brief Determine whether the given class has a copy assignment operator
5571/// that accepts a const-qualified argument.
5572static bool hasConstCopyAssignment(Sema &S, const CXXRecordDecl *CClass) {
5573 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(CClass);
5574
5575 if (!Class->hasDeclaredCopyAssignment())
5576 S.DeclareImplicitCopyAssignment(Class);
5577
5578 QualType ClassType = S.Context.getCanonicalType(S.Context.getTypeDeclType(Class));
5579 DeclarationName OpName
5580 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
5581
5582 DeclContext::lookup_const_iterator Op, OpEnd;
5583 for (llvm::tie(Op, OpEnd) = Class->lookup(OpName); Op != OpEnd; ++Op) {
5584 // C++ [class.copy]p9:
5585 // A user-declared copy assignment operator is a non-static non-template
5586 // member function of class X with exactly one parameter of type X, X&,
5587 // const X&, volatile X& or const volatile X&.
5588 const CXXMethodDecl* Method = dyn_cast<CXXMethodDecl>(*Op);
5589 if (!Method)
5590 continue;
5591
5592 if (Method->isStatic())
5593 continue;
5594 if (Method->getPrimaryTemplate())
5595 continue;
5596 const FunctionProtoType *FnType =
5597 Method->getType()->getAs<FunctionProtoType>();
5598 assert(FnType && "Overloaded operator has no prototype.");
5599 // Don't assert on this; an invalid decl might have been left in the AST.
5600 if (FnType->getNumArgs() != 1 || FnType->isVariadic())
5601 continue;
5602 bool AcceptsConst = true;
5603 QualType ArgType = FnType->getArgType(0);
5604 if (const LValueReferenceType *Ref = ArgType->getAs<LValueReferenceType>()){
5605 ArgType = Ref->getPointeeType();
5606 // Is it a non-const lvalue reference?
5607 if (!ArgType.isConstQualified())
5608 AcceptsConst = false;
5609 }
5610 if (!S.Context.hasSameUnqualifiedType(ArgType, ClassType))
5611 continue;
5612
5613 // We have a single argument of type cv X or cv X&, i.e. we've found the
5614 // copy assignment operator. Return whether it accepts const arguments.
5615 return AcceptsConst;
5616 }
5617 assert(Class->isInvalidDecl() &&
5618 "No copy assignment operator declared in valid code.");
5619 return false;
5620}
5621
Douglas Gregor23c94db2010-07-02 17:43:08 +00005622CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
Douglas Gregord3c35902010-07-01 16:36:15 +00005623 // Note: The following rules are largely analoguous to the copy
5624 // constructor rules. Note that virtual bases are not taken into account
5625 // for determining the argument type of the operator. Note also that
5626 // operators taking an object instead of a reference are allowed.
Douglas Gregor18274032010-07-03 00:47:00 +00005627
5628
Douglas Gregord3c35902010-07-01 16:36:15 +00005629 // C++ [class.copy]p10:
5630 // If the class definition does not explicitly declare a copy
5631 // assignment operator, one is declared implicitly.
5632 // The implicitly-defined copy assignment operator for a class X
5633 // will have the form
5634 //
5635 // X& X::operator=(const X&)
5636 //
5637 // if
5638 bool HasConstCopyAssignment = true;
5639
5640 // -- each direct base class B of X has a copy assignment operator
5641 // whose parameter is of type const B&, const volatile B& or B,
5642 // and
5643 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5644 BaseEnd = ClassDecl->bases_end();
5645 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
5646 assert(!Base->getType()->isDependentType() &&
5647 "Cannot generate implicit members for class with dependent bases.");
5648 const CXXRecordDecl *BaseClassDecl
5649 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora376d102010-07-02 21:50:04 +00005650 HasConstCopyAssignment = hasConstCopyAssignment(*this, BaseClassDecl);
Douglas Gregord3c35902010-07-01 16:36:15 +00005651 }
5652
5653 // -- for all the nonstatic data members of X that are of a class
5654 // type M (or array thereof), each such class type has a copy
5655 // assignment operator whose parameter is of type const M&,
5656 // const volatile M& or M.
5657 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5658 FieldEnd = ClassDecl->field_end();
5659 HasConstCopyAssignment && Field != FieldEnd;
5660 ++Field) {
5661 QualType FieldType = Context.getBaseElementType((*Field)->getType());
5662 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
5663 const CXXRecordDecl *FieldClassDecl
5664 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora376d102010-07-02 21:50:04 +00005665 HasConstCopyAssignment = hasConstCopyAssignment(*this, FieldClassDecl);
Douglas Gregord3c35902010-07-01 16:36:15 +00005666 }
5667 }
5668
5669 // Otherwise, the implicitly declared copy assignment operator will
5670 // have the form
5671 //
5672 // X& X::operator=(X&)
5673 QualType ArgType = Context.getTypeDeclType(ClassDecl);
5674 QualType RetType = Context.getLValueReferenceType(ArgType);
5675 if (HasConstCopyAssignment)
5676 ArgType = ArgType.withConst();
5677 ArgType = Context.getLValueReferenceType(ArgType);
5678
Douglas Gregorb87786f2010-07-01 17:48:08 +00005679 // C++ [except.spec]p14:
5680 // An implicitly declared special member function (Clause 12) shall have an
5681 // exception-specification. [...]
5682 ImplicitExceptionSpecification ExceptSpec(Context);
5683 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5684 BaseEnd = ClassDecl->bases_end();
5685 Base != BaseEnd; ++Base) {
Douglas Gregora376d102010-07-02 21:50:04 +00005686 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00005687 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora376d102010-07-02 21:50:04 +00005688
5689 if (!BaseClassDecl->hasDeclaredCopyAssignment())
5690 DeclareImplicitCopyAssignment(BaseClassDecl);
5691
Douglas Gregorb87786f2010-07-01 17:48:08 +00005692 if (CXXMethodDecl *CopyAssign
5693 = BaseClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
5694 ExceptSpec.CalledDecl(CopyAssign);
5695 }
5696 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5697 FieldEnd = ClassDecl->field_end();
5698 Field != FieldEnd;
5699 ++Field) {
5700 QualType FieldType = Context.getBaseElementType((*Field)->getType());
5701 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregora376d102010-07-02 21:50:04 +00005702 CXXRecordDecl *FieldClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00005703 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora376d102010-07-02 21:50:04 +00005704
5705 if (!FieldClassDecl->hasDeclaredCopyAssignment())
5706 DeclareImplicitCopyAssignment(FieldClassDecl);
5707
Douglas Gregorb87786f2010-07-01 17:48:08 +00005708 if (CXXMethodDecl *CopyAssign
5709 = FieldClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
5710 ExceptSpec.CalledDecl(CopyAssign);
5711 }
5712 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00005713
Douglas Gregord3c35902010-07-01 16:36:15 +00005714 // An implicitly-declared copy assignment operator is an inline public
5715 // member of its class.
John McCalle23cf432010-12-14 08:05:40 +00005716 FunctionProtoType::ExtProtoInfo EPI;
Sebastian Redl60618fa2011-03-12 11:50:43 +00005717 EPI.ExceptionSpecType = ExceptSpec.getExceptionSpecType();
John McCalle23cf432010-12-14 08:05:40 +00005718 EPI.NumExceptions = ExceptSpec.size();
5719 EPI.Exceptions = ExceptSpec.data();
Douglas Gregord3c35902010-07-01 16:36:15 +00005720 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005721 SourceLocation ClassLoc = ClassDecl->getLocation();
5722 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregord3c35902010-07-01 16:36:15 +00005723 CXXMethodDecl *CopyAssignment
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005724 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
John McCalle23cf432010-12-14 08:05:40 +00005725 Context.getFunctionType(RetType, &ArgType, 1, EPI),
Douglas Gregord3c35902010-07-01 16:36:15 +00005726 /*TInfo=*/0, /*isStatic=*/false,
John McCalld931b082010-08-26 03:08:43 +00005727 /*StorageClassAsWritten=*/SC_None,
Douglas Gregorf5251602011-03-08 17:10:18 +00005728 /*isInline=*/true,
5729 SourceLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00005730 CopyAssignment->setAccess(AS_public);
5731 CopyAssignment->setImplicit();
5732 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Douglas Gregord3c35902010-07-01 16:36:15 +00005733
5734 // Add the parameter to the operator.
5735 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005736 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregord3c35902010-07-01 16:36:15 +00005737 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00005738 SC_None,
5739 SC_None, 0);
Douglas Gregord3c35902010-07-01 16:36:15 +00005740 CopyAssignment->setParams(&FromParam, 1);
5741
Douglas Gregora376d102010-07-02 21:50:04 +00005742 // Note that we have added this copy-assignment operator.
Douglas Gregora376d102010-07-02 21:50:04 +00005743 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
5744
Douglas Gregor23c94db2010-07-02 17:43:08 +00005745 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora376d102010-07-02 21:50:04 +00005746 PushOnScopeChains(CopyAssignment, S, false);
5747 ClassDecl->addDecl(CopyAssignment);
Douglas Gregord3c35902010-07-01 16:36:15 +00005748
5749 AddOverriddenMethods(ClassDecl, CopyAssignment);
5750 return CopyAssignment;
5751}
5752
Douglas Gregor06a9f362010-05-01 20:49:11 +00005753void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
5754 CXXMethodDecl *CopyAssignOperator) {
5755 assert((CopyAssignOperator->isImplicit() &&
5756 CopyAssignOperator->isOverloadedOperator() &&
5757 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Douglas Gregorc070cc62010-06-17 23:14:26 +00005758 !CopyAssignOperator->isUsed(false)) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00005759 "DefineImplicitCopyAssignment called for wrong function");
5760
5761 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
5762
5763 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
5764 CopyAssignOperator->setInvalidDecl();
5765 return;
5766 }
5767
5768 CopyAssignOperator->setUsed();
5769
5770 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00005771 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005772
5773 // C++0x [class.copy]p30:
5774 // The implicitly-defined or explicitly-defaulted copy assignment operator
5775 // for a non-union class X performs memberwise copy assignment of its
5776 // subobjects. The direct base classes of X are assigned first, in the
5777 // order of their declaration in the base-specifier-list, and then the
5778 // immediate non-static data members of X are assigned, in the order in
5779 // which they were declared in the class definition.
5780
5781 // The statements that form the synthesized function body.
John McCallca0408f2010-08-23 06:44:23 +00005782 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005783
5784 // The parameter for the "other" object, which we are copying from.
5785 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
5786 Qualifiers OtherQuals = Other->getType().getQualifiers();
5787 QualType OtherRefType = Other->getType();
5788 if (const LValueReferenceType *OtherRef
5789 = OtherRefType->getAs<LValueReferenceType>()) {
5790 OtherRefType = OtherRef->getPointeeType();
5791 OtherQuals = OtherRefType.getQualifiers();
5792 }
5793
5794 // Our location for everything implicitly-generated.
5795 SourceLocation Loc = CopyAssignOperator->getLocation();
5796
5797 // Construct a reference to the "other" object. We'll be using this
5798 // throughout the generated ASTs.
John McCall09431682010-11-18 19:01:18 +00005799 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00005800 assert(OtherRef && "Reference to parameter cannot fail!");
5801
5802 // Construct the "this" pointer. We'll be using this throughout the generated
5803 // ASTs.
5804 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
5805 assert(This && "Reference to this cannot fail!");
5806
5807 // Assign base classes.
5808 bool Invalid = false;
5809 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5810 E = ClassDecl->bases_end(); Base != E; ++Base) {
5811 // Form the assignment:
5812 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
5813 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00005814 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00005815 Invalid = true;
5816 continue;
5817 }
5818
John McCallf871d0c2010-08-07 06:22:56 +00005819 CXXCastPath BasePath;
5820 BasePath.push_back(Base);
5821
Douglas Gregor06a9f362010-05-01 20:49:11 +00005822 // Construct the "from" expression, which is an implicit cast to the
5823 // appropriately-qualified base type.
John McCall3fa5cae2010-10-26 07:05:15 +00005824 Expr *From = OtherRef;
John Wiegley429bb272011-04-08 18:41:53 +00005825 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
5826 CK_UncheckedDerivedToBase,
5827 VK_LValue, &BasePath).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00005828
5829 // Dereference "this".
John McCall5baba9d2010-08-25 10:28:54 +00005830 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005831
5832 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley429bb272011-04-08 18:41:53 +00005833 To = ImpCastExprToType(To.take(),
5834 Context.getCVRQualifiedType(BaseType,
5835 CopyAssignOperator->getTypeQualifiers()),
5836 CK_UncheckedDerivedToBase,
5837 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005838
5839 // Build the copy.
John McCall60d7b3a2010-08-24 06:29:42 +00005840 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00005841 To.get(), From,
5842 /*CopyingBaseSubobject=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005843 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00005844 Diag(CurrentLocation, diag::note_member_synthesized_at)
5845 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5846 CopyAssignOperator->setInvalidDecl();
5847 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00005848 }
5849
5850 // Success! Record the copy.
5851 Statements.push_back(Copy.takeAs<Expr>());
5852 }
5853
5854 // \brief Reference to the __builtin_memcpy function.
5855 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00005856 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00005857 Expr *CollectableMemCpyRef = 0;
Douglas Gregor06a9f362010-05-01 20:49:11 +00005858
5859 // Assign non-static members.
5860 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5861 FieldEnd = ClassDecl->field_end();
5862 Field != FieldEnd; ++Field) {
5863 // Check for members of reference type; we can't copy those.
5864 if (Field->getType()->isReferenceType()) {
5865 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
5866 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
5867 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00005868 Diag(CurrentLocation, diag::note_member_synthesized_at)
5869 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005870 Invalid = true;
5871 continue;
5872 }
5873
5874 // Check for members of const-qualified, non-class type.
5875 QualType BaseType = Context.getBaseElementType(Field->getType());
5876 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
5877 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
5878 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
5879 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00005880 Diag(CurrentLocation, diag::note_member_synthesized_at)
5881 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005882 Invalid = true;
5883 continue;
5884 }
5885
5886 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00005887 if (FieldType->isIncompleteArrayType()) {
5888 assert(ClassDecl->hasFlexibleArrayMember() &&
5889 "Incomplete array type is not valid");
5890 continue;
5891 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00005892
5893 // Build references to the field in the object we're copying from and to.
5894 CXXScopeSpec SS; // Intentionally empty
5895 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
5896 LookupMemberName);
5897 MemberLookup.addDecl(*Field);
5898 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00005899 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall09431682010-11-18 19:01:18 +00005900 Loc, /*IsArrow=*/false,
5901 SS, 0, MemberLookup, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00005902 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall09431682010-11-18 19:01:18 +00005903 Loc, /*IsArrow=*/true,
5904 SS, 0, MemberLookup, 0);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005905 assert(!From.isInvalid() && "Implicit field reference cannot fail");
5906 assert(!To.isInvalid() && "Implicit field reference cannot fail");
5907
5908 // If the field should be copied with __builtin_memcpy rather than via
5909 // explicit assignments, do so. This optimization only applies for arrays
5910 // of scalars and arrays of class type with trivial copy-assignment
5911 // operators.
5912 if (FieldType->isArrayType() &&
5913 (!BaseType->isRecordType() ||
5914 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl())
5915 ->hasTrivialCopyAssignment())) {
5916 // Compute the size of the memory buffer to be copied.
5917 QualType SizeType = Context.getSizeType();
5918 llvm::APInt Size(Context.getTypeSize(SizeType),
5919 Context.getTypeSizeInChars(BaseType).getQuantity());
5920 for (const ConstantArrayType *Array
5921 = Context.getAsConstantArrayType(FieldType);
5922 Array;
5923 Array = Context.getAsConstantArrayType(Array->getElementType())) {
Jay Foad9f71a8f2010-12-07 08:25:34 +00005924 llvm::APInt ArraySize
5925 = Array->getSize().zextOrTrunc(Size.getBitWidth());
Douglas Gregor06a9f362010-05-01 20:49:11 +00005926 Size *= ArraySize;
5927 }
5928
5929 // Take the address of the field references for "from" and "to".
John McCall2de56d12010-08-25 11:45:40 +00005930 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
5931 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00005932
5933 bool NeedsCollectableMemCpy =
5934 (BaseType->isRecordType() &&
5935 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
5936
5937 if (NeedsCollectableMemCpy) {
5938 if (!CollectableMemCpyRef) {
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00005939 // Create a reference to the __builtin_objc_memmove_collectable function.
5940 LookupResult R(*this,
5941 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00005942 Loc, LookupOrdinaryName);
5943 LookupName(R, TUScope, true);
5944
5945 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
5946 if (!CollectableMemCpy) {
5947 // Something went horribly wrong earlier, and we will have
5948 // complained about it.
5949 Invalid = true;
5950 continue;
5951 }
5952
5953 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
5954 CollectableMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00005955 VK_LValue, Loc, 0).take();
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00005956 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
5957 }
5958 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00005959 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00005960 else if (!BuiltinMemCpyRef) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00005961 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
5962 LookupOrdinaryName);
5963 LookupName(R, TUScope, true);
5964
5965 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
5966 if (!BuiltinMemCpy) {
5967 // Something went horribly wrong earlier, and we will have complained
5968 // about it.
5969 Invalid = true;
5970 continue;
5971 }
5972
5973 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
5974 BuiltinMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00005975 VK_LValue, Loc, 0).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00005976 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
5977 }
5978
John McCallca0408f2010-08-23 06:44:23 +00005979 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005980 CallArgs.push_back(To.takeAs<Expr>());
5981 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00005982 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCall60d7b3a2010-08-24 06:29:42 +00005983 ExprResult Call = ExprError();
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005984 if (NeedsCollectableMemCpy)
5985 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00005986 CollectableMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005987 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00005988 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005989 else
5990 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00005991 BuiltinMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005992 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00005993 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005994
Douglas Gregor06a9f362010-05-01 20:49:11 +00005995 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
5996 Statements.push_back(Call.takeAs<Expr>());
5997 continue;
5998 }
5999
6000 // Build the copy of this field.
John McCall60d7b3a2010-08-24 06:29:42 +00006001 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
John McCall9ae2f072010-08-23 23:25:46 +00006002 To.get(), From.get(),
Douglas Gregor6cdc1612010-05-04 15:20:55 +00006003 /*CopyingBaseSubobject=*/false);
Douglas Gregor06a9f362010-05-01 20:49:11 +00006004 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00006005 Diag(CurrentLocation, diag::note_member_synthesized_at)
6006 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
6007 CopyAssignOperator->setInvalidDecl();
6008 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00006009 }
6010
6011 // Success! Record the copy.
6012 Statements.push_back(Copy.takeAs<Stmt>());
6013 }
6014
6015 if (!Invalid) {
6016 // Add a "return *this;"
John McCall2de56d12010-08-25 11:45:40 +00006017 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00006018
John McCall60d7b3a2010-08-24 06:29:42 +00006019 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00006020 if (Return.isInvalid())
6021 Invalid = true;
6022 else {
6023 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00006024
6025 if (Trap.hasErrorOccurred()) {
6026 Diag(CurrentLocation, diag::note_member_synthesized_at)
6027 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
6028 Invalid = true;
6029 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00006030 }
6031 }
6032
6033 if (Invalid) {
6034 CopyAssignOperator->setInvalidDecl();
6035 return;
6036 }
6037
John McCall60d7b3a2010-08-24 06:29:42 +00006038 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
Douglas Gregor06a9f362010-05-01 20:49:11 +00006039 /*isStmtExpr=*/false);
6040 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
6041 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redl58a2cd82011-04-24 16:28:06 +00006042
6043 if (ASTMutationListener *L = getASTMutationListener()) {
6044 L->CompletedImplicitDefinition(CopyAssignOperator);
6045 }
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00006046}
6047
Douglas Gregor23c94db2010-07-02 17:43:08 +00006048CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
6049 CXXRecordDecl *ClassDecl) {
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00006050 // C++ [class.copy]p4:
6051 // If the class definition does not explicitly declare a copy
6052 // constructor, one is declared implicitly.
6053
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00006054 // C++ [class.copy]p5:
6055 // The implicitly-declared copy constructor for a class X will
6056 // have the form
6057 //
6058 // X::X(const X&)
6059 //
6060 // if
6061 bool HasConstCopyConstructor = true;
6062
6063 // -- each direct or virtual base class B of X has a copy
6064 // constructor whose first parameter is of type const B& or
6065 // const volatile B&, and
6066 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
6067 BaseEnd = ClassDecl->bases_end();
6068 HasConstCopyConstructor && Base != BaseEnd;
6069 ++Base) {
Douglas Gregor598a8542010-07-01 18:27:03 +00006070 // Virtual bases are handled below.
6071 if (Base->isVirtual())
6072 continue;
6073
Douglas Gregor22584312010-07-02 23:41:54 +00006074 CXXRecordDecl *BaseClassDecl
Douglas Gregor598a8542010-07-01 18:27:03 +00006075 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00006076 if (!BaseClassDecl->hasDeclaredCopyConstructor())
6077 DeclareImplicitCopyConstructor(BaseClassDecl);
6078
Douglas Gregor598a8542010-07-01 18:27:03 +00006079 HasConstCopyConstructor
6080 = BaseClassDecl->hasConstCopyConstructor(Context);
6081 }
6082
6083 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
6084 BaseEnd = ClassDecl->vbases_end();
6085 HasConstCopyConstructor && Base != BaseEnd;
6086 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00006087 CXXRecordDecl *BaseClassDecl
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00006088 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00006089 if (!BaseClassDecl->hasDeclaredCopyConstructor())
6090 DeclareImplicitCopyConstructor(BaseClassDecl);
6091
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00006092 HasConstCopyConstructor
6093 = BaseClassDecl->hasConstCopyConstructor(Context);
6094 }
6095
6096 // -- for all the nonstatic data members of X that are of a
6097 // class type M (or array thereof), each such class type
6098 // has a copy constructor whose first parameter is of type
6099 // const M& or const volatile M&.
6100 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
6101 FieldEnd = ClassDecl->field_end();
6102 HasConstCopyConstructor && Field != FieldEnd;
6103 ++Field) {
Douglas Gregor598a8542010-07-01 18:27:03 +00006104 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00006105 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregor22584312010-07-02 23:41:54 +00006106 CXXRecordDecl *FieldClassDecl
Douglas Gregor598a8542010-07-01 18:27:03 +00006107 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00006108 if (!FieldClassDecl->hasDeclaredCopyConstructor())
6109 DeclareImplicitCopyConstructor(FieldClassDecl);
6110
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00006111 HasConstCopyConstructor
Douglas Gregor598a8542010-07-01 18:27:03 +00006112 = FieldClassDecl->hasConstCopyConstructor(Context);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00006113 }
6114 }
6115
6116 // Otherwise, the implicitly declared copy constructor will have
6117 // the form
6118 //
6119 // X::X(X&)
6120 QualType ClassType = Context.getTypeDeclType(ClassDecl);
6121 QualType ArgType = ClassType;
6122 if (HasConstCopyConstructor)
6123 ArgType = ArgType.withConst();
6124 ArgType = Context.getLValueReferenceType(ArgType);
6125
Douglas Gregor0d405db2010-07-01 20:59:04 +00006126 // C++ [except.spec]p14:
6127 // An implicitly declared special member function (Clause 12) shall have an
6128 // exception-specification. [...]
6129 ImplicitExceptionSpecification ExceptSpec(Context);
6130 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
6131 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
6132 BaseEnd = ClassDecl->bases_end();
6133 Base != BaseEnd;
6134 ++Base) {
6135 // Virtual bases are handled below.
6136 if (Base->isVirtual())
6137 continue;
6138
Douglas Gregor22584312010-07-02 23:41:54 +00006139 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00006140 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00006141 if (!BaseClassDecl->hasDeclaredCopyConstructor())
6142 DeclareImplicitCopyConstructor(BaseClassDecl);
6143
Douglas Gregor0d405db2010-07-01 20:59:04 +00006144 if (CXXConstructorDecl *CopyConstructor
6145 = BaseClassDecl->getCopyConstructor(Context, Quals))
6146 ExceptSpec.CalledDecl(CopyConstructor);
6147 }
6148 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
6149 BaseEnd = ClassDecl->vbases_end();
6150 Base != BaseEnd;
6151 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00006152 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00006153 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00006154 if (!BaseClassDecl->hasDeclaredCopyConstructor())
6155 DeclareImplicitCopyConstructor(BaseClassDecl);
6156
Douglas Gregor0d405db2010-07-01 20:59:04 +00006157 if (CXXConstructorDecl *CopyConstructor
6158 = BaseClassDecl->getCopyConstructor(Context, Quals))
6159 ExceptSpec.CalledDecl(CopyConstructor);
6160 }
6161 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
6162 FieldEnd = ClassDecl->field_end();
6163 Field != FieldEnd;
6164 ++Field) {
6165 QualType FieldType = Context.getBaseElementType((*Field)->getType());
6166 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregor22584312010-07-02 23:41:54 +00006167 CXXRecordDecl *FieldClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00006168 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00006169 if (!FieldClassDecl->hasDeclaredCopyConstructor())
6170 DeclareImplicitCopyConstructor(FieldClassDecl);
6171
Douglas Gregor0d405db2010-07-01 20:59:04 +00006172 if (CXXConstructorDecl *CopyConstructor
6173 = FieldClassDecl->getCopyConstructor(Context, Quals))
6174 ExceptSpec.CalledDecl(CopyConstructor);
6175 }
6176 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00006177
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00006178 // An implicitly-declared copy constructor is an inline public
6179 // member of its class.
John McCalle23cf432010-12-14 08:05:40 +00006180 FunctionProtoType::ExtProtoInfo EPI;
Sebastian Redl60618fa2011-03-12 11:50:43 +00006181 EPI.ExceptionSpecType = ExceptSpec.getExceptionSpecType();
John McCalle23cf432010-12-14 08:05:40 +00006182 EPI.NumExceptions = ExceptSpec.size();
6183 EPI.Exceptions = ExceptSpec.data();
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00006184 DeclarationName Name
6185 = Context.DeclarationNames.getCXXConstructorName(
6186 Context.getCanonicalType(ClassType));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006187 SourceLocation ClassLoc = ClassDecl->getLocation();
6188 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00006189 CXXConstructorDecl *CopyConstructor
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006190 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00006191 Context.getFunctionType(Context.VoidTy,
John McCalle23cf432010-12-14 08:05:40 +00006192 &ArgType, 1, EPI),
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00006193 /*TInfo=*/0,
6194 /*isExplicit=*/false,
6195 /*isInline=*/true,
Sean Hunt5f802e52011-05-06 00:11:07 +00006196 /*isImplicitlyDeclared=*/true);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00006197 CopyConstructor->setAccess(AS_public);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00006198 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
6199
Douglas Gregor22584312010-07-02 23:41:54 +00006200 // Note that we have declared this constructor.
Douglas Gregor22584312010-07-02 23:41:54 +00006201 ++ASTContext::NumImplicitCopyConstructorsDeclared;
6202
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00006203 // Add the parameter to the constructor.
6204 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006205 ClassLoc, ClassLoc,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00006206 /*IdentifierInfo=*/0,
6207 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00006208 SC_None,
6209 SC_None, 0);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00006210 CopyConstructor->setParams(&FromParam, 1);
Douglas Gregor23c94db2010-07-02 17:43:08 +00006211 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor22584312010-07-02 23:41:54 +00006212 PushOnScopeChains(CopyConstructor, S, false);
6213 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00006214
6215 return CopyConstructor;
6216}
6217
Fariborz Jahanian485f0872009-06-22 23:34:40 +00006218void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
6219 CXXConstructorDecl *CopyConstructor,
6220 unsigned TypeQuals) {
Mike Stump1eb44332009-09-09 15:08:12 +00006221 assert((CopyConstructor->isImplicit() &&
Douglas Gregor9e9199d2009-12-22 00:34:07 +00006222 CopyConstructor->isCopyConstructor(TypeQuals) &&
Douglas Gregorc070cc62010-06-17 23:14:26 +00006223 !CopyConstructor->isUsed(false)) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00006224 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00006225
Anders Carlsson63010a72010-04-23 16:24:12 +00006226 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00006227 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006228
Douglas Gregor39957dc2010-05-01 15:04:51 +00006229 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00006230 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006231
Sean Huntcbb67482011-01-08 20:30:50 +00006232 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00006233 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00006234 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00006235 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00006236 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00006237 } else {
6238 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
6239 CopyConstructor->getLocation(),
6240 MultiStmtArg(*this, 0, 0),
6241 /*isStmtExpr=*/false)
6242 .takeAs<Stmt>());
Anders Carlsson8e142cc2010-04-25 00:52:09 +00006243 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00006244
6245 CopyConstructor->setUsed();
Sebastian Redl58a2cd82011-04-24 16:28:06 +00006246
6247 if (ASTMutationListener *L = getASTMutationListener()) {
6248 L->CompletedImplicitDefinition(CopyConstructor);
6249 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +00006250}
6251
John McCall60d7b3a2010-08-24 06:29:42 +00006252ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00006253Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00006254 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00006255 MultiExprArg ExprArgs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006256 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00006257 unsigned ConstructKind,
6258 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00006259 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00006260
Douglas Gregor2f599792010-04-02 18:24:57 +00006261 // C++0x [class.copy]p34:
6262 // When certain criteria are met, an implementation is allowed to
6263 // omit the copy/move construction of a class object, even if the
6264 // copy/move constructor and/or destructor for the object have
6265 // side effects. [...]
6266 // - when a temporary class object that has not been bound to a
6267 // reference (12.2) would be copied/moved to a class object
6268 // with the same cv-unqualified type, the copy/move operation
6269 // can be omitted by constructing the temporary object
6270 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +00006271 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregor70a21de2011-01-27 23:24:55 +00006272 Constructor->isCopyOrMoveConstructor() && ExprArgs.size() >= 1) {
Douglas Gregor2f599792010-04-02 18:24:57 +00006273 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
John McCall558d2ab2010-09-15 10:14:12 +00006274 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00006275 }
Mike Stump1eb44332009-09-09 15:08:12 +00006276
6277 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006278 Elidable, move(ExprArgs), RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00006279 ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00006280}
6281
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00006282/// BuildCXXConstructExpr - Creates a complete call to a constructor,
6283/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00006284ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00006285Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
6286 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00006287 MultiExprArg ExprArgs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006288 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00006289 unsigned ConstructKind,
6290 SourceRange ParenRange) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00006291 unsigned NumExprs = ExprArgs.size();
6292 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00006293
Nick Lewycky909a70d2011-03-25 01:44:32 +00006294 for (specific_attr_iterator<NonNullAttr>
6295 i = Constructor->specific_attr_begin<NonNullAttr>(),
6296 e = Constructor->specific_attr_end<NonNullAttr>(); i != e; ++i) {
6297 const NonNullAttr *NonNull = *i;
6298 CheckNonNullArguments(NonNull, ExprArgs.get(), ConstructLoc);
6299 }
6300
Douglas Gregor7edfb692009-11-23 12:27:39 +00006301 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00006302 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor16006c92009-12-16 18:50:27 +00006303 Constructor, Elidable, Exprs, NumExprs,
John McCall7a1fad32010-08-24 07:32:53 +00006304 RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00006305 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
6306 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00006307}
6308
Mike Stump1eb44332009-09-09 15:08:12 +00006309bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00006310 CXXConstructorDecl *Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00006311 MultiExprArg Exprs) {
Chandler Carruth428edaf2010-10-25 08:47:36 +00006312 // FIXME: Provide the correct paren SourceRange when available.
John McCall60d7b3a2010-08-24 06:29:42 +00006313 ExprResult TempResult =
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00006314 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Chandler Carruth428edaf2010-10-25 08:47:36 +00006315 move(Exprs), false, CXXConstructExpr::CK_Complete,
6316 SourceRange());
Anders Carlssonfe2de492009-08-25 05:18:00 +00006317 if (TempResult.isInvalid())
6318 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00006319
Anders Carlssonda3f4e22009-08-25 05:12:04 +00006320 Expr *Temp = TempResult.takeAs<Expr>();
John McCallb4eb64d2010-10-08 02:01:28 +00006321 CheckImplicitConversions(Temp, VD->getLocation());
Douglas Gregord7f37bf2009-06-22 23:06:13 +00006322 MarkDeclarationReferenced(VD->getLocation(), Constructor);
John McCall4765fa02010-12-06 08:20:24 +00006323 Temp = MaybeCreateExprWithCleanups(Temp);
Douglas Gregor838db382010-02-11 01:19:42 +00006324 VD->setInit(Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00006325
Anders Carlssonfe2de492009-08-25 05:18:00 +00006326 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00006327}
6328
John McCall68c6c9a2010-02-02 09:10:11 +00006329void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00006330 if (VD->isInvalidDecl()) return;
6331
John McCall68c6c9a2010-02-02 09:10:11 +00006332 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00006333 if (ClassDecl->isInvalidDecl()) return;
6334 if (ClassDecl->hasTrivialDestructor()) return;
6335 if (ClassDecl->isDependentContext()) return;
John McCall626e96e2010-08-01 20:20:59 +00006336
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00006337 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
6338 MarkDeclarationReferenced(VD->getLocation(), Destructor);
6339 CheckDestructorAccess(VD->getLocation(), Destructor,
6340 PDiag(diag::err_access_dtor_var)
6341 << VD->getDeclName()
6342 << VD->getType());
Anders Carlsson2b32dad2011-03-24 01:01:41 +00006343
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00006344 if (!VD->hasGlobalStorage()) return;
6345
6346 // Emit warning for non-trivial dtor in global scope (a real global,
6347 // class-static, function-static).
6348 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
6349
6350 // TODO: this should be re-enabled for static locals by !CXAAtExit
6351 if (!VD->isStaticLocal())
6352 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00006353}
6354
Mike Stump1eb44332009-09-09 15:08:12 +00006355/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006356/// ActOnDeclarator, when a C++ direct initializer is present.
6357/// e.g: "int x(1);"
John McCalld226f652010-08-21 09:40:31 +00006358void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006359 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +00006360 MultiExprArg Exprs,
Richard Smith34b41d92011-02-20 03:19:35 +00006361 SourceLocation RParenLoc,
6362 bool TypeMayContainAuto) {
Daniel Dunbar51846262009-12-24 19:19:26 +00006363 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006364
6365 // If there is no declaration, there was an error parsing it. Just ignore
6366 // the initializer.
Chris Lattnerb28317a2009-03-28 19:18:32 +00006367 if (RealDecl == 0)
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006368 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006369
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006370 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
6371 if (!VDecl) {
6372 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
6373 RealDecl->setInvalidDecl();
6374 return;
6375 }
6376
Richard Smith34b41d92011-02-20 03:19:35 +00006377 // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
6378 if (TypeMayContainAuto && VDecl->getType()->getContainedAutoType()) {
Richard Smith34b41d92011-02-20 03:19:35 +00006379 // FIXME: n3225 doesn't actually seem to indicate this is ill-formed
6380 if (Exprs.size() > 1) {
6381 Diag(Exprs.get()[1]->getSourceRange().getBegin(),
6382 diag::err_auto_var_init_multiple_expressions)
6383 << VDecl->getDeclName() << VDecl->getType()
6384 << VDecl->getSourceRange();
6385 RealDecl->setInvalidDecl();
6386 return;
6387 }
6388
6389 Expr *Init = Exprs.get()[0];
Richard Smitha085da82011-03-17 16:11:59 +00006390 TypeSourceInfo *DeducedType = 0;
6391 if (!DeduceAutoType(VDecl->getTypeSourceInfo(), Init, DeducedType))
Richard Smith34b41d92011-02-20 03:19:35 +00006392 Diag(VDecl->getLocation(), diag::err_auto_var_deduction_failure)
6393 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
6394 << Init->getSourceRange();
Richard Smitha085da82011-03-17 16:11:59 +00006395 if (!DeducedType) {
Richard Smith34b41d92011-02-20 03:19:35 +00006396 RealDecl->setInvalidDecl();
6397 return;
6398 }
Richard Smitha085da82011-03-17 16:11:59 +00006399 VDecl->setTypeSourceInfo(DeducedType);
6400 VDecl->setType(DeducedType->getType());
Richard Smith34b41d92011-02-20 03:19:35 +00006401
6402 // If this is a redeclaration, check that the type we just deduced matches
6403 // the previously declared type.
6404 if (VarDecl *Old = VDecl->getPreviousDeclaration())
6405 MergeVarDeclTypes(VDecl, Old);
6406 }
6407
Douglas Gregor83ddad32009-08-26 21:14:46 +00006408 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00006409 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006410 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
6411 //
6412 // Clients that want to distinguish between the two forms, can check for
6413 // direct initializer using VarDecl::hasCXXDirectInitializer().
6414 // A major benefit is that clients that don't particularly care about which
6415 // exactly form was it (like the CodeGen) can handle both cases without
6416 // special case code.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00006417
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006418 // C++ 8.5p11:
6419 // The form of initialization (using parentheses or '=') is generally
6420 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00006421 // class type.
6422
Douglas Gregor4dffad62010-02-11 22:55:30 +00006423 if (!VDecl->getType()->isDependentType() &&
6424 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor615c5d42009-03-24 16:43:20 +00006425 diag::err_typecheck_decl_incomplete_type)) {
6426 VDecl->setInvalidDecl();
6427 return;
6428 }
6429
Douglas Gregor90f93822009-12-22 22:17:25 +00006430 // The variable can not have an abstract class type.
6431 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
6432 diag::err_abstract_type_in_decl,
6433 AbstractVariableType))
6434 VDecl->setInvalidDecl();
6435
Sebastian Redl31310a22010-02-01 20:16:42 +00006436 const VarDecl *Def;
6437 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregor90f93822009-12-22 22:17:25 +00006438 Diag(VDecl->getLocation(), diag::err_redefinition)
6439 << VDecl->getDeclName();
6440 Diag(Def->getLocation(), diag::note_previous_definition);
6441 VDecl->setInvalidDecl();
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00006442 return;
6443 }
Douglas Gregor4dffad62010-02-11 22:55:30 +00006444
Douglas Gregor3a91abf2010-08-24 05:27:49 +00006445 // C++ [class.static.data]p4
6446 // If a static data member is of const integral or const
6447 // enumeration type, its declaration in the class definition can
6448 // specify a constant-initializer which shall be an integral
6449 // constant expression (5.19). In that case, the member can appear
6450 // in integral constant expressions. The member shall still be
6451 // defined in a namespace scope if it is used in the program and the
6452 // namespace scope definition shall not contain an initializer.
6453 //
6454 // We already performed a redefinition check above, but for static
6455 // data members we also need to check whether there was an in-class
6456 // declaration with an initializer.
6457 const VarDecl* PrevInit = 0;
6458 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
6459 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
6460 Diag(PrevInit->getLocation(), diag::note_previous_definition);
6461 return;
6462 }
6463
Douglas Gregora31040f2010-12-16 01:31:22 +00006464 bool IsDependent = false;
6465 for (unsigned I = 0, N = Exprs.size(); I != N; ++I) {
6466 if (DiagnoseUnexpandedParameterPack(Exprs.get()[I], UPPC_Expression)) {
6467 VDecl->setInvalidDecl();
6468 return;
6469 }
6470
6471 if (Exprs.get()[I]->isTypeDependent())
6472 IsDependent = true;
6473 }
6474
Douglas Gregor4dffad62010-02-11 22:55:30 +00006475 // If either the declaration has a dependent type or if any of the
6476 // expressions is type-dependent, we represent the initialization
6477 // via a ParenListExpr for later use during template instantiation.
Douglas Gregora31040f2010-12-16 01:31:22 +00006478 if (VDecl->getType()->isDependentType() || IsDependent) {
Douglas Gregor4dffad62010-02-11 22:55:30 +00006479 // Let clients know that initialization was done with a direct initializer.
6480 VDecl->setCXXDirectInitializer(true);
6481
6482 // Store the initialization expressions as a ParenListExpr.
6483 unsigned NumExprs = Exprs.size();
6484 VDecl->setInit(new (Context) ParenListExpr(Context, LParenLoc,
6485 (Expr **)Exprs.release(),
6486 NumExprs, RParenLoc));
6487 return;
6488 }
Douglas Gregor90f93822009-12-22 22:17:25 +00006489
6490 // Capture the variable that is being initialized and the style of
6491 // initialization.
6492 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
6493
6494 // FIXME: Poor source location information.
6495 InitializationKind Kind
6496 = InitializationKind::CreateDirect(VDecl->getLocation(),
6497 LParenLoc, RParenLoc);
6498
6499 InitializationSequence InitSeq(*this, Entity, Kind,
John McCall9ae2f072010-08-23 23:25:46 +00006500 Exprs.get(), Exprs.size());
John McCall60d7b3a2010-08-24 06:29:42 +00006501 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
Douglas Gregor90f93822009-12-22 22:17:25 +00006502 if (Result.isInvalid()) {
6503 VDecl->setInvalidDecl();
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006504 return;
6505 }
John McCallb4eb64d2010-10-08 02:01:28 +00006506
6507 CheckImplicitConversions(Result.get(), LParenLoc);
Douglas Gregor90f93822009-12-22 22:17:25 +00006508
Douglas Gregor53c374f2010-12-07 00:41:46 +00006509 Result = MaybeCreateExprWithCleanups(Result);
Douglas Gregor838db382010-02-11 01:19:42 +00006510 VDecl->setInit(Result.takeAs<Expr>());
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006511 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00006512
John McCall2998d6b2011-01-19 11:48:09 +00006513 CheckCompleteVariableDeclaration(VDecl);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006514}
Douglas Gregor27c8dc02008-10-29 00:13:59 +00006515
Douglas Gregor39da0b82009-09-09 23:08:42 +00006516/// \brief Given a constructor and the set of arguments provided for the
6517/// constructor, convert the arguments and add any required default arguments
6518/// to form a proper call to this constructor.
6519///
6520/// \returns true if an error occurred, false otherwise.
6521bool
6522Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
6523 MultiExprArg ArgsPtr,
6524 SourceLocation Loc,
John McCallca0408f2010-08-23 06:44:23 +00006525 ASTOwningVector<Expr*> &ConvertedArgs) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00006526 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
6527 unsigned NumArgs = ArgsPtr.size();
6528 Expr **Args = (Expr **)ArgsPtr.get();
6529
6530 const FunctionProtoType *Proto
6531 = Constructor->getType()->getAs<FunctionProtoType>();
6532 assert(Proto && "Constructor without a prototype?");
6533 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00006534
6535 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00006536 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00006537 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00006538 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00006539 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00006540
6541 VariadicCallType CallType =
6542 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
6543 llvm::SmallVector<Expr *, 8> AllArgs;
6544 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
6545 Proto, 0, Args, NumArgs, AllArgs,
6546 CallType);
6547 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
6548 ConvertedArgs.push_back(AllArgs[i]);
6549 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00006550}
6551
Anders Carlsson20d45d22009-12-12 00:32:00 +00006552static inline bool
6553CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
6554 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00006555 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +00006556 if (isa<NamespaceDecl>(DC)) {
6557 return SemaRef.Diag(FnDecl->getLocation(),
6558 diag::err_operator_new_delete_declared_in_namespace)
6559 << FnDecl->getDeclName();
6560 }
6561
6562 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +00006563 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00006564 return SemaRef.Diag(FnDecl->getLocation(),
6565 diag::err_operator_new_delete_declared_static)
6566 << FnDecl->getDeclName();
6567 }
6568
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00006569 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00006570}
6571
Anders Carlsson156c78e2009-12-13 17:53:43 +00006572static inline bool
6573CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
6574 CanQualType ExpectedResultType,
6575 CanQualType ExpectedFirstParamType,
6576 unsigned DependentParamTypeDiag,
6577 unsigned InvalidParamTypeDiag) {
6578 QualType ResultType =
6579 FnDecl->getType()->getAs<FunctionType>()->getResultType();
6580
6581 // Check that the result type is not dependent.
6582 if (ResultType->isDependentType())
6583 return SemaRef.Diag(FnDecl->getLocation(),
6584 diag::err_operator_new_delete_dependent_result_type)
6585 << FnDecl->getDeclName() << ExpectedResultType;
6586
6587 // Check that the result type is what we expect.
6588 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
6589 return SemaRef.Diag(FnDecl->getLocation(),
6590 diag::err_operator_new_delete_invalid_result_type)
6591 << FnDecl->getDeclName() << ExpectedResultType;
6592
6593 // A function template must have at least 2 parameters.
6594 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
6595 return SemaRef.Diag(FnDecl->getLocation(),
6596 diag::err_operator_new_delete_template_too_few_parameters)
6597 << FnDecl->getDeclName();
6598
6599 // The function decl must have at least 1 parameter.
6600 if (FnDecl->getNumParams() == 0)
6601 return SemaRef.Diag(FnDecl->getLocation(),
6602 diag::err_operator_new_delete_too_few_parameters)
6603 << FnDecl->getDeclName();
6604
6605 // Check the the first parameter type is not dependent.
6606 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
6607 if (FirstParamType->isDependentType())
6608 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
6609 << FnDecl->getDeclName() << ExpectedFirstParamType;
6610
6611 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +00006612 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +00006613 ExpectedFirstParamType)
6614 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
6615 << FnDecl->getDeclName() << ExpectedFirstParamType;
6616
6617 return false;
6618}
6619
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00006620static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +00006621CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00006622 // C++ [basic.stc.dynamic.allocation]p1:
6623 // A program is ill-formed if an allocation function is declared in a
6624 // namespace scope other than global scope or declared static in global
6625 // scope.
6626 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
6627 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +00006628
6629 CanQualType SizeTy =
6630 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
6631
6632 // C++ [basic.stc.dynamic.allocation]p1:
6633 // The return type shall be void*. The first parameter shall have type
6634 // std::size_t.
6635 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
6636 SizeTy,
6637 diag::err_operator_new_dependent_param_type,
6638 diag::err_operator_new_param_type))
6639 return true;
6640
6641 // C++ [basic.stc.dynamic.allocation]p1:
6642 // The first parameter shall not have an associated default argument.
6643 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +00006644 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +00006645 diag::err_operator_new_default_arg)
6646 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
6647
6648 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +00006649}
6650
6651static bool
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00006652CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
6653 // C++ [basic.stc.dynamic.deallocation]p1:
6654 // A program is ill-formed if deallocation functions are declared in a
6655 // namespace scope other than global scope or declared static in global
6656 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +00006657 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
6658 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00006659
6660 // C++ [basic.stc.dynamic.deallocation]p2:
6661 // Each deallocation function shall return void and its first parameter
6662 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +00006663 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
6664 SemaRef.Context.VoidPtrTy,
6665 diag::err_operator_delete_dependent_param_type,
6666 diag::err_operator_delete_param_type))
6667 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00006668
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00006669 return false;
6670}
6671
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006672/// CheckOverloadedOperatorDeclaration - Check whether the declaration
6673/// of this overloaded operator is well-formed. If so, returns false;
6674/// otherwise, emits appropriate diagnostics and returns true.
6675bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00006676 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006677 "Expected an overloaded operator declaration");
6678
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006679 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
6680
Mike Stump1eb44332009-09-09 15:08:12 +00006681 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006682 // The allocation and deallocation functions, operator new,
6683 // operator new[], operator delete and operator delete[], are
6684 // described completely in 3.7.3. The attributes and restrictions
6685 // found in the rest of this subclause do not apply to them unless
6686 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +00006687 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00006688 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00006689
Anders Carlssona3ccda52009-12-12 00:26:23 +00006690 if (Op == OO_New || Op == OO_Array_New)
6691 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006692
6693 // C++ [over.oper]p6:
6694 // An operator function shall either be a non-static member
6695 // function or be a non-member function and have at least one
6696 // parameter whose type is a class, a reference to a class, an
6697 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00006698 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
6699 if (MethodDecl->isStatic())
6700 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00006701 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006702 } else {
6703 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00006704 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
6705 ParamEnd = FnDecl->param_end();
6706 Param != ParamEnd; ++Param) {
6707 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00006708 if (ParamType->isDependentType() || ParamType->isRecordType() ||
6709 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006710 ClassOrEnumParam = true;
6711 break;
6712 }
6713 }
6714
Douglas Gregor43c7bad2008-11-17 16:14:12 +00006715 if (!ClassOrEnumParam)
6716 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00006717 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00006718 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006719 }
6720
6721 // C++ [over.oper]p8:
6722 // An operator function cannot have default arguments (8.3.6),
6723 // except where explicitly stated below.
6724 //
Mike Stump1eb44332009-09-09 15:08:12 +00006725 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006726 // (C++ [over.call]p1).
6727 if (Op != OO_Call) {
6728 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
6729 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +00006730 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00006731 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00006732 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +00006733 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006734 }
6735 }
6736
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00006737 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
6738 { false, false, false }
6739#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
6740 , { Unary, Binary, MemberOnly }
6741#include "clang/Basic/OperatorKinds.def"
6742 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006743
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00006744 bool CanBeUnaryOperator = OperatorUses[Op][0];
6745 bool CanBeBinaryOperator = OperatorUses[Op][1];
6746 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006747
6748 // C++ [over.oper]p8:
6749 // [...] Operator functions cannot have more or fewer parameters
6750 // than the number required for the corresponding operator, as
6751 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00006752 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00006753 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006754 if (Op != OO_Call &&
6755 ((NumParams == 1 && !CanBeUnaryOperator) ||
6756 (NumParams == 2 && !CanBeBinaryOperator) ||
6757 (NumParams < 1) || (NumParams > 2))) {
6758 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00006759 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00006760 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00006761 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00006762 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00006763 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00006764 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00006765 assert(CanBeBinaryOperator &&
6766 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00006767 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00006768 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006769
Chris Lattner416e46f2008-11-21 07:57:12 +00006770 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00006771 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006772 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00006773
Douglas Gregor43c7bad2008-11-17 16:14:12 +00006774 // Overloaded operators other than operator() cannot be variadic.
6775 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00006776 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00006777 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00006778 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006779 }
6780
6781 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00006782 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
6783 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00006784 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00006785 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006786 }
6787
6788 // C++ [over.inc]p1:
6789 // The user-defined function called operator++ implements the
6790 // prefix and postfix ++ operator. If this function is a member
6791 // function with no parameters, or a non-member function with one
6792 // parameter of class or enumeration type, it defines the prefix
6793 // increment operator ++ for objects of that type. If the function
6794 // is a member function with one parameter (which shall be of type
6795 // int) or a non-member function with two parameters (the second
6796 // of which shall be of type int), it defines the postfix
6797 // increment operator ++ for objects of that type.
6798 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
6799 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
6800 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00006801 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006802 ParamIsInt = BT->getKind() == BuiltinType::Int;
6803
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00006804 if (!ParamIsInt)
6805 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00006806 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00006807 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006808 }
6809
Douglas Gregor43c7bad2008-11-17 16:14:12 +00006810 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006811}
Chris Lattner5a003a42008-12-17 07:09:26 +00006812
Sean Hunta6c058d2010-01-13 09:01:02 +00006813/// CheckLiteralOperatorDeclaration - Check whether the declaration
6814/// of this literal operator function is well-formed. If so, returns
6815/// false; otherwise, emits appropriate diagnostics and returns true.
6816bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
6817 DeclContext *DC = FnDecl->getDeclContext();
6818 Decl::Kind Kind = DC->getDeclKind();
6819 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
6820 Kind != Decl::LinkageSpec) {
6821 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
6822 << FnDecl->getDeclName();
6823 return true;
6824 }
6825
6826 bool Valid = false;
6827
Sean Hunt216c2782010-04-07 23:11:06 +00006828 // template <char...> type operator "" name() is the only valid template
6829 // signature, and the only valid signature with no parameters.
6830 if (FnDecl->param_size() == 0) {
6831 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
6832 // Must have only one template parameter
6833 TemplateParameterList *Params = TpDecl->getTemplateParameters();
6834 if (Params->size() == 1) {
6835 NonTypeTemplateParmDecl *PmDecl =
6836 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +00006837
Sean Hunt216c2782010-04-07 23:11:06 +00006838 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +00006839 if (PmDecl && PmDecl->isTemplateParameterPack() &&
6840 Context.hasSameType(PmDecl->getType(), Context.CharTy))
6841 Valid = true;
6842 }
6843 }
6844 } else {
Sean Hunta6c058d2010-01-13 09:01:02 +00006845 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +00006846 FunctionDecl::param_iterator Param = FnDecl->param_begin();
6847
Sean Hunta6c058d2010-01-13 09:01:02 +00006848 QualType T = (*Param)->getType();
6849
Sean Hunt30019c02010-04-07 22:57:35 +00006850 // unsigned long long int, long double, and any character type are allowed
6851 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +00006852 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
6853 Context.hasSameType(T, Context.LongDoubleTy) ||
6854 Context.hasSameType(T, Context.CharTy) ||
6855 Context.hasSameType(T, Context.WCharTy) ||
6856 Context.hasSameType(T, Context.Char16Ty) ||
6857 Context.hasSameType(T, Context.Char32Ty)) {
6858 if (++Param == FnDecl->param_end())
6859 Valid = true;
6860 goto FinishedParams;
6861 }
6862
Sean Hunt30019c02010-04-07 22:57:35 +00006863 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +00006864 const PointerType *PT = T->getAs<PointerType>();
6865 if (!PT)
6866 goto FinishedParams;
6867 T = PT->getPointeeType();
6868 if (!T.isConstQualified())
6869 goto FinishedParams;
6870 T = T.getUnqualifiedType();
6871
6872 // Move on to the second parameter;
6873 ++Param;
6874
6875 // If there is no second parameter, the first must be a const char *
6876 if (Param == FnDecl->param_end()) {
6877 if (Context.hasSameType(T, Context.CharTy))
6878 Valid = true;
6879 goto FinishedParams;
6880 }
6881
6882 // const char *, const wchar_t*, const char16_t*, and const char32_t*
6883 // are allowed as the first parameter to a two-parameter function
6884 if (!(Context.hasSameType(T, Context.CharTy) ||
6885 Context.hasSameType(T, Context.WCharTy) ||
6886 Context.hasSameType(T, Context.Char16Ty) ||
6887 Context.hasSameType(T, Context.Char32Ty)))
6888 goto FinishedParams;
6889
6890 // The second and final parameter must be an std::size_t
6891 T = (*Param)->getType().getUnqualifiedType();
6892 if (Context.hasSameType(T, Context.getSizeType()) &&
6893 ++Param == FnDecl->param_end())
6894 Valid = true;
6895 }
6896
6897 // FIXME: This diagnostic is absolutely terrible.
6898FinishedParams:
6899 if (!Valid) {
6900 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
6901 << FnDecl->getDeclName();
6902 return true;
6903 }
6904
6905 return false;
6906}
6907
Douglas Gregor074149e2009-01-05 19:45:36 +00006908/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
6909/// linkage specification, including the language and (if present)
6910/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
6911/// the location of the language string literal, which is provided
6912/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
6913/// the '{' brace. Otherwise, this linkage specification does not
6914/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +00006915Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
6916 SourceLocation LangLoc,
6917 llvm::StringRef Lang,
6918 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00006919 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +00006920 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00006921 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +00006922 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00006923 Language = LinkageSpecDecl::lang_cxx;
6924 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00006925 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +00006926 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +00006927 }
Mike Stump1eb44332009-09-09 15:08:12 +00006928
Chris Lattnercc98eac2008-12-17 07:13:27 +00006929 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +00006930
Douglas Gregor074149e2009-01-05 19:45:36 +00006931 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00006932 ExternLoc, LangLoc, Language);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006933 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00006934 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +00006935 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +00006936}
6937
Abramo Bagnara35f9a192010-07-30 16:47:02 +00006938/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +00006939/// the C++ linkage specification LinkageSpec. If RBraceLoc is
6940/// valid, it's the position of the closing '}' brace in a linkage
6941/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +00006942Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +00006943 Decl *LinkageSpec,
6944 SourceLocation RBraceLoc) {
6945 if (LinkageSpec) {
6946 if (RBraceLoc.isValid()) {
6947 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
6948 LSDecl->setRBraceLoc(RBraceLoc);
6949 }
Douglas Gregor074149e2009-01-05 19:45:36 +00006950 PopDeclContext();
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +00006951 }
Douglas Gregor074149e2009-01-05 19:45:36 +00006952 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00006953}
6954
Douglas Gregord308e622009-05-18 20:51:54 +00006955/// \brief Perform semantic analysis for the variable declaration that
6956/// occurs within a C++ catch clause, returning the newly-created
6957/// variable.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006958VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +00006959 TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006960 SourceLocation StartLoc,
6961 SourceLocation Loc,
6962 IdentifierInfo *Name) {
Douglas Gregord308e622009-05-18 20:51:54 +00006963 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +00006964 QualType ExDeclType = TInfo->getType();
6965
Sebastian Redl4b07b292008-12-22 19:15:10 +00006966 // Arrays and functions decay.
6967 if (ExDeclType->isArrayType())
6968 ExDeclType = Context.getArrayDecayedType(ExDeclType);
6969 else if (ExDeclType->isFunctionType())
6970 ExDeclType = Context.getPointerType(ExDeclType);
6971
6972 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
6973 // The exception-declaration shall not denote a pointer or reference to an
6974 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00006975 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +00006976 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +00006977 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +00006978 Invalid = true;
6979 }
Douglas Gregord308e622009-05-18 20:51:54 +00006980
Douglas Gregora2762912010-03-08 01:47:36 +00006981 // GCC allows catching pointers and references to incomplete types
6982 // as an extension; so do we, but we warn by default.
6983
Sebastian Redl4b07b292008-12-22 19:15:10 +00006984 QualType BaseType = ExDeclType;
6985 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00006986 unsigned DK = diag::err_catch_incomplete;
Douglas Gregora2762912010-03-08 01:47:36 +00006987 bool IncompleteCatchIsInvalid = true;
Ted Kremenek6217b802009-07-29 21:53:49 +00006988 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00006989 BaseType = Ptr->getPointeeType();
6990 Mode = 1;
Douglas Gregora2762912010-03-08 01:47:36 +00006991 DK = diag::ext_catch_incomplete_ptr;
6992 IncompleteCatchIsInvalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +00006993 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00006994 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00006995 BaseType = Ref->getPointeeType();
6996 Mode = 2;
Douglas Gregora2762912010-03-08 01:47:36 +00006997 DK = diag::ext_catch_incomplete_ref;
6998 IncompleteCatchIsInvalid = false;
Sebastian Redl4b07b292008-12-22 19:15:10 +00006999 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00007000 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregora2762912010-03-08 01:47:36 +00007001 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
7002 IncompleteCatchIsInvalid)
Sebastian Redl4b07b292008-12-22 19:15:10 +00007003 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00007004
Mike Stump1eb44332009-09-09 15:08:12 +00007005 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +00007006 RequireNonAbstractType(Loc, ExDeclType,
7007 diag::err_abstract_type_in_decl,
7008 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00007009 Invalid = true;
7010
John McCall5a180392010-07-24 00:37:23 +00007011 // Only the non-fragile NeXT runtime currently supports C++ catches
7012 // of ObjC types, and no runtime supports catching ObjC types by value.
7013 if (!Invalid && getLangOptions().ObjC1) {
7014 QualType T = ExDeclType;
7015 if (const ReferenceType *RT = T->getAs<ReferenceType>())
7016 T = RT->getPointeeType();
7017
7018 if (T->isObjCObjectType()) {
7019 Diag(Loc, diag::err_objc_object_catch);
7020 Invalid = true;
7021 } else if (T->isObjCObjectPointerType()) {
David Chisnall80558d22011-03-20 21:35:39 +00007022 if (!getLangOptions().ObjCNonFragileABI) {
John McCall5a180392010-07-24 00:37:23 +00007023 Diag(Loc, diag::err_objc_pointer_cxx_catch_fragile);
7024 Invalid = true;
7025 }
7026 }
7027 }
7028
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007029 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
7030 ExDeclType, TInfo, SC_None, SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +00007031 ExDecl->setExceptionVariable(true);
7032
Douglas Gregor6d182892010-03-05 23:38:39 +00007033 if (!Invalid) {
John McCalle996ffd2011-02-16 08:02:54 +00007034 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
Douglas Gregor6d182892010-03-05 23:38:39 +00007035 // C++ [except.handle]p16:
7036 // The object declared in an exception-declaration or, if the
7037 // exception-declaration does not specify a name, a temporary (12.2) is
7038 // copy-initialized (8.5) from the exception object. [...]
7039 // The object is destroyed when the handler exits, after the destruction
7040 // of any automatic objects initialized within the handler.
7041 //
7042 // We just pretend to initialize the object with itself, then make sure
7043 // it can be destroyed later.
John McCalle996ffd2011-02-16 08:02:54 +00007044 QualType initType = ExDeclType;
7045
7046 InitializedEntity entity =
7047 InitializedEntity::InitializeVariable(ExDecl);
7048 InitializationKind initKind =
7049 InitializationKind::CreateCopy(Loc, SourceLocation());
7050
7051 Expr *opaqueValue =
7052 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
7053 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
7054 ExprResult result = sequence.Perform(*this, entity, initKind,
7055 MultiExprArg(&opaqueValue, 1));
7056 if (result.isInvalid())
Douglas Gregor6d182892010-03-05 23:38:39 +00007057 Invalid = true;
John McCalle996ffd2011-02-16 08:02:54 +00007058 else {
7059 // If the constructor used was non-trivial, set this as the
7060 // "initializer".
7061 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
7062 if (!construct->getConstructor()->isTrivial()) {
7063 Expr *init = MaybeCreateExprWithCleanups(construct);
7064 ExDecl->setInit(init);
7065 }
7066
7067 // And make sure it's destructable.
7068 FinalizeVarWithDestructor(ExDecl, recordType);
7069 }
Douglas Gregor6d182892010-03-05 23:38:39 +00007070 }
7071 }
7072
Douglas Gregord308e622009-05-18 20:51:54 +00007073 if (Invalid)
7074 ExDecl->setInvalidDecl();
7075
7076 return ExDecl;
7077}
7078
7079/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
7080/// handler.
John McCalld226f652010-08-21 09:40:31 +00007081Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +00007082 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +00007083 bool Invalid = D.isInvalidType();
7084
7085 // Check for unexpanded parameter packs.
7086 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
7087 UPPC_ExceptionType)) {
7088 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
7089 D.getIdentifierLoc());
7090 Invalid = true;
7091 }
7092
Sebastian Redl4b07b292008-12-22 19:15:10 +00007093 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +00007094 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +00007095 LookupOrdinaryName,
7096 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00007097 // The scope should be freshly made just for us. There is just no way
7098 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +00007099 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +00007100 if (PrevDecl->isTemplateParameter()) {
7101 // Maybe we will complain about the shadowed template parameter.
7102 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00007103 }
7104 }
7105
Chris Lattnereaaebc72009-04-25 08:06:05 +00007106 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00007107 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
7108 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00007109 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00007110 }
7111
Douglas Gregor83cb9422010-09-09 17:09:21 +00007112 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007113 D.getSourceRange().getBegin(),
7114 D.getIdentifierLoc(),
7115 D.getIdentifier());
Chris Lattnereaaebc72009-04-25 08:06:05 +00007116 if (Invalid)
7117 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00007118
Sebastian Redl4b07b292008-12-22 19:15:10 +00007119 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00007120 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00007121 PushOnScopeChains(ExDecl, S);
7122 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00007123 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00007124
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00007125 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +00007126 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +00007127}
Anders Carlssonfb311762009-03-14 00:25:26 +00007128
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00007129Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +00007130 Expr *AssertExpr,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00007131 Expr *AssertMessageExpr_,
7132 SourceLocation RParenLoc) {
John McCall9ae2f072010-08-23 23:25:46 +00007133 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
Anders Carlssonfb311762009-03-14 00:25:26 +00007134
Anders Carlssonc3082412009-03-14 00:33:21 +00007135 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
7136 llvm::APSInt Value(32);
7137 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00007138 Diag(StaticAssertLoc,
7139 diag::err_static_assert_expression_is_not_constant) <<
Anders Carlssonc3082412009-03-14 00:33:21 +00007140 AssertExpr->getSourceRange();
John McCalld226f652010-08-21 09:40:31 +00007141 return 0;
Anders Carlssonc3082412009-03-14 00:33:21 +00007142 }
Anders Carlssonfb311762009-03-14 00:25:26 +00007143
Anders Carlssonc3082412009-03-14 00:33:21 +00007144 if (Value == 0) {
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00007145 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Benjamin Kramer8d042582009-12-11 13:33:18 +00007146 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlssonc3082412009-03-14 00:33:21 +00007147 }
7148 }
Mike Stump1eb44332009-09-09 15:08:12 +00007149
Douglas Gregor399ad972010-12-15 23:55:21 +00007150 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
7151 return 0;
7152
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00007153 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
7154 AssertExpr, AssertMessage, RParenLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00007155
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00007156 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +00007157 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +00007158}
Sebastian Redl50de12f2009-03-24 22:27:57 +00007159
Douglas Gregor1d869352010-04-07 16:53:43 +00007160/// \brief Perform semantic analysis of the given friend type declaration.
7161///
7162/// \returns A friend declaration that.
7163FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc,
7164 TypeSourceInfo *TSInfo) {
7165 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
7166
7167 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00007168 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +00007169
Douglas Gregor06245bf2010-04-07 17:57:12 +00007170 if (!getLangOptions().CPlusPlus0x) {
7171 // C++03 [class.friend]p2:
7172 // An elaborated-type-specifier shall be used in a friend declaration
7173 // for a class.*
7174 //
7175 // * The class-key of the elaborated-type-specifier is required.
7176 if (!ActiveTemplateInstantiations.empty()) {
7177 // Do not complain about the form of friend template types during
7178 // template instantiation; we will already have complained when the
7179 // template was declared.
7180 } else if (!T->isElaboratedTypeSpecifier()) {
7181 // If we evaluated the type to a record type, suggest putting
7182 // a tag in front.
7183 if (const RecordType *RT = T->getAs<RecordType>()) {
7184 RecordDecl *RD = RT->getDecl();
7185
7186 std::string InsertionText = std::string(" ") + RD->getKindName();
7187
7188 Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type)
7189 << (unsigned) RD->getTagKind()
7190 << T
7191 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
7192 InsertionText);
7193 } else {
7194 Diag(FriendLoc, diag::ext_nonclass_type_friend)
7195 << T
7196 << SourceRange(FriendLoc, TypeRange.getEnd());
7197 }
7198 } else if (T->getAs<EnumType>()) {
7199 Diag(FriendLoc, diag::ext_enum_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +00007200 << T
Douglas Gregor1d869352010-04-07 16:53:43 +00007201 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregor1d869352010-04-07 16:53:43 +00007202 }
7203 }
7204
Douglas Gregor06245bf2010-04-07 17:57:12 +00007205 // C++0x [class.friend]p3:
7206 // If the type specifier in a friend declaration designates a (possibly
7207 // cv-qualified) class type, that class is declared as a friend; otherwise,
7208 // the friend declaration is ignored.
7209
7210 // FIXME: C++0x has some syntactic restrictions on friend type declarations
7211 // in [class.friend]p3 that we do not implement.
Douglas Gregor1d869352010-04-07 16:53:43 +00007212
7213 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc);
7214}
7215
John McCall9a34edb2010-10-19 01:40:49 +00007216/// Handle a friend tag declaration where the scope specifier was
7217/// templated.
7218Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
7219 unsigned TagSpec, SourceLocation TagLoc,
7220 CXXScopeSpec &SS,
7221 IdentifierInfo *Name, SourceLocation NameLoc,
7222 AttributeList *Attr,
7223 MultiTemplateParamsArg TempParamLists) {
7224 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
7225
7226 bool isExplicitSpecialization = false;
John McCall9a34edb2010-10-19 01:40:49 +00007227 bool Invalid = false;
7228
7229 if (TemplateParameterList *TemplateParams
7230 = MatchTemplateParametersToScopeSpecifier(TagLoc, SS,
7231 TempParamLists.get(),
7232 TempParamLists.size(),
7233 /*friend*/ true,
7234 isExplicitSpecialization,
7235 Invalid)) {
John McCall9a34edb2010-10-19 01:40:49 +00007236 if (TemplateParams->size() > 0) {
7237 // This is a declaration of a class template.
7238 if (Invalid)
7239 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +00007240
John McCall9a34edb2010-10-19 01:40:49 +00007241 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
7242 SS, Name, NameLoc, Attr,
Abramo Bagnarac57c17d2011-03-10 13:28:31 +00007243 TemplateParams, AS_public,
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00007244 TempParamLists.size() - 1,
Abramo Bagnarac57c17d2011-03-10 13:28:31 +00007245 (TemplateParameterList**) TempParamLists.release()).take();
John McCall9a34edb2010-10-19 01:40:49 +00007246 } else {
7247 // The "template<>" header is extraneous.
7248 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
7249 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
7250 isExplicitSpecialization = true;
7251 }
7252 }
7253
7254 if (Invalid) return 0;
7255
7256 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
7257
7258 bool isAllExplicitSpecializations = true;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00007259 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
John McCall9a34edb2010-10-19 01:40:49 +00007260 if (TempParamLists.get()[I]->size()) {
7261 isAllExplicitSpecializations = false;
7262 break;
7263 }
7264 }
7265
7266 // FIXME: don't ignore attributes.
7267
7268 // If it's explicit specializations all the way down, just forget
7269 // about the template header and build an appropriate non-templated
7270 // friend. TODO: for source fidelity, remember the headers.
7271 if (isAllExplicitSpecializations) {
Douglas Gregor2494dd02011-03-01 01:34:45 +00007272 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall9a34edb2010-10-19 01:40:49 +00007273 ElaboratedTypeKeyword Keyword
7274 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor2494dd02011-03-01 01:34:45 +00007275 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +00007276 *Name, NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +00007277 if (T.isNull())
7278 return 0;
7279
7280 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
7281 if (isa<DependentNameType>(T)) {
7282 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
7283 TL.setKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +00007284 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +00007285 TL.setNameLoc(NameLoc);
7286 } else {
7287 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
7288 TL.setKeywordLoc(TagLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +00007289 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +00007290 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
7291 }
7292
7293 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
7294 TSI, FriendLoc);
7295 Friend->setAccess(AS_public);
7296 CurContext->addDecl(Friend);
7297 return Friend;
7298 }
7299
7300 // Handle the case of a templated-scope friend class. e.g.
7301 // template <class T> class A<T>::B;
7302 // FIXME: we don't support these right now.
7303 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
7304 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
7305 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
7306 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
7307 TL.setKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +00007308 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCall9a34edb2010-10-19 01:40:49 +00007309 TL.setNameLoc(NameLoc);
7310
7311 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
7312 TSI, FriendLoc);
7313 Friend->setAccess(AS_public);
7314 Friend->setUnsupportedFriend(true);
7315 CurContext->addDecl(Friend);
7316 return Friend;
7317}
7318
7319
John McCalldd4a3b02009-09-16 22:47:08 +00007320/// Handle a friend type declaration. This works in tandem with
7321/// ActOnTag.
7322///
7323/// Notes on friend class templates:
7324///
7325/// We generally treat friend class declarations as if they were
7326/// declaring a class. So, for example, the elaborated type specifier
7327/// in a friend declaration is required to obey the restrictions of a
7328/// class-head (i.e. no typedefs in the scope chain), template
7329/// parameters are required to match up with simple template-ids, &c.
7330/// However, unlike when declaring a template specialization, it's
7331/// okay to refer to a template specialization without an empty
7332/// template parameter declaration, e.g.
7333/// friend class A<T>::B<unsigned>;
7334/// We permit this as a special case; if there are any template
7335/// parameters present at all, require proper matching, i.e.
7336/// template <> template <class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +00007337Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +00007338 MultiTemplateParamsArg TempParams) {
John McCall02cace72009-08-28 07:59:38 +00007339 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall67d1a672009-08-06 02:15:43 +00007340
7341 assert(DS.isFriendSpecified());
7342 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
7343
John McCalldd4a3b02009-09-16 22:47:08 +00007344 // Try to convert the decl specifier to a type. This works for
7345 // friend templates because ActOnTag never produces a ClassTemplateDecl
7346 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +00007347 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +00007348 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
7349 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +00007350 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +00007351 return 0;
John McCall67d1a672009-08-06 02:15:43 +00007352
Douglas Gregor6ccab972010-12-16 01:14:37 +00007353 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
7354 return 0;
7355
John McCalldd4a3b02009-09-16 22:47:08 +00007356 // This is definitely an error in C++98. It's probably meant to
7357 // be forbidden in C++0x, too, but the specification is just
7358 // poorly written.
7359 //
7360 // The problem is with declarations like the following:
7361 // template <T> friend A<T>::foo;
7362 // where deciding whether a class C is a friend or not now hinges
7363 // on whether there exists an instantiation of A that causes
7364 // 'foo' to equal C. There are restrictions on class-heads
7365 // (which we declare (by fiat) elaborated friend declarations to
7366 // be) that makes this tractable.
7367 //
7368 // FIXME: handle "template <> friend class A<T>;", which
7369 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +00007370 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +00007371 Diag(Loc, diag::err_tagless_friend_type_template)
7372 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +00007373 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +00007374 }
Douglas Gregor1d869352010-04-07 16:53:43 +00007375
John McCall02cace72009-08-28 07:59:38 +00007376 // C++98 [class.friend]p1: A friend of a class is a function
7377 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +00007378 // This is fixed in DR77, which just barely didn't make the C++03
7379 // deadline. It's also a very silly restriction that seriously
7380 // affects inner classes and which nobody else seems to implement;
7381 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +00007382 //
7383 // But note that we could warn about it: it's always useless to
7384 // friend one of your own members (it's not, however, worthless to
7385 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +00007386
John McCalldd4a3b02009-09-16 22:47:08 +00007387 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +00007388 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +00007389 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +00007390 NumTempParamLists,
John McCallbe04b6d2010-10-16 07:23:36 +00007391 TempParams.release(),
John McCall32f2fb52010-03-25 18:04:51 +00007392 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +00007393 DS.getFriendSpecLoc());
7394 else
Douglas Gregor1d869352010-04-07 16:53:43 +00007395 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
7396
7397 if (!D)
John McCalld226f652010-08-21 09:40:31 +00007398 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +00007399
John McCalldd4a3b02009-09-16 22:47:08 +00007400 D->setAccess(AS_public);
7401 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +00007402
John McCalld226f652010-08-21 09:40:31 +00007403 return D;
John McCall02cace72009-08-28 07:59:38 +00007404}
7405
John McCall337ec3d2010-10-12 23:13:28 +00007406Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, bool IsDefinition,
7407 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +00007408 const DeclSpec &DS = D.getDeclSpec();
7409
7410 assert(DS.isFriendSpecified());
7411 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
7412
7413 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +00007414 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
7415 QualType T = TInfo->getType();
John McCall67d1a672009-08-06 02:15:43 +00007416
7417 // C++ [class.friend]p1
7418 // A friend of a class is a function or class....
7419 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +00007420 // It *doesn't* see through dependent types, which is correct
7421 // according to [temp.arg.type]p3:
7422 // If a declaration acquires a function type through a
7423 // type dependent on a template-parameter and this causes
7424 // a declaration that does not use the syntactic form of a
7425 // function declarator to have a function type, the program
7426 // is ill-formed.
John McCall67d1a672009-08-06 02:15:43 +00007427 if (!T->isFunctionType()) {
7428 Diag(Loc, diag::err_unexpected_friend);
7429
7430 // It might be worthwhile to try to recover by creating an
7431 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +00007432 return 0;
John McCall67d1a672009-08-06 02:15:43 +00007433 }
7434
7435 // C++ [namespace.memdef]p3
7436 // - If a friend declaration in a non-local class first declares a
7437 // class or function, the friend class or function is a member
7438 // of the innermost enclosing namespace.
7439 // - The name of the friend is not found by simple name lookup
7440 // until a matching declaration is provided in that namespace
7441 // scope (either before or after the class declaration granting
7442 // friendship).
7443 // - If a friend function is called, its name may be found by the
7444 // name lookup that considers functions from namespaces and
7445 // classes associated with the types of the function arguments.
7446 // - When looking for a prior declaration of a class or a function
7447 // declared as a friend, scopes outside the innermost enclosing
7448 // namespace scope are not considered.
7449
John McCall337ec3d2010-10-12 23:13:28 +00007450 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00007451 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
7452 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +00007453 assert(Name);
7454
Douglas Gregor6ccab972010-12-16 01:14:37 +00007455 // Check for unexpanded parameter packs.
7456 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
7457 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
7458 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
7459 return 0;
7460
John McCall67d1a672009-08-06 02:15:43 +00007461 // The context we found the declaration in, or in which we should
7462 // create the declaration.
7463 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +00007464 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +00007465 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +00007466 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +00007467
John McCall337ec3d2010-10-12 23:13:28 +00007468 // FIXME: there are different rules in local classes
John McCall67d1a672009-08-06 02:15:43 +00007469
John McCall337ec3d2010-10-12 23:13:28 +00007470 // There are four cases here.
7471 // - There's no scope specifier, in which case we just go to the
John McCall29ae6e52010-10-13 05:45:15 +00007472 // appropriate scope and look for a function or function template
John McCall337ec3d2010-10-12 23:13:28 +00007473 // there as appropriate.
7474 // Recover from invalid scope qualifiers as if they just weren't there.
7475 if (SS.isInvalid() || !SS.isSet()) {
John McCall29ae6e52010-10-13 05:45:15 +00007476 // C++0x [namespace.memdef]p3:
7477 // If the name in a friend declaration is neither qualified nor
7478 // a template-id and the declaration is a function or an
7479 // elaborated-type-specifier, the lookup to determine whether
7480 // the entity has been previously declared shall not consider
7481 // any scopes outside the innermost enclosing namespace.
7482 // C++0x [class.friend]p11:
7483 // If a friend declaration appears in a local class and the name
7484 // specified is an unqualified name, a prior declaration is
7485 // looked up without considering scopes that are outside the
7486 // innermost enclosing non-class scope. For a friend function
7487 // declaration, if there is no prior declaration, the program is
7488 // ill-formed.
7489 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCall8a407372010-10-14 22:22:28 +00007490 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +00007491
John McCall29ae6e52010-10-13 05:45:15 +00007492 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +00007493 DC = CurContext;
7494 while (true) {
7495 // Skip class contexts. If someone can cite chapter and verse
7496 // for this behavior, that would be nice --- it's what GCC and
7497 // EDG do, and it seems like a reasonable intent, but the spec
7498 // really only says that checks for unqualified existing
7499 // declarations should stop at the nearest enclosing namespace,
7500 // not that they should only consider the nearest enclosing
7501 // namespace.
Douglas Gregor182ddf02009-09-28 00:08:27 +00007502 while (DC->isRecord())
7503 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +00007504
John McCall68263142009-11-18 22:49:29 +00007505 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +00007506
7507 // TODO: decide what we think about using declarations.
John McCall29ae6e52010-10-13 05:45:15 +00007508 if (isLocal || !Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +00007509 break;
John McCall29ae6e52010-10-13 05:45:15 +00007510
John McCall8a407372010-10-14 22:22:28 +00007511 if (isTemplateId) {
7512 if (isa<TranslationUnitDecl>(DC)) break;
7513 } else {
7514 if (DC->isFileContext()) break;
7515 }
John McCall67d1a672009-08-06 02:15:43 +00007516 DC = DC->getParent();
7517 }
7518
7519 // C++ [class.friend]p1: A friend of a class is a function or
7520 // class that is not a member of the class . . .
John McCall7f27d922009-08-06 20:49:32 +00007521 // C++0x changes this for both friend types and functions.
7522 // Most C++ 98 compilers do seem to give an error here, so
7523 // we do, too.
John McCall68263142009-11-18 22:49:29 +00007524 if (!Previous.empty() && DC->Equals(CurContext)
7525 && !getLangOptions().CPlusPlus0x)
John McCall67d1a672009-08-06 02:15:43 +00007526 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
John McCall337ec3d2010-10-12 23:13:28 +00007527
John McCall380aaa42010-10-13 06:22:15 +00007528 DCScope = getScopeForDeclContext(S, DC);
John McCall29ae6e52010-10-13 05:45:15 +00007529
John McCall337ec3d2010-10-12 23:13:28 +00007530 // - There's a non-dependent scope specifier, in which case we
7531 // compute it and do a previous lookup there for a function
7532 // or function template.
7533 } else if (!SS.getScopeRep()->isDependent()) {
7534 DC = computeDeclContext(SS);
7535 if (!DC) return 0;
7536
7537 if (RequireCompleteDeclContext(SS, DC)) return 0;
7538
7539 LookupQualifiedName(Previous, DC);
7540
7541 // Ignore things found implicitly in the wrong scope.
7542 // TODO: better diagnostics for this case. Suggesting the right
7543 // qualified scope would be nice...
7544 LookupResult::Filter F = Previous.makeFilter();
7545 while (F.hasNext()) {
7546 NamedDecl *D = F.next();
7547 if (!DC->InEnclosingNamespaceSetOf(
7548 D->getDeclContext()->getRedeclContext()))
7549 F.erase();
7550 }
7551 F.done();
7552
7553 if (Previous.empty()) {
7554 D.setInvalidType();
7555 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
7556 return 0;
7557 }
7558
7559 // C++ [class.friend]p1: A friend of a class is a function or
7560 // class that is not a member of the class . . .
7561 if (DC->Equals(CurContext))
7562 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
7563
7564 // - There's a scope specifier that does not match any template
7565 // parameter lists, in which case we use some arbitrary context,
7566 // create a method or method template, and wait for instantiation.
7567 // - There's a scope specifier that does match some template
7568 // parameter lists, which we don't handle right now.
7569 } else {
7570 DC = CurContext;
7571 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +00007572 }
7573
John McCall29ae6e52010-10-13 05:45:15 +00007574 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +00007575 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00007576 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
7577 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
7578 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +00007579 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +00007580 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
7581 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +00007582 return 0;
John McCall67d1a672009-08-06 02:15:43 +00007583 }
John McCall67d1a672009-08-06 02:15:43 +00007584 }
7585
Douglas Gregor182ddf02009-09-28 00:08:27 +00007586 bool Redeclaration = false;
John McCall380aaa42010-10-13 06:22:15 +00007587 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, T, TInfo, Previous,
Douglas Gregora735b202009-10-13 14:39:41 +00007588 move(TemplateParams),
John McCall3f9a8a62009-08-11 06:59:38 +00007589 IsDefinition,
7590 Redeclaration);
John McCalld226f652010-08-21 09:40:31 +00007591 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +00007592
Douglas Gregor182ddf02009-09-28 00:08:27 +00007593 assert(ND->getDeclContext() == DC);
7594 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +00007595
John McCallab88d972009-08-31 22:39:49 +00007596 // Add the function declaration to the appropriate lookup tables,
7597 // adjusting the redeclarations list as necessary. We don't
7598 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +00007599 //
John McCallab88d972009-08-31 22:39:49 +00007600 // Also update the scope-based lookup if the target context's
7601 // lookup context is in lexical scope.
7602 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00007603 DC = DC->getRedeclContext();
Douglas Gregor182ddf02009-09-28 00:08:27 +00007604 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCallab88d972009-08-31 22:39:49 +00007605 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +00007606 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +00007607 }
John McCall02cace72009-08-28 07:59:38 +00007608
7609 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +00007610 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +00007611 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +00007612 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +00007613 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +00007614
John McCall337ec3d2010-10-12 23:13:28 +00007615 if (ND->isInvalidDecl())
7616 FrD->setInvalidDecl();
John McCall6102ca12010-10-16 06:59:13 +00007617 else {
7618 FunctionDecl *FD;
7619 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
7620 FD = FTD->getTemplatedDecl();
7621 else
7622 FD = cast<FunctionDecl>(ND);
7623
7624 // Mark templated-scope function declarations as unsupported.
7625 if (FD->getNumTemplateParameterLists())
7626 FrD->setUnsupportedFriend(true);
7627 }
John McCall337ec3d2010-10-12 23:13:28 +00007628
John McCalld226f652010-08-21 09:40:31 +00007629 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +00007630}
7631
John McCalld226f652010-08-21 09:40:31 +00007632void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
7633 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +00007634
Sebastian Redl50de12f2009-03-24 22:27:57 +00007635 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
7636 if (!Fn) {
7637 Diag(DelLoc, diag::err_deleted_non_function);
7638 return;
7639 }
7640 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
7641 Diag(DelLoc, diag::err_deleted_decl_not_first);
7642 Diag(Prev->getLocation(), diag::note_previous_declaration);
7643 // If the declaration wasn't the first, we delete the function anyway for
7644 // recovery.
7645 }
7646 Fn->setDeleted();
7647}
Sebastian Redl13e88542009-04-27 21:33:24 +00007648
7649static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +00007650 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +00007651 Stmt *SubStmt = *CI;
7652 if (!SubStmt)
7653 continue;
7654 if (isa<ReturnStmt>(SubStmt))
7655 Self.Diag(SubStmt->getSourceRange().getBegin(),
7656 diag::err_return_in_constructor_handler);
7657 if (!isa<Expr>(SubStmt))
7658 SearchForReturnInStmt(Self, SubStmt);
7659 }
7660}
7661
7662void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
7663 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
7664 CXXCatchStmt *Handler = TryBlock->getHandler(I);
7665 SearchForReturnInStmt(*this, Handler);
7666 }
7667}
Anders Carlssond7ba27d2009-05-14 01:09:04 +00007668
Mike Stump1eb44332009-09-09 15:08:12 +00007669bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +00007670 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +00007671 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
7672 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +00007673
Chandler Carruth73857792010-02-15 11:53:20 +00007674 if (Context.hasSameType(NewTy, OldTy) ||
7675 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +00007676 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00007677
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007678 // Check if the return types are covariant
7679 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +00007680
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007681 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00007682 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
7683 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007684 NewClassTy = NewPT->getPointeeType();
7685 OldClassTy = OldPT->getPointeeType();
7686 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00007687 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
7688 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
7689 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
7690 NewClassTy = NewRT->getPointeeType();
7691 OldClassTy = OldRT->getPointeeType();
7692 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007693 }
7694 }
Mike Stump1eb44332009-09-09 15:08:12 +00007695
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007696 // The return types aren't either both pointers or references to a class type.
7697 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +00007698 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007699 diag::err_different_return_type_for_overriding_virtual_function)
7700 << New->getDeclName() << NewTy << OldTy;
7701 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +00007702
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007703 return true;
7704 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +00007705
Anders Carlssonbe2e2052009-12-31 18:34:24 +00007706 // C++ [class.virtual]p6:
7707 // If the return type of D::f differs from the return type of B::f, the
7708 // class type in the return type of D::f shall be complete at the point of
7709 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +00007710 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
7711 if (!RT->isBeingDefined() &&
7712 RequireCompleteType(New->getLocation(), NewClassTy,
7713 PDiag(diag::err_covariant_return_incomplete)
7714 << New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +00007715 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +00007716 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +00007717
Douglas Gregora4923eb2009-11-16 21:35:15 +00007718 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007719 // Check if the new class derives from the old class.
7720 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
7721 Diag(New->getLocation(),
7722 diag::err_covariant_return_not_derived)
7723 << New->getDeclName() << NewTy << OldTy;
7724 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
7725 return true;
7726 }
Mike Stump1eb44332009-09-09 15:08:12 +00007727
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007728 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +00007729 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +00007730 diag::err_covariant_return_inaccessible_base,
7731 diag::err_covariant_return_ambiguous_derived_to_base_conv,
7732 // FIXME: Should this point to the return type?
7733 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCalleee1d542011-02-14 07:13:47 +00007734 // FIXME: this note won't trigger for delayed access control
7735 // diagnostics, and it's impossible to get an undelayed error
7736 // here from access control during the original parse because
7737 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007738 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
7739 return true;
7740 }
7741 }
Mike Stump1eb44332009-09-09 15:08:12 +00007742
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007743 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00007744 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007745 Diag(New->getLocation(),
7746 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +00007747 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007748 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
7749 return true;
7750 };
Mike Stump1eb44332009-09-09 15:08:12 +00007751
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007752
7753 // The new class type must have the same or less qualifiers as the old type.
7754 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
7755 Diag(New->getLocation(),
7756 diag::err_covariant_return_type_class_type_more_qualified)
7757 << New->getDeclName() << NewTy << OldTy;
7758 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
7759 return true;
7760 };
Mike Stump1eb44332009-09-09 15:08:12 +00007761
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007762 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +00007763}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00007764
Douglas Gregor4ba31362009-12-01 17:24:26 +00007765/// \brief Mark the given method pure.
7766///
7767/// \param Method the method to be marked pure.
7768///
7769/// \param InitRange the source range that covers the "0" initializer.
7770bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnara796aa442011-03-12 11:17:06 +00007771 SourceLocation EndLoc = InitRange.getEnd();
7772 if (EndLoc.isValid())
7773 Method->setRangeEnd(EndLoc);
7774
Douglas Gregor4ba31362009-12-01 17:24:26 +00007775 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
7776 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +00007777 return false;
Abramo Bagnara796aa442011-03-12 11:17:06 +00007778 }
Douglas Gregor4ba31362009-12-01 17:24:26 +00007779
7780 if (!Method->isInvalidDecl())
7781 Diag(Method->getLocation(), diag::err_non_virtual_pure)
7782 << Method->getDeclName() << InitRange;
7783 return true;
7784}
7785
John McCall731ad842009-12-19 09:28:58 +00007786/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
7787/// an initializer for the out-of-line declaration 'Dcl'. The scope
7788/// is a fresh scope pushed for just this purpose.
7789///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00007790/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
7791/// static data member of class X, names should be looked up in the scope of
7792/// class X.
John McCalld226f652010-08-21 09:40:31 +00007793void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00007794 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +00007795 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00007796
John McCall731ad842009-12-19 09:28:58 +00007797 // We should only get called for declarations with scope specifiers, like:
7798 // int foo::bar;
7799 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +00007800 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00007801}
7802
7803/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +00007804/// initializer for the out-of-line declaration 'D'.
7805void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00007806 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +00007807 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00007808
John McCall731ad842009-12-19 09:28:58 +00007809 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +00007810 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00007811}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00007812
7813/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
7814/// C++ if/switch/while/for statement.
7815/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +00007816DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00007817 // C++ 6.4p2:
7818 // The declarator shall not specify a function or an array.
7819 // The type-specifier-seq shall not contain typedef and shall not declare a
7820 // new class or enumeration.
7821 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
7822 "Parser allowed 'typedef' as storage class of condition decl.");
7823
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00007824 TagDecl *OwnedTag = 0;
John McCallbf1a0282010-06-04 23:28:52 +00007825 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S, &OwnedTag);
7826 QualType Ty = TInfo->getType();
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00007827
7828 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
7829 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
7830 // would be created and CXXConditionDeclExpr wants a VarDecl.
7831 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
7832 << D.getSourceRange();
7833 return DeclResult();
7834 } else if (OwnedTag && OwnedTag->isDefinition()) {
7835 // The type-specifier-seq shall not declare a new class or enumeration.
7836 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
7837 }
7838
John McCalld226f652010-08-21 09:40:31 +00007839 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00007840 if (!Dcl)
7841 return DeclResult();
7842
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00007843 return Dcl;
7844}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00007845
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007846void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
7847 bool DefinitionRequired) {
7848 // Ignore any vtable uses in unevaluated operands or for classes that do
7849 // not have a vtable.
7850 if (!Class->isDynamicClass() || Class->isDependentContext() ||
7851 CurContext->isDependentContext() ||
7852 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolabbf58bb2010-03-10 02:19:29 +00007853 return;
7854
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007855 // Try to insert this class into the map.
7856 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
7857 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
7858 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
7859 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +00007860 // If we already had an entry, check to see if we are promoting this vtable
7861 // to required a definition. If so, we need to reappend to the VTableUses
7862 // list, since we may have already processed the first entry.
7863 if (DefinitionRequired && !Pos.first->second) {
7864 Pos.first->second = true;
7865 } else {
7866 // Otherwise, we can early exit.
7867 return;
7868 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007869 }
7870
7871 // Local classes need to have their virtual members marked
7872 // immediately. For all other classes, we mark their virtual members
7873 // at the end of the translation unit.
7874 if (Class->isLocalClass())
7875 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +00007876 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007877 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +00007878}
7879
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007880bool Sema::DefineUsedVTables() {
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007881 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +00007882 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +00007883
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007884 // Note: The VTableUses vector could grow as a result of marking
7885 // the members of a class as "used", so we check the size each
7886 // time through the loop and prefer indices (with are stable) to
7887 // iterators (which are not).
Douglas Gregor78844032011-04-22 22:25:37 +00007888 bool DefinedAnything = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007889 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +00007890 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007891 if (!Class)
7892 continue;
7893
7894 SourceLocation Loc = VTableUses[I].second;
7895
7896 // If this class has a key function, but that key function is
7897 // defined in another translation unit, we don't need to emit the
7898 // vtable even though we're using it.
7899 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00007900 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007901 switch (KeyFunction->getTemplateSpecializationKind()) {
7902 case TSK_Undeclared:
7903 case TSK_ExplicitSpecialization:
7904 case TSK_ExplicitInstantiationDeclaration:
7905 // The key function is in another translation unit.
7906 continue;
7907
7908 case TSK_ExplicitInstantiationDefinition:
7909 case TSK_ImplicitInstantiation:
7910 // We will be instantiating the key function.
7911 break;
7912 }
7913 } else if (!KeyFunction) {
7914 // If we have a class with no key function that is the subject
7915 // of an explicit instantiation declaration, suppress the
7916 // vtable; it will live with the explicit instantiation
7917 // definition.
7918 bool IsExplicitInstantiationDeclaration
7919 = Class->getTemplateSpecializationKind()
7920 == TSK_ExplicitInstantiationDeclaration;
7921 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
7922 REnd = Class->redecls_end();
7923 R != REnd; ++R) {
7924 TemplateSpecializationKind TSK
7925 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
7926 if (TSK == TSK_ExplicitInstantiationDeclaration)
7927 IsExplicitInstantiationDeclaration = true;
7928 else if (TSK == TSK_ExplicitInstantiationDefinition) {
7929 IsExplicitInstantiationDeclaration = false;
7930 break;
7931 }
7932 }
7933
7934 if (IsExplicitInstantiationDeclaration)
7935 continue;
7936 }
7937
7938 // Mark all of the virtual members of this class as referenced, so
7939 // that we can build a vtable. Then, tell the AST consumer that a
7940 // vtable for this class is required.
Douglas Gregor78844032011-04-22 22:25:37 +00007941 DefinedAnything = true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007942 MarkVirtualMembersReferenced(Loc, Class);
7943 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
7944 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
7945
7946 // Optionally warn if we're emitting a weak vtable.
7947 if (Class->getLinkage() == ExternalLinkage &&
7948 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00007949 if (!KeyFunction || (KeyFunction->hasBody() && KeyFunction->isInlined()))
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007950 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
7951 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00007952 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007953 VTableUses.clear();
7954
Douglas Gregor78844032011-04-22 22:25:37 +00007955 return DefinedAnything;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00007956}
Anders Carlssond6a637f2009-12-07 08:24:59 +00007957
Rafael Espindola3e1ae932010-03-26 00:36:59 +00007958void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
7959 const CXXRecordDecl *RD) {
Anders Carlssond6a637f2009-12-07 08:24:59 +00007960 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
7961 e = RD->method_end(); i != e; ++i) {
7962 CXXMethodDecl *MD = *i;
7963
7964 // C++ [basic.def.odr]p2:
7965 // [...] A virtual member function is used if it is not pure. [...]
7966 if (MD->isVirtual() && !MD->isPure())
7967 MarkDeclarationReferenced(Loc, MD);
7968 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +00007969
7970 // Only classes that have virtual bases need a VTT.
7971 if (RD->getNumVBases() == 0)
7972 return;
7973
7974 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
7975 e = RD->bases_end(); i != e; ++i) {
7976 const CXXRecordDecl *Base =
7977 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +00007978 if (Base->getNumVBases() == 0)
7979 continue;
7980 MarkVirtualMembersReferenced(Loc, Base);
7981 }
Anders Carlssond6a637f2009-12-07 08:24:59 +00007982}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007983
7984/// SetIvarInitializers - This routine builds initialization ASTs for the
7985/// Objective-C implementation whose ivars need be initialized.
7986void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
7987 if (!getLangOptions().CPlusPlus)
7988 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00007989 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007990 llvm::SmallVector<ObjCIvarDecl*, 8> ivars;
7991 CollectIvarsToConstructOrDestruct(OID, ivars);
7992 if (ivars.empty())
7993 return;
Sean Huntcbb67482011-01-08 20:30:50 +00007994 llvm::SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007995 for (unsigned i = 0; i < ivars.size(); i++) {
7996 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +00007997 if (Field->isInvalidDecl())
7998 continue;
7999
Sean Huntcbb67482011-01-08 20:30:50 +00008000 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00008001 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
8002 InitializationKind InitKind =
8003 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
8004
8005 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00008006 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00008007 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregor53c374f2010-12-07 00:41:46 +00008008 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00008009 // Note, MemberInit could actually come back empty if no initialization
8010 // is required (e.g., because it would call a trivial default constructor)
8011 if (!MemberInit.get() || MemberInit.isInvalid())
8012 continue;
John McCallb4eb64d2010-10-08 02:01:28 +00008013
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00008014 Member =
Sean Huntcbb67482011-01-08 20:30:50 +00008015 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
8016 SourceLocation(),
8017 MemberInit.takeAs<Expr>(),
8018 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00008019 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +00008020
8021 // Be sure that the destructor is accessible and is marked as referenced.
8022 if (const RecordType *RecordTy
8023 = Context.getBaseElementType(Field->getType())
8024 ->getAs<RecordType>()) {
8025 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +00008026 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Douglas Gregor68dd3ee2010-05-20 02:24:22 +00008027 MarkDeclarationReferenced(Field->getLocation(), Destructor);
8028 CheckDestructorAccess(Field->getLocation(), Destructor,
8029 PDiag(diag::err_access_dtor_ivar)
8030 << Context.getBaseElementType(Field->getType()));
8031 }
8032 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00008033 }
8034 ObjCImplementation->setIvarInitializers(Context,
8035 AllToInit.data(), AllToInit.size());
8036 }
8037}
Sean Huntfe57eef2011-05-04 05:57:24 +00008038
Sean Huntebcbe1d2011-05-04 23:29:54 +00008039static
8040void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
8041 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
8042 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
8043 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
8044 Sema &S) {
8045 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
8046 CE = Current.end();
8047 if (Ctor->isInvalidDecl())
8048 return;
8049
8050 const FunctionDecl *FNTarget = 0;
8051 CXXConstructorDecl *Target;
8052
8053 // We ignore the result here since if we don't have a body, Target will be
8054 // null below.
8055 (void)Ctor->getTargetConstructor()->hasBody(FNTarget);
8056 Target
8057= const_cast<CXXConstructorDecl*>(cast_or_null<CXXConstructorDecl>(FNTarget));
8058
8059 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
8060 // Avoid dereferencing a null pointer here.
8061 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
8062
8063 if (!Current.insert(Canonical))
8064 return;
8065
8066 // We know that beyond here, we aren't chaining into a cycle.
8067 if (!Target || !Target->isDelegatingConstructor() ||
8068 Target->isInvalidDecl() || Valid.count(TCanonical)) {
8069 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
8070 Valid.insert(*CI);
8071 Current.clear();
8072 // We've hit a cycle.
8073 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
8074 Current.count(TCanonical)) {
8075 // If we haven't diagnosed this cycle yet, do so now.
8076 if (!Invalid.count(TCanonical)) {
8077 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Sean Huntc1598702011-05-05 00:05:47 +00008078 diag::warn_delegating_ctor_cycle)
Sean Huntebcbe1d2011-05-04 23:29:54 +00008079 << Ctor;
8080
8081 // Don't add a note for a function delegating directo to itself.
8082 if (TCanonical != Canonical)
8083 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
8084
8085 CXXConstructorDecl *C = Target;
8086 while (C->getCanonicalDecl() != Canonical) {
8087 (void)C->getTargetConstructor()->hasBody(FNTarget);
8088 assert(FNTarget && "Ctor cycle through bodiless function");
8089
8090 C
8091 = const_cast<CXXConstructorDecl*>(cast<CXXConstructorDecl>(FNTarget));
8092 S.Diag(C->getLocation(), diag::note_which_delegates_to);
8093 }
8094 }
8095
8096 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
8097 Invalid.insert(*CI);
8098 Current.clear();
8099 } else {
8100 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
8101 }
8102}
8103
8104
Sean Huntfe57eef2011-05-04 05:57:24 +00008105void Sema::CheckDelegatingCtorCycles() {
8106 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
8107
Sean Huntebcbe1d2011-05-04 23:29:54 +00008108 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
8109 CE = Current.end();
Sean Huntfe57eef2011-05-04 05:57:24 +00008110
8111 for (llvm::SmallVector<CXXConstructorDecl*, 4>::iterator
Sean Huntebcbe1d2011-05-04 23:29:54 +00008112 I = DelegatingCtorDecls.begin(),
8113 E = DelegatingCtorDecls.end();
8114 I != E; ++I) {
8115 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Sean Huntfe57eef2011-05-04 05:57:24 +00008116 }
Sean Huntebcbe1d2011-05-04 23:29:54 +00008117
8118 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
8119 (*CI)->setInvalidDecl();
Sean Huntfe57eef2011-05-04 05:57:24 +00008120}