blob: ec92470ae1f6d29c8e5cf211e0f624f2aefdcb35 [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"
Eli Friedman7badd242012-02-09 20:13:14 +000019#include "clang/Sema/ScopeInfo.h"
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +000020#include "clang/AST/ASTConsumer.h"
Douglas Gregore37ac4f2008-04-13 21:30:24 +000021#include "clang/AST/ASTContext.h"
Sebastian Redl58a2cd82011-04-24 16:28:06 +000022#include "clang/AST/ASTMutationListener.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000023#include "clang/AST/CharUnits.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000024#include "clang/AST/CXXInheritance.h"
Anders Carlsson8211eff2009-03-24 01:19:16 +000025#include "clang/AST/DeclVisitor.h"
Sean Hunt41717662011-02-26 19:13:13 +000026#include "clang/AST/ExprCXX.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000027#include "clang/AST/RecordLayout.h"
28#include "clang/AST/StmtVisitor.h"
Douglas Gregor802ab452009-12-02 22:36:29 +000029#include "clang/AST/TypeLoc.h"
Douglas Gregor02189362008-10-22 21:13:31 +000030#include "clang/AST/TypeOrdering.h"
John McCall19510852010-08-20 18:27:03 +000031#include "clang/Sema/DeclSpec.h"
32#include "clang/Sema/ParsedTemplate.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000033#include "clang/Basic/PartialDiagnostic.h"
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +000034#include "clang/Lex/Preprocessor.h"
John McCall50df6ae2010-08-25 07:03:20 +000035#include "llvm/ADT/DenseSet.h"
Benjamin Kramer8fe83e12012-02-04 13:45:25 +000036#include "llvm/ADT/SmallString.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000037#include "llvm/ADT/STLExtras.h"
Douglas Gregorf8268ae2008-10-22 17:49:05 +000038#include <map>
Douglas Gregora8f32e02009-10-06 17:59:45 +000039#include <set>
Chris Lattner3d1cee32008-04-08 05:04:30 +000040
41using namespace clang;
42
Chris Lattner8123a952008-04-10 02:22:51 +000043//===----------------------------------------------------------------------===//
44// CheckDefaultArgumentVisitor
45//===----------------------------------------------------------------------===//
46
Chris Lattner9e979552008-04-12 23:52:44 +000047namespace {
48 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
49 /// the default argument of a parameter to determine whether it
50 /// contains any ill-formed subexpressions. For example, this will
51 /// diagnose the use of local variables or parameters within the
52 /// default argument expression.
Benjamin Kramer85b45212009-11-28 19:45:26 +000053 class CheckDefaultArgumentVisitor
Chris Lattnerb77792e2008-07-26 22:17:49 +000054 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattner9e979552008-04-12 23:52:44 +000055 Expr *DefaultArg;
56 Sema *S;
Chris Lattner8123a952008-04-10 02:22:51 +000057
Chris Lattner9e979552008-04-12 23:52:44 +000058 public:
Mike Stump1eb44332009-09-09 15:08:12 +000059 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattner9e979552008-04-12 23:52:44 +000060 : DefaultArg(defarg), S(s) {}
Chris Lattner8123a952008-04-10 02:22:51 +000061
Chris Lattner9e979552008-04-12 23:52:44 +000062 bool VisitExpr(Expr *Node);
63 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor796da182008-11-04 14:32:21 +000064 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattner9e979552008-04-12 23:52:44 +000065 };
Chris Lattner8123a952008-04-10 02:22:51 +000066
Chris Lattner9e979552008-04-12 23:52:44 +000067 /// VisitExpr - Visit all of the children of this expression.
68 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
69 bool IsInvalid = false;
John McCall7502c1d2011-02-13 04:07:26 +000070 for (Stmt::child_range I = Node->children(); I; ++I)
Chris Lattnerb77792e2008-07-26 22:17:49 +000071 IsInvalid |= Visit(*I);
Chris Lattner9e979552008-04-12 23:52:44 +000072 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000073 }
74
Chris Lattner9e979552008-04-12 23:52:44 +000075 /// VisitDeclRefExpr - Visit a reference to a declaration, to
76 /// determine whether this declaration can be used in the default
77 /// argument expression.
78 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000079 NamedDecl *Decl = DRE->getDecl();
Chris Lattner9e979552008-04-12 23:52:44 +000080 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
81 // C++ [dcl.fct.default]p9
82 // Default arguments are evaluated each time the function is
83 // called. The order of evaluation of function arguments is
84 // unspecified. Consequently, parameters of a function shall not
85 // be used in default argument expressions, even if they are not
86 // evaluated. Parameters of a function declared before a default
87 // argument expression are in scope and can hide namespace and
88 // class member names.
Mike Stump1eb44332009-09-09 15:08:12 +000089 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000090 diag::err_param_default_argument_references_param)
Chris Lattner08631c52008-11-23 21:45:46 +000091 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff248a7532008-04-15 22:42:06 +000092 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000093 // C++ [dcl.fct.default]p7
94 // Local variables shall not be used in default argument
95 // expressions.
John McCallb6bbcc92010-10-15 04:57:14 +000096 if (VDecl->isLocalVarDecl())
Mike Stump1eb44332009-09-09 15:08:12 +000097 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000098 diag::err_param_default_argument_references_local)
Chris Lattner08631c52008-11-23 21:45:46 +000099 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000100 }
Chris Lattner8123a952008-04-10 02:22:51 +0000101
Douglas Gregor3996f232008-11-04 13:41:56 +0000102 return false;
103 }
Chris Lattner9e979552008-04-12 23:52:44 +0000104
Douglas Gregor796da182008-11-04 14:32:21 +0000105 /// VisitCXXThisExpr - Visit a C++ "this" expression.
106 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
107 // C++ [dcl.fct.default]p8:
108 // The keyword this shall not be used in a default argument of a
109 // member function.
110 return S->Diag(ThisE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000111 diag::err_param_default_argument_references_this)
112 << ThisE->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000113 }
Chris Lattner8123a952008-04-10 02:22:51 +0000114}
115
Sean Hunt001cad92011-05-10 00:49:42 +0000116void Sema::ImplicitExceptionSpecification::CalledDecl(CXXMethodDecl *Method) {
Sean Hunt49634cf2011-05-13 06:10:58 +0000117 assert(Context && "ImplicitExceptionSpecification without an ASTContext");
Richard Smith7a614d82011-06-11 17:19:42 +0000118 // If we have an MSAny or unknown spec already, don't bother.
119 if (!Method || ComputedEST == EST_MSAny || ComputedEST == EST_Delayed)
Sean Hunt001cad92011-05-10 00:49:42 +0000120 return;
121
122 const FunctionProtoType *Proto
123 = Method->getType()->getAs<FunctionProtoType>();
124
125 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
126
127 // If this function can throw any exceptions, make a note of that.
Richard Smith7a614d82011-06-11 17:19:42 +0000128 if (EST == EST_Delayed || EST == EST_MSAny || EST == EST_None) {
Sean Hunt001cad92011-05-10 00:49:42 +0000129 ClearExceptions();
130 ComputedEST = EST;
131 return;
132 }
133
Richard Smith7a614d82011-06-11 17:19:42 +0000134 // FIXME: If the call to this decl is using any of its default arguments, we
135 // need to search them for potentially-throwing calls.
136
Sean Hunt001cad92011-05-10 00:49:42 +0000137 // If this function has a basic noexcept, it doesn't affect the outcome.
138 if (EST == EST_BasicNoexcept)
139 return;
140
141 // If we have a throw-all spec at this point, ignore the function.
142 if (ComputedEST == EST_None)
143 return;
144
145 // If we're still at noexcept(true) and there's a nothrow() callee,
146 // change to that specification.
147 if (EST == EST_DynamicNone) {
148 if (ComputedEST == EST_BasicNoexcept)
149 ComputedEST = EST_DynamicNone;
150 return;
151 }
152
153 // Check out noexcept specs.
154 if (EST == EST_ComputedNoexcept) {
Sean Hunt49634cf2011-05-13 06:10:58 +0000155 FunctionProtoType::NoexceptResult NR = Proto->getNoexceptSpec(*Context);
Sean Hunt001cad92011-05-10 00:49:42 +0000156 assert(NR != FunctionProtoType::NR_NoNoexcept &&
157 "Must have noexcept result for EST_ComputedNoexcept.");
158 assert(NR != FunctionProtoType::NR_Dependent &&
159 "Should not generate implicit declarations for dependent cases, "
160 "and don't know how to handle them anyway.");
161
162 // noexcept(false) -> no spec on the new function
163 if (NR == FunctionProtoType::NR_Throw) {
164 ClearExceptions();
165 ComputedEST = EST_None;
166 }
167 // noexcept(true) won't change anything either.
168 return;
169 }
170
171 assert(EST == EST_Dynamic && "EST case not considered earlier.");
172 assert(ComputedEST != EST_None &&
173 "Shouldn't collect exceptions when throw-all is guaranteed.");
174 ComputedEST = EST_Dynamic;
175 // Record the exceptions in this function's exception specification.
176 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
177 EEnd = Proto->exception_end();
178 E != EEnd; ++E)
Sean Hunt49634cf2011-05-13 06:10:58 +0000179 if (ExceptionsSeen.insert(Context->getCanonicalType(*E)))
Sean Hunt001cad92011-05-10 00:49:42 +0000180 Exceptions.push_back(*E);
181}
182
Richard Smith7a614d82011-06-11 17:19:42 +0000183void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
184 if (!E || ComputedEST == EST_MSAny || ComputedEST == EST_Delayed)
185 return;
186
187 // FIXME:
188 //
189 // C++0x [except.spec]p14:
NAKAMURA Takumi48579472011-06-21 03:19:28 +0000190 // [An] implicit exception-specification specifies the type-id T if and
191 // only if T is allowed by the exception-specification of a function directly
192 // invoked by f's implicit definition; f shall allow all exceptions if any
Richard Smith7a614d82011-06-11 17:19:42 +0000193 // function it directly invokes allows all exceptions, and f shall allow no
194 // exceptions if every function it directly invokes allows no exceptions.
195 //
196 // Note in particular that if an implicit exception-specification is generated
197 // for a function containing a throw-expression, that specification can still
198 // be noexcept(true).
199 //
200 // Note also that 'directly invoked' is not defined in the standard, and there
201 // is no indication that we should only consider potentially-evaluated calls.
202 //
203 // Ultimately we should implement the intent of the standard: the exception
204 // specification should be the set of exceptions which can be thrown by the
205 // implicit definition. For now, we assume that any non-nothrow expression can
206 // throw any exception.
207
208 if (E->CanThrow(*Context))
209 ComputedEST = EST_None;
210}
211
Anders Carlssoned961f92009-08-25 02:29:20 +0000212bool
John McCall9ae2f072010-08-23 23:25:46 +0000213Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump1eb44332009-09-09 15:08:12 +0000214 SourceLocation EqualLoc) {
Anders Carlsson5653ca52009-08-25 13:46:13 +0000215 if (RequireCompleteType(Param->getLocation(), Param->getType(),
216 diag::err_typecheck_decl_incomplete_type)) {
217 Param->setInvalidDecl();
218 return true;
219 }
220
Anders Carlssoned961f92009-08-25 02:29:20 +0000221 // C++ [dcl.fct.default]p5
222 // A default argument expression is implicitly converted (clause
223 // 4) to the parameter type. The default argument expression has
224 // the same semantic constraints as the initializer expression in
225 // a declaration of a variable of the parameter type, using the
226 // copy-initialization semantics (8.5).
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000227 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
228 Param);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000229 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
230 EqualLoc);
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000231 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
John McCall60d7b3a2010-08-24 06:29:42 +0000232 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
Nico Weber6bb4dcb2010-11-28 22:53:37 +0000233 MultiExprArg(*this, &Arg, 1));
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000234 if (Result.isInvalid())
Anders Carlsson9351c172009-08-25 03:18:48 +0000235 return true;
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000236 Arg = Result.takeAs<Expr>();
Anders Carlssoned961f92009-08-25 02:29:20 +0000237
John McCallb4eb64d2010-10-08 02:01:28 +0000238 CheckImplicitConversions(Arg, EqualLoc);
John McCall4765fa02010-12-06 08:20:24 +0000239 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000240
Anders Carlssoned961f92009-08-25 02:29:20 +0000241 // Okay: add the default argument to the parameter
242 Param->setDefaultArg(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000243
Douglas Gregor8cfb7a32010-10-12 18:23:32 +0000244 // We have already instantiated this parameter; provide each of the
245 // instantiations with the uninstantiated default argument.
246 UnparsedDefaultArgInstantiationsMap::iterator InstPos
247 = UnparsedDefaultArgInstantiations.find(Param);
248 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
249 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
250 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
251
252 // We're done tracking this parameter's instantiations.
253 UnparsedDefaultArgInstantiations.erase(InstPos);
254 }
255
Anders Carlsson9351c172009-08-25 03:18:48 +0000256 return false;
Anders Carlssoned961f92009-08-25 02:29:20 +0000257}
258
Chris Lattner8123a952008-04-10 02:22:51 +0000259/// ActOnParamDefaultArgument - Check whether the default argument
260/// provided for a function parameter is well-formed. If so, attach it
261/// to the parameter declaration.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000262void
John McCalld226f652010-08-21 09:40:31 +0000263Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000264 Expr *DefaultArg) {
265 if (!param || !DefaultArg)
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000266 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000267
John McCalld226f652010-08-21 09:40:31 +0000268 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000269 UnparsedDefaultArgLocs.erase(Param);
270
Chris Lattner3d1cee32008-04-08 05:04:30 +0000271 // Default arguments are only permitted in C++
272 if (!getLangOptions().CPlusPlus) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000273 Diag(EqualLoc, diag::err_param_default_argument)
274 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000275 Param->setInvalidDecl();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000276 return;
277 }
278
Douglas Gregor6f526752010-12-16 08:48:57 +0000279 // Check for unexpanded parameter packs.
280 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
281 Param->setInvalidDecl();
282 return;
283 }
284
Anders Carlsson66e30672009-08-25 01:02:06 +0000285 // Check that the default argument is well-formed
John McCall9ae2f072010-08-23 23:25:46 +0000286 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
287 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlsson66e30672009-08-25 01:02:06 +0000288 Param->setInvalidDecl();
289 return;
290 }
Mike Stump1eb44332009-09-09 15:08:12 +0000291
John McCall9ae2f072010-08-23 23:25:46 +0000292 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000293}
294
Douglas Gregor61366e92008-12-24 00:01:03 +0000295/// ActOnParamUnparsedDefaultArgument - We've seen a default
296/// argument for a function parameter, but we can't parse it yet
297/// because we're inside a class definition. Note that this default
298/// argument will be parsed later.
John McCalld226f652010-08-21 09:40:31 +0000299void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson5e300d12009-06-12 16:51:40 +0000300 SourceLocation EqualLoc,
301 SourceLocation ArgLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000302 if (!param)
303 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000304
John McCalld226f652010-08-21 09:40:31 +0000305 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000306 if (Param)
307 Param->setUnparsedDefaultArg();
Mike Stump1eb44332009-09-09 15:08:12 +0000308
Anders Carlsson5e300d12009-06-12 16:51:40 +0000309 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor61366e92008-12-24 00:01:03 +0000310}
311
Douglas Gregor72b505b2008-12-16 21:30:33 +0000312/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
313/// the default argument for the parameter param failed.
John McCalld226f652010-08-21 09:40:31 +0000314void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000315 if (!param)
316 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000317
John McCalld226f652010-08-21 09:40:31 +0000318 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Mike Stump1eb44332009-09-09 15:08:12 +0000319
Anders Carlsson5e300d12009-06-12 16:51:40 +0000320 Param->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000321
Anders Carlsson5e300d12009-06-12 16:51:40 +0000322 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000323}
324
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000325/// CheckExtraCXXDefaultArguments - Check for any extra default
326/// arguments in the declarator, which is not a function declaration
327/// or definition and therefore is not permitted to have default
328/// arguments. This routine should be invoked for every declarator
329/// that is not a function declaration or definition.
330void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
331 // C++ [dcl.fct.default]p3
332 // A default argument expression shall be specified only in the
333 // parameter-declaration-clause of a function declaration or in a
334 // template-parameter (14.1). It shall not be specified for a
335 // parameter pack. If it is specified in a
336 // parameter-declaration-clause, it shall not occur within a
337 // declarator or abstract-declarator of a parameter-declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000338 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000339 DeclaratorChunk &chunk = D.getTypeObject(i);
340 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000341 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
342 ParmVarDecl *Param =
John McCalld226f652010-08-21 09:40:31 +0000343 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000344 if (Param->hasUnparsedDefaultArg()) {
345 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000346 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
347 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
348 delete Toks;
349 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor61366e92008-12-24 00:01:03 +0000350 } else if (Param->getDefaultArg()) {
351 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
352 << Param->getDefaultArg()->getSourceRange();
353 Param->setDefaultArg(0);
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000354 }
355 }
356 }
357 }
358}
359
Chris Lattner3d1cee32008-04-08 05:04:30 +0000360// MergeCXXFunctionDecl - Merge two declarations of the same C++
361// function, once we already know that they have the same
Douglas Gregorcda9c672009-02-16 17:45:42 +0000362// type. Subroutine of MergeFunctionDecl. Returns true if there was an
363// error, false otherwise.
364bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
365 bool Invalid = false;
366
Chris Lattner3d1cee32008-04-08 05:04:30 +0000367 // C++ [dcl.fct.default]p4:
Chris Lattner3d1cee32008-04-08 05:04:30 +0000368 // For non-template functions, default arguments can be added in
369 // later declarations of a function in the same
370 // scope. Declarations in different scopes have completely
371 // distinct sets of default arguments. That is, declarations in
372 // inner scopes do not acquire default arguments from
373 // declarations in outer scopes, and vice versa. In a given
374 // function declaration, all parameters subsequent to a
375 // parameter with a default argument shall have default
376 // arguments supplied in this or previous declarations. A
377 // default argument shall not be redefined by a later
378 // declaration (not even to the same value).
Douglas Gregor6cc15182009-09-11 18:44:32 +0000379 //
380 // C++ [dcl.fct.default]p6:
381 // Except for member functions of class templates, the default arguments
382 // in a member function definition that appears outside of the class
383 // definition are added to the set of default arguments provided by the
384 // member function declaration in the class definition.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000385 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
386 ParmVarDecl *OldParam = Old->getParamDecl(p);
387 ParmVarDecl *NewParam = New->getParamDecl(p);
388
Douglas Gregor6cc15182009-09-11 18:44:32 +0000389 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000390
Francois Pichet8d051e02011-04-10 03:03:52 +0000391 unsigned DiagDefaultParamID =
392 diag::err_param_default_argument_redefinition;
393
394 // MSVC accepts that default parameters be redefined for member functions
395 // of template class. The new default parameter's value is ignored.
396 Invalid = true;
Francois Pichet62ec1f22011-09-17 17:15:52 +0000397 if (getLangOptions().MicrosoftExt) {
Francois Pichet8d051e02011-04-10 03:03:52 +0000398 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
399 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000400 // Merge the old default argument into the new parameter.
401 NewParam->setHasInheritedDefaultArg();
402 if (OldParam->hasUninstantiatedDefaultArg())
403 NewParam->setUninstantiatedDefaultArg(
404 OldParam->getUninstantiatedDefaultArg());
405 else
406 NewParam->setDefaultArg(OldParam->getInit());
Francois Pichetcf320c62011-04-22 08:25:24 +0000407 DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
Francois Pichet8d051e02011-04-10 03:03:52 +0000408 Invalid = false;
409 }
410 }
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000411
Francois Pichet8cf90492011-04-10 04:58:30 +0000412 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
413 // hint here. Alternatively, we could walk the type-source information
414 // for NewParam to find the last source location in the type... but it
415 // isn't worth the effort right now. This is the kind of test case that
416 // is hard to get right:
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000417 // int f(int);
418 // void g(int (*fp)(int) = f);
419 // void g(int (*fp)(int) = &f);
Francois Pichet8d051e02011-04-10 03:03:52 +0000420 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000421 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000422
423 // Look for the function declaration where the default argument was
424 // actually written, which may be a declaration prior to Old.
Douglas Gregoref96ee02012-01-14 16:38:05 +0000425 for (FunctionDecl *Older = Old->getPreviousDecl();
426 Older; Older = Older->getPreviousDecl()) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000427 if (!Older->getParamDecl(p)->hasDefaultArg())
428 break;
429
430 OldParam = Older->getParamDecl(p);
431 }
432
433 Diag(OldParam->getLocation(), diag::note_previous_definition)
434 << OldParam->getDefaultArgRange();
Douglas Gregord85cef52009-09-17 19:51:30 +0000435 } else if (OldParam->hasDefaultArg()) {
John McCall3d6c1782010-05-04 01:53:42 +0000436 // Merge the old default argument into the new parameter.
437 // It's important to use getInit() here; getDefaultArg()
John McCall4765fa02010-12-06 08:20:24 +0000438 // strips off any top-level ExprWithCleanups.
John McCallbf73b352010-03-12 18:31:32 +0000439 NewParam->setHasInheritedDefaultArg();
Douglas Gregord85cef52009-09-17 19:51:30 +0000440 if (OldParam->hasUninstantiatedDefaultArg())
441 NewParam->setUninstantiatedDefaultArg(
442 OldParam->getUninstantiatedDefaultArg());
443 else
John McCall3d6c1782010-05-04 01:53:42 +0000444 NewParam->setDefaultArg(OldParam->getInit());
Douglas Gregor6cc15182009-09-11 18:44:32 +0000445 } else if (NewParam->hasDefaultArg()) {
446 if (New->getDescribedFunctionTemplate()) {
447 // Paragraph 4, quoted above, only applies to non-template functions.
448 Diag(NewParam->getLocation(),
449 diag::err_param_default_argument_template_redecl)
450 << NewParam->getDefaultArgRange();
451 Diag(Old->getLocation(), diag::note_template_prev_declaration)
452 << false;
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000453 } else if (New->getTemplateSpecializationKind()
454 != TSK_ImplicitInstantiation &&
455 New->getTemplateSpecializationKind() != TSK_Undeclared) {
456 // C++ [temp.expr.spec]p21:
457 // Default function arguments shall not be specified in a declaration
458 // or a definition for one of the following explicit specializations:
459 // - the explicit specialization of a function template;
Douglas Gregor8c638ab2009-10-13 23:52:38 +0000460 // - the explicit specialization of a member function template;
461 // - the explicit specialization of a member function of a class
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000462 // template where the class template specialization to which the
463 // member function specialization belongs is implicitly
464 // instantiated.
465 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
466 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
467 << New->getDeclName()
468 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000469 } else if (New->getDeclContext()->isDependentContext()) {
470 // C++ [dcl.fct.default]p6 (DR217):
471 // Default arguments for a member function of a class template shall
472 // be specified on the initial declaration of the member function
473 // within the class template.
474 //
475 // Reading the tea leaves a bit in DR217 and its reference to DR205
476 // leads me to the conclusion that one cannot add default function
477 // arguments for an out-of-line definition of a member function of a
478 // dependent type.
479 int WhichKind = 2;
480 if (CXXRecordDecl *Record
481 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
482 if (Record->getDescribedClassTemplate())
483 WhichKind = 0;
484 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
485 WhichKind = 1;
486 else
487 WhichKind = 2;
488 }
489
490 Diag(NewParam->getLocation(),
491 diag::err_param_default_argument_member_template_redecl)
492 << WhichKind
493 << NewParam->getDefaultArgRange();
Sean Hunt9ae60d52011-05-26 01:26:05 +0000494 } else if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(New)) {
495 CXXSpecialMember NewSM = getSpecialMember(Ctor),
496 OldSM = getSpecialMember(cast<CXXConstructorDecl>(Old));
497 if (NewSM != OldSM) {
498 Diag(NewParam->getLocation(),diag::warn_default_arg_makes_ctor_special)
499 << NewParam->getDefaultArgRange() << NewSM;
500 Diag(Old->getLocation(), diag::note_previous_declaration_special)
501 << OldSM;
502 }
Douglas Gregor6cc15182009-09-11 18:44:32 +0000503 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000504 }
505 }
506
Richard Smith9f569cc2011-10-01 02:31:28 +0000507 // C++0x [dcl.constexpr]p1: If any declaration of a function or function
508 // template has a constexpr specifier then all its declarations shall
509 // contain the constexpr specifier. [Note: An explicit specialization can
510 // differ from the template declaration with respect to the constexpr
511 // specifier. -- end note]
512 //
513 // FIXME: Don't reject changes in constexpr in explicit specializations.
514 if (New->isConstexpr() != Old->isConstexpr()) {
515 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
516 << New << New->isConstexpr();
517 Diag(Old->getLocation(), diag::note_previous_declaration);
518 Invalid = true;
519 }
520
Douglas Gregore13ad832010-02-12 07:32:17 +0000521 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000522 Invalid = true;
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000523
Douglas Gregorcda9c672009-02-16 17:45:42 +0000524 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000525}
526
Sebastian Redl60618fa2011-03-12 11:50:43 +0000527/// \brief Merge the exception specifications of two variable declarations.
528///
529/// This is called when there's a redeclaration of a VarDecl. The function
530/// checks if the redeclaration might have an exception specification and
531/// validates compatibility and merges the specs if necessary.
532void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
533 // Shortcut if exceptions are disabled.
534 if (!getLangOptions().CXXExceptions)
535 return;
536
537 assert(Context.hasSameType(New->getType(), Old->getType()) &&
538 "Should only be called if types are otherwise the same.");
539
540 QualType NewType = New->getType();
541 QualType OldType = Old->getType();
542
543 // We're only interested in pointers and references to functions, as well
544 // as pointers to member functions.
545 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
546 NewType = R->getPointeeType();
547 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
548 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
549 NewType = P->getPointeeType();
550 OldType = OldType->getAs<PointerType>()->getPointeeType();
551 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
552 NewType = M->getPointeeType();
553 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
554 }
555
556 if (!NewType->isFunctionProtoType())
557 return;
558
559 // There's lots of special cases for functions. For function pointers, system
560 // libraries are hopefully not as broken so that we don't need these
561 // workarounds.
562 if (CheckEquivalentExceptionSpec(
563 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
564 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
565 New->setInvalidDecl();
566 }
567}
568
Chris Lattner3d1cee32008-04-08 05:04:30 +0000569/// CheckCXXDefaultArguments - Verify that the default arguments for a
570/// function declaration are well-formed according to C++
571/// [dcl.fct.default].
572void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
573 unsigned NumParams = FD->getNumParams();
574 unsigned p;
575
576 // Find first parameter with a default argument
577 for (p = 0; p < NumParams; ++p) {
578 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000579 if (Param->hasDefaultArg())
Chris Lattner3d1cee32008-04-08 05:04:30 +0000580 break;
581 }
582
583 // C++ [dcl.fct.default]p4:
584 // In a given function declaration, all parameters
585 // subsequent to a parameter with a default argument shall
586 // have default arguments supplied in this or previous
587 // declarations. A default argument shall not be redefined
588 // by a later declaration (not even to the same value).
589 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000590 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000591 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000592 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000593 if (Param->isInvalidDecl())
594 /* We already complained about this parameter. */;
595 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000596 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000597 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000598 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000599 else
Mike Stump1eb44332009-09-09 15:08:12 +0000600 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000601 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000602
Chris Lattner3d1cee32008-04-08 05:04:30 +0000603 LastMissingDefaultArg = p;
604 }
605 }
606
607 if (LastMissingDefaultArg > 0) {
608 // Some default arguments were missing. Clear out all of the
609 // default arguments up to (and including) the last missing
610 // default argument, so that we leave the function parameters
611 // in a semantically valid state.
612 for (p = 0; p <= LastMissingDefaultArg; ++p) {
613 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000614 if (Param->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000615 Param->setDefaultArg(0);
616 }
617 }
618 }
619}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000620
Richard Smith9f569cc2011-10-01 02:31:28 +0000621// CheckConstexprParameterTypes - Check whether a function's parameter types
622// are all literal types. If so, return true. If not, produce a suitable
623// diagnostic depending on @p CCK and return false.
624static bool CheckConstexprParameterTypes(Sema &SemaRef, const FunctionDecl *FD,
625 Sema::CheckConstexprKind CCK) {
626 unsigned ArgIndex = 0;
627 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
628 for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(),
629 e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) {
630 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
631 SourceLocation ParamLoc = PD->getLocation();
632 if (!(*i)->isDependentType() &&
633 SemaRef.RequireLiteralType(ParamLoc, *i, CCK == Sema::CCK_Declaration ?
634 SemaRef.PDiag(diag::err_constexpr_non_literal_param)
635 << ArgIndex+1 << PD->getSourceRange()
636 << isa<CXXConstructorDecl>(FD) :
637 SemaRef.PDiag(),
638 /*AllowIncompleteType*/ true)) {
639 if (CCK == Sema::CCK_NoteNonConstexprInstantiation)
640 SemaRef.Diag(ParamLoc, diag::note_constexpr_tmpl_non_literal_param)
641 << ArgIndex+1 << PD->getSourceRange()
642 << isa<CXXConstructorDecl>(FD) << *i;
643 return false;
644 }
645 }
646 return true;
647}
648
649// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
650// the requirements of a constexpr function declaration or a constexpr
651// constructor declaration. Return true if it does, false if not.
652//
Richard Smith35340502012-01-13 04:54:00 +0000653// This implements C++11 [dcl.constexpr]p3,4, as amended by N3308.
Richard Smith9f569cc2011-10-01 02:31:28 +0000654//
655// \param CCK Specifies whether to produce diagnostics if the function does not
656// satisfy the requirements.
657bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD,
658 CheckConstexprKind CCK) {
659 assert((CCK != CCK_NoteNonConstexprInstantiation ||
660 (NewFD->getTemplateInstantiationPattern() &&
661 NewFD->getTemplateInstantiationPattern()->isConstexpr())) &&
662 "only constexpr templates can be instantiated non-constexpr");
663
Richard Smith35340502012-01-13 04:54:00 +0000664 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
665 if (MD && MD->isInstance()) {
666 // C++11 [dcl.constexpr]p4: In the definition of a constexpr constructor...
Richard Smith9f569cc2011-10-01 02:31:28 +0000667 // In addition, either its function-body shall be = delete or = default or
668 // it shall satisfy the following constraints:
669 // - the class shall not have any virtual base classes;
Richard Smith35340502012-01-13 04:54:00 +0000670 //
671 // We apply this to constexpr member functions too: the class cannot be a
672 // literal type, so the members are not permitted to be constexpr.
673 const CXXRecordDecl *RD = MD->getParent();
Richard Smith9f569cc2011-10-01 02:31:28 +0000674 if (RD->getNumVBases()) {
675 // Note, this is still illegal if the body is = default, since the
676 // implicit body does not satisfy the requirements of a constexpr
677 // constructor. We also reject cases where the body is = delete, as
678 // required by N3308.
679 if (CCK != CCK_Instantiation) {
680 Diag(NewFD->getLocation(),
681 CCK == CCK_Declaration ? diag::err_constexpr_virtual_base
682 : diag::note_constexpr_tmpl_virtual_base)
Richard Smith35340502012-01-13 04:54:00 +0000683 << isa<CXXConstructorDecl>(NewFD) << RD->isStruct()
684 << RD->getNumVBases();
Richard Smith9f569cc2011-10-01 02:31:28 +0000685 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
686 E = RD->vbases_end(); I != E; ++I)
687 Diag(I->getSourceRange().getBegin(),
688 diag::note_constexpr_virtual_base_here) << I->getSourceRange();
689 }
690 return false;
691 }
Richard Smith35340502012-01-13 04:54:00 +0000692 }
693
694 if (!isa<CXXConstructorDecl>(NewFD)) {
695 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +0000696 // The definition of a constexpr function shall satisfy the following
697 // constraints:
698 // - it shall not be virtual;
699 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
700 if (Method && Method->isVirtual()) {
701 if (CCK != CCK_Instantiation) {
702 Diag(NewFD->getLocation(),
703 CCK == CCK_Declaration ? diag::err_constexpr_virtual
704 : diag::note_constexpr_tmpl_virtual);
705
706 // If it's not obvious why this function is virtual, find an overridden
707 // function which uses the 'virtual' keyword.
708 const CXXMethodDecl *WrittenVirtual = Method;
709 while (!WrittenVirtual->isVirtualAsWritten())
710 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
711 if (WrittenVirtual != Method)
Richard Smith35340502012-01-13 04:54:00 +0000712 Diag(WrittenVirtual->getLocation(),
Richard Smith9f569cc2011-10-01 02:31:28 +0000713 diag::note_overridden_virtual_function);
714 }
715 return false;
716 }
717
718 // - its return type shall be a literal type;
719 QualType RT = NewFD->getResultType();
720 if (!RT->isDependentType() &&
721 RequireLiteralType(NewFD->getLocation(), RT, CCK == CCK_Declaration ?
722 PDiag(diag::err_constexpr_non_literal_return) :
723 PDiag(),
724 /*AllowIncompleteType*/ true)) {
725 if (CCK == CCK_NoteNonConstexprInstantiation)
726 Diag(NewFD->getLocation(),
727 diag::note_constexpr_tmpl_non_literal_return) << RT;
728 return false;
729 }
Richard Smith9f569cc2011-10-01 02:31:28 +0000730 }
731
Richard Smith35340502012-01-13 04:54:00 +0000732 // - each of its parameter types shall be a literal type;
733 if (!CheckConstexprParameterTypes(*this, NewFD, CCK))
734 return false;
735
Richard Smith9f569cc2011-10-01 02:31:28 +0000736 return true;
737}
738
739/// Check the given declaration statement is legal within a constexpr function
740/// body. C++0x [dcl.constexpr]p3,p4.
741///
742/// \return true if the body is OK, false if we have diagnosed a problem.
743static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
744 DeclStmt *DS) {
745 // C++0x [dcl.constexpr]p3 and p4:
746 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
747 // contain only
748 for (DeclStmt::decl_iterator DclIt = DS->decl_begin(),
749 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
750 switch ((*DclIt)->getKind()) {
751 case Decl::StaticAssert:
752 case Decl::Using:
753 case Decl::UsingShadow:
754 case Decl::UsingDirective:
755 case Decl::UnresolvedUsingTypename:
756 // - static_assert-declarations
757 // - using-declarations,
758 // - using-directives,
759 continue;
760
761 case Decl::Typedef:
762 case Decl::TypeAlias: {
763 // - typedef declarations and alias-declarations that do not define
764 // classes or enumerations,
765 TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt);
766 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
767 // Don't allow variably-modified types in constexpr functions.
768 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
769 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
770 << TL.getSourceRange() << TL.getType()
771 << isa<CXXConstructorDecl>(Dcl);
772 return false;
773 }
774 continue;
775 }
776
777 case Decl::Enum:
778 case Decl::CXXRecord:
779 // As an extension, we allow the declaration (but not the definition) of
780 // classes and enumerations in all declarations, not just in typedef and
781 // alias declarations.
782 if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition()) {
783 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_type_definition)
784 << isa<CXXConstructorDecl>(Dcl);
785 return false;
786 }
787 continue;
788
789 case Decl::Var:
790 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_var_declaration)
791 << isa<CXXConstructorDecl>(Dcl);
792 return false;
793
794 default:
795 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
796 << isa<CXXConstructorDecl>(Dcl);
797 return false;
798 }
799 }
800
801 return true;
802}
803
804/// Check that the given field is initialized within a constexpr constructor.
805///
806/// \param Dcl The constexpr constructor being checked.
807/// \param Field The field being checked. This may be a member of an anonymous
808/// struct or union nested within the class being checked.
809/// \param Inits All declarations, including anonymous struct/union members and
810/// indirect members, for which any initialization was provided.
811/// \param Diagnosed Set to true if an error is produced.
812static void CheckConstexprCtorInitializer(Sema &SemaRef,
813 const FunctionDecl *Dcl,
814 FieldDecl *Field,
815 llvm::SmallSet<Decl*, 16> &Inits,
816 bool &Diagnosed) {
Douglas Gregord61db332011-10-10 17:22:13 +0000817 if (Field->isUnnamedBitfield())
818 return;
Richard Smith30ecfad2012-02-09 06:40:58 +0000819
820 if (Field->isAnonymousStructOrUnion() &&
821 Field->getType()->getAsCXXRecordDecl()->isEmpty())
822 return;
823
Richard Smith9f569cc2011-10-01 02:31:28 +0000824 if (!Inits.count(Field)) {
825 if (!Diagnosed) {
826 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
827 Diagnosed = true;
828 }
829 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
830 } else if (Field->isAnonymousStructOrUnion()) {
831 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
832 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
833 I != E; ++I)
834 // If an anonymous union contains an anonymous struct of which any member
835 // is initialized, all members must be initialized.
836 if (!RD->isUnion() || Inits.count(*I))
837 CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed);
838 }
839}
840
841/// Check the body for the given constexpr function declaration only contains
842/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
843///
844/// \return true if the body is OK, false if we have diagnosed a problem.
Richard Smithd79093a2012-02-05 02:30:54 +0000845bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body,
846 bool IsInstantiation) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000847 if (isa<CXXTryStmt>(Body)) {
Richard Smith5ba73e12012-02-04 00:33:54 +0000848 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +0000849 // The definition of a constexpr function shall satisfy the following
850 // constraints: [...]
851 // - its function-body shall be = delete, = default, or a
852 // compound-statement
853 //
Richard Smith5ba73e12012-02-04 00:33:54 +0000854 // C++11 [dcl.constexpr]p4:
Richard Smith9f569cc2011-10-01 02:31:28 +0000855 // In the definition of a constexpr constructor, [...]
856 // - its function-body shall not be a function-try-block;
857 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
858 << isa<CXXConstructorDecl>(Dcl);
859 return false;
860 }
861
862 // - its function-body shall be [...] a compound-statement that contains only
863 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
864
865 llvm::SmallVector<SourceLocation, 4> ReturnStmts;
866 for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(),
867 BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) {
868 switch ((*BodyIt)->getStmtClass()) {
869 case Stmt::NullStmtClass:
870 // - null statements,
871 continue;
872
873 case Stmt::DeclStmtClass:
874 // - static_assert-declarations
875 // - using-declarations,
876 // - using-directives,
877 // - typedef declarations and alias-declarations that do not define
878 // classes or enumerations,
879 if (!CheckConstexprDeclStmt(*this, Dcl, cast<DeclStmt>(*BodyIt)))
880 return false;
881 continue;
882
883 case Stmt::ReturnStmtClass:
884 // - and exactly one return statement;
885 if (isa<CXXConstructorDecl>(Dcl))
886 break;
887
888 ReturnStmts.push_back((*BodyIt)->getLocStart());
889 // FIXME
890 // - every constructor call and implicit conversion used in initializing
891 // the return value shall be one of those allowed in a constant
892 // expression.
893 // Deal with this as part of a general check that the function can produce
894 // a constant expression (for [dcl.constexpr]p5).
895 continue;
896
897 default:
898 break;
899 }
900
901 Diag((*BodyIt)->getLocStart(), diag::err_constexpr_body_invalid_stmt)
902 << isa<CXXConstructorDecl>(Dcl);
903 return false;
904 }
905
906 if (const CXXConstructorDecl *Constructor
907 = dyn_cast<CXXConstructorDecl>(Dcl)) {
908 const CXXRecordDecl *RD = Constructor->getParent();
Richard Smith30ecfad2012-02-09 06:40:58 +0000909 // DR1359:
910 // - every non-variant non-static data member and base class sub-object
911 // shall be initialized;
912 // - if the class is a non-empty union, or for each non-empty anonymous
913 // union member of a non-union class, exactly one non-static data member
914 // shall be initialized;
Richard Smith9f569cc2011-10-01 02:31:28 +0000915 if (RD->isUnion()) {
Richard Smith30ecfad2012-02-09 06:40:58 +0000916 if (Constructor->getNumCtorInitializers() == 0 && !RD->isEmpty()) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000917 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
918 return false;
919 }
Richard Smith6e433752011-10-10 16:38:04 +0000920 } else if (!Constructor->isDependentContext() &&
921 !Constructor->isDelegatingConstructor()) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000922 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
923
924 // Skip detailed checking if we have enough initializers, and we would
925 // allow at most one initializer per member.
926 bool AnyAnonStructUnionMembers = false;
927 unsigned Fields = 0;
928 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
929 E = RD->field_end(); I != E; ++I, ++Fields) {
930 if ((*I)->isAnonymousStructOrUnion()) {
931 AnyAnonStructUnionMembers = true;
932 break;
933 }
934 }
935 if (AnyAnonStructUnionMembers ||
936 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
937 // Check initialization of non-static data members. Base classes are
938 // always initialized so do not need to be checked. Dependent bases
939 // might not have initializers in the member initializer list.
940 llvm::SmallSet<Decl*, 16> Inits;
941 for (CXXConstructorDecl::init_const_iterator
942 I = Constructor->init_begin(), E = Constructor->init_end();
943 I != E; ++I) {
944 if (FieldDecl *FD = (*I)->getMember())
945 Inits.insert(FD);
946 else if (IndirectFieldDecl *ID = (*I)->getIndirectMember())
947 Inits.insert(ID->chain_begin(), ID->chain_end());
948 }
949
950 bool Diagnosed = false;
951 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
952 E = RD->field_end(); I != E; ++I)
953 CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed);
954 if (Diagnosed)
955 return false;
956 }
957 }
958
959 // FIXME
960 // - every constructor involved in initializing non-static data members
961 // and base class sub-objects shall be a constexpr constructor;
962 // - every assignment-expression that is an initializer-clause appearing
963 // directly or indirectly within a brace-or-equal-initializer for
964 // a non-static data member that is not named by a mem-initializer-id
965 // shall be a constant expression; and
966 // - every implicit conversion used in converting a constructor argument
967 // to the corresponding parameter type and converting
968 // a full-expression to the corresponding member type shall be one of
969 // those allowed in a constant expression.
970 // Deal with these as part of a general check that the function can produce
971 // a constant expression (for [dcl.constexpr]p5).
972 } else {
973 if (ReturnStmts.empty()) {
974 Diag(Dcl->getLocation(), diag::err_constexpr_body_no_return);
975 return false;
976 }
977 if (ReturnStmts.size() > 1) {
978 Diag(ReturnStmts.back(), diag::err_constexpr_body_multiple_return);
979 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
980 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
981 return false;
982 }
983 }
984
Richard Smith5ba73e12012-02-04 00:33:54 +0000985 // C++11 [dcl.constexpr]p5:
986 // if no function argument values exist such that the function invocation
987 // substitution would produce a constant expression, the program is
988 // ill-formed; no diagnostic required.
989 // C++11 [dcl.constexpr]p3:
990 // - every constructor call and implicit conversion used in initializing the
991 // return value shall be one of those allowed in a constant expression.
992 // C++11 [dcl.constexpr]p4:
993 // - every constructor involved in initializing non-static data members and
994 // base class sub-objects shall be a constexpr constructor.
Richard Smith745f5142012-01-27 01:14:48 +0000995 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith925d8e72012-02-08 06:14:53 +0000996 if (!IsInstantiation && !Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smith745f5142012-01-27 01:14:48 +0000997 Diag(Dcl->getLocation(), diag::err_constexpr_function_never_constant_expr)
998 << isa<CXXConstructorDecl>(Dcl);
999 for (size_t I = 0, N = Diags.size(); I != N; ++I)
1000 Diag(Diags[I].first, Diags[I].second);
1001 return false;
1002 }
1003
Richard Smith9f569cc2011-10-01 02:31:28 +00001004 return true;
1005}
1006
Douglas Gregorb48fe382008-10-31 09:07:45 +00001007/// isCurrentClassName - Determine whether the identifier II is the
1008/// name of the class type currently being defined. In the case of
1009/// nested classes, this will only return true if II is the name of
1010/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00001011bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1012 const CXXScopeSpec *SS) {
Douglas Gregorb862b8f2010-01-11 23:29:10 +00001013 assert(getLangOptions().CPlusPlus && "No class names in C!");
1014
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001015 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +00001016 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +00001017 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001018 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1019 } else
1020 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1021
Douglas Gregor6f7a17b2010-02-05 06:12:42 +00001022 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregorb48fe382008-10-31 09:07:45 +00001023 return &II == CurDecl->getIdentifier();
1024 else
1025 return false;
1026}
1027
Mike Stump1eb44332009-09-09 15:08:12 +00001028/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001029///
1030/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1031/// and returns NULL otherwise.
1032CXXBaseSpecifier *
1033Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1034 SourceRange SpecifierRange,
1035 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001036 TypeSourceInfo *TInfo,
1037 SourceLocation EllipsisLoc) {
Nick Lewycky56062202010-07-26 16:56:01 +00001038 QualType BaseType = TInfo->getType();
1039
Douglas Gregor2943aed2009-03-03 04:44:36 +00001040 // C++ [class.union]p1:
1041 // A union shall not have base classes.
1042 if (Class->isUnion()) {
1043 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1044 << SpecifierRange;
1045 return 0;
1046 }
1047
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001048 if (EllipsisLoc.isValid() &&
1049 !TInfo->getType()->containsUnexpandedParameterPack()) {
1050 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1051 << TInfo->getTypeLoc().getSourceRange();
1052 EllipsisLoc = SourceLocation();
1053 }
1054
Douglas Gregor2943aed2009-03-03 04:44:36 +00001055 if (BaseType->isDependentType())
Mike Stump1eb44332009-09-09 15:08:12 +00001056 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001057 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001058 Access, TInfo, EllipsisLoc);
Nick Lewycky56062202010-07-26 16:56:01 +00001059
1060 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001061
1062 // Base specifiers must be record types.
1063 if (!BaseType->isRecordType()) {
1064 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1065 return 0;
1066 }
1067
1068 // C++ [class.union]p1:
1069 // A union shall not be used as a base class.
1070 if (BaseType->isUnionType()) {
1071 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1072 return 0;
1073 }
1074
1075 // C++ [class.derived]p2:
1076 // The class-name in a base-specifier shall not be an incompletely
1077 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +00001078 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssonb7906612009-08-26 23:45:07 +00001079 PDiag(diag::err_incomplete_base_class)
John McCall572fc622010-08-17 07:23:57 +00001080 << SpecifierRange)) {
1081 Class->setInvalidDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001082 return 0;
John McCall572fc622010-08-17 07:23:57 +00001083 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001084
Eli Friedman1d954f62009-08-15 21:55:26 +00001085 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +00001086 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001087 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor952b0172010-02-11 01:04:33 +00001088 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001089 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedman1d954f62009-08-15 21:55:26 +00001090 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
1091 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +00001092
Anders Carlsson1d209272011-03-25 14:55:14 +00001093 // C++ [class]p3:
1094 // If a class is marked final and it appears as a base-type-specifier in
1095 // base-clause, the program is ill-formed.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001096 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
Anders Carlssondfc2f102011-01-22 17:51:53 +00001097 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1098 << CXXBaseDecl->getDeclName();
1099 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1100 << CXXBaseDecl->getDeclName();
1101 return 0;
1102 }
1103
John McCall572fc622010-08-17 07:23:57 +00001104 if (BaseDecl->isInvalidDecl())
1105 Class->setInvalidDecl();
Anders Carlsson51f94042009-12-03 17:49:57 +00001106
1107 // Create the base specifier.
Anders Carlsson51f94042009-12-03 17:49:57 +00001108 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001109 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001110 Access, TInfo, EllipsisLoc);
Anders Carlsson51f94042009-12-03 17:49:57 +00001111}
1112
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001113/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1114/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +00001115/// example:
1116/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001117/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallf312b1e2010-08-26 23:41:50 +00001118BaseResult
John McCalld226f652010-08-21 09:40:31 +00001119Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001120 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001121 ParsedType basetype, SourceLocation BaseLoc,
1122 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001123 if (!classdecl)
1124 return true;
1125
Douglas Gregor40808ce2009-03-09 23:48:35 +00001126 AdjustDeclIfTemplate(classdecl);
John McCalld226f652010-08-21 09:40:31 +00001127 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregor5fe8c042010-02-27 00:25:28 +00001128 if (!Class)
1129 return true;
1130
Nick Lewycky56062202010-07-26 16:56:01 +00001131 TypeSourceInfo *TInfo = 0;
1132 GetTypeFromParser(basetype, &TInfo);
Douglas Gregord0937222010-12-13 22:49:22 +00001133
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001134 if (EllipsisLoc.isInvalid() &&
1135 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregord0937222010-12-13 22:49:22 +00001136 UPPC_BaseType))
1137 return true;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001138
Douglas Gregor2943aed2009-03-03 04:44:36 +00001139 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001140 Virtual, Access, TInfo,
1141 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +00001142 return BaseSpec;
Mike Stump1eb44332009-09-09 15:08:12 +00001143
Douglas Gregor2943aed2009-03-03 04:44:36 +00001144 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001145}
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001146
Douglas Gregor2943aed2009-03-03 04:44:36 +00001147/// \brief Performs the actual work of attaching the given base class
1148/// specifiers to a C++ class.
1149bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1150 unsigned NumBases) {
1151 if (NumBases == 0)
1152 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001153
1154 // Used to keep track of which base types we have already seen, so
1155 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +00001156 // that the key is always the unqualified canonical type of the base
1157 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001158 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1159
1160 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +00001161 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +00001162 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +00001163 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001164 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +00001165 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +00001166 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001167 if (KnownBaseTypes[NewBaseType]) {
1168 // C++ [class.mi]p3:
1169 // A class shall not be specified as a direct base class of a
1170 // derived class more than once.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001171 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001172 diag::err_duplicate_base_class)
Chris Lattnerd1625842008-11-24 06:25:27 +00001173 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +00001174 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +00001175
1176 // Delete the duplicate base class specifier; we're going to
1177 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001178 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001179
1180 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001181 } else {
1182 // Okay, add this new base class.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001183 KnownBaseTypes[NewBaseType] = Bases[idx];
1184 Bases[NumGoodBases++] = Bases[idx];
Fariborz Jahanian91589022011-10-24 17:30:45 +00001185 if (const RecordType *Record = NewBaseType->getAs<RecordType>())
Fariborz Jahanian13c7fcc2011-10-21 22:27:12 +00001186 if (const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()))
1187 if (RD->hasAttr<WeakAttr>())
1188 Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context));
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001189 }
1190 }
1191
1192 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +00001193 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +00001194
1195 // Delete the remaining (good) base class specifiers, since their
1196 // data has been copied into the CXXRecordDecl.
1197 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001198 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001199
1200 return Invalid;
1201}
1202
1203/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1204/// class, after checking whether there are any duplicate base
1205/// classes.
Richard Trieu90ab75b2011-09-09 03:18:59 +00001206void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001207 unsigned NumBases) {
1208 if (!ClassDecl || !Bases || !NumBases)
1209 return;
1210
1211 AdjustDeclIfTemplate(ClassDecl);
John McCalld226f652010-08-21 09:40:31 +00001212 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor2943aed2009-03-03 04:44:36 +00001213 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001214}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001215
John McCall3cb0ebd2010-03-10 03:28:59 +00001216static CXXRecordDecl *GetClassForType(QualType T) {
1217 if (const RecordType *RT = T->getAs<RecordType>())
1218 return cast<CXXRecordDecl>(RT->getDecl());
1219 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
1220 return ICT->getDecl();
1221 else
1222 return 0;
1223}
1224
Douglas Gregora8f32e02009-10-06 17:59:45 +00001225/// \brief Determine whether the type \p Derived is a C++ class that is
1226/// derived from the type \p Base.
1227bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
1228 if (!getLangOptions().CPlusPlus)
1229 return false;
John McCall3cb0ebd2010-03-10 03:28:59 +00001230
1231 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1232 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001233 return false;
1234
John McCall3cb0ebd2010-03-10 03:28:59 +00001235 CXXRecordDecl *BaseRD = GetClassForType(Base);
1236 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001237 return false;
1238
John McCall86ff3082010-02-04 22:26:26 +00001239 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1240 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001241}
1242
1243/// \brief Determine whether the type \p Derived is a C++ class that is
1244/// derived from the type \p Base.
1245bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
1246 if (!getLangOptions().CPlusPlus)
1247 return false;
1248
John McCall3cb0ebd2010-03-10 03:28:59 +00001249 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1250 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001251 return false;
1252
John McCall3cb0ebd2010-03-10 03:28:59 +00001253 CXXRecordDecl *BaseRD = GetClassForType(Base);
1254 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001255 return false;
1256
Douglas Gregora8f32e02009-10-06 17:59:45 +00001257 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1258}
1259
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001260void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallf871d0c2010-08-07 06:22:56 +00001261 CXXCastPath &BasePathArray) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001262 assert(BasePathArray.empty() && "Base path array must be empty!");
1263 assert(Paths.isRecordingPaths() && "Must record paths!");
1264
1265 const CXXBasePath &Path = Paths.front();
1266
1267 // We first go backward and check if we have a virtual base.
1268 // FIXME: It would be better if CXXBasePath had the base specifier for
1269 // the nearest virtual base.
1270 unsigned Start = 0;
1271 for (unsigned I = Path.size(); I != 0; --I) {
1272 if (Path[I - 1].Base->isVirtual()) {
1273 Start = I - 1;
1274 break;
1275 }
1276 }
1277
1278 // Now add all bases.
1279 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallf871d0c2010-08-07 06:22:56 +00001280 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001281}
1282
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001283/// \brief Determine whether the given base path includes a virtual
1284/// base class.
John McCallf871d0c2010-08-07 06:22:56 +00001285bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1286 for (CXXCastPath::const_iterator B = BasePath.begin(),
1287 BEnd = BasePath.end();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001288 B != BEnd; ++B)
1289 if ((*B)->isVirtual())
1290 return true;
1291
1292 return false;
1293}
1294
Douglas Gregora8f32e02009-10-06 17:59:45 +00001295/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1296/// conversion (where Derived and Base are class types) is
1297/// well-formed, meaning that the conversion is unambiguous (and
1298/// that all of the base classes are accessible). Returns true
1299/// and emits a diagnostic if the code is ill-formed, returns false
1300/// otherwise. Loc is the location where this routine should point to
1301/// if there is an error, and Range is the source range to highlight
1302/// if there is an error.
1303bool
1304Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall58e6f342010-03-16 05:22:47 +00001305 unsigned InaccessibleBaseID,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001306 unsigned AmbigiousBaseConvID,
1307 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001308 DeclarationName Name,
John McCallf871d0c2010-08-07 06:22:56 +00001309 CXXCastPath *BasePath) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001310 // First, determine whether the path from Derived to Base is
1311 // ambiguous. This is slightly more expensive than checking whether
1312 // the Derived to Base conversion exists, because here we need to
1313 // explore multiple paths to determine if there is an ambiguity.
1314 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1315 /*DetectVirtual=*/false);
1316 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1317 assert(DerivationOkay &&
1318 "Can only be used with a derived-to-base conversion");
1319 (void)DerivationOkay;
1320
1321 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001322 if (InaccessibleBaseID) {
1323 // Check that the base class can be accessed.
1324 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1325 InaccessibleBaseID)) {
1326 case AR_inaccessible:
1327 return true;
1328 case AR_accessible:
1329 case AR_dependent:
1330 case AR_delayed:
1331 break;
Anders Carlssone25a96c2010-04-24 17:11:09 +00001332 }
John McCall6b2accb2010-02-10 09:31:12 +00001333 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001334
1335 // Build a base path if necessary.
1336 if (BasePath)
1337 BuildBasePathArray(Paths, *BasePath);
1338 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001339 }
1340
1341 // We know that the derived-to-base conversion is ambiguous, and
1342 // we're going to produce a diagnostic. Perform the derived-to-base
1343 // search just one more time to compute all of the possible paths so
1344 // that we can print them out. This is more expensive than any of
1345 // the previous derived-to-base checks we've done, but at this point
1346 // performance isn't as much of an issue.
1347 Paths.clear();
1348 Paths.setRecordingPaths(true);
1349 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1350 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1351 (void)StillOkay;
1352
1353 // Build up a textual representation of the ambiguous paths, e.g.,
1354 // D -> B -> A, that will be used to illustrate the ambiguous
1355 // conversions in the diagnostic. We only print one of the paths
1356 // to each base class subobject.
1357 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1358
1359 Diag(Loc, AmbigiousBaseConvID)
1360 << Derived << Base << PathDisplayStr << Range << Name;
1361 return true;
1362}
1363
1364bool
1365Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001366 SourceLocation Loc, SourceRange Range,
John McCallf871d0c2010-08-07 06:22:56 +00001367 CXXCastPath *BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001368 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001369 return CheckDerivedToBaseConversion(Derived, Base,
John McCall58e6f342010-03-16 05:22:47 +00001370 IgnoreAccess ? 0
1371 : diag::err_upcast_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001372 diag::err_ambiguous_derived_to_base_conv,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001373 Loc, Range, DeclarationName(),
1374 BasePath);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001375}
1376
1377
1378/// @brief Builds a string representing ambiguous paths from a
1379/// specific derived class to different subobjects of the same base
1380/// class.
1381///
1382/// This function builds a string that can be used in error messages
1383/// to show the different paths that one can take through the
1384/// inheritance hierarchy to go from the derived class to different
1385/// subobjects of a base class. The result looks something like this:
1386/// @code
1387/// struct D -> struct B -> struct A
1388/// struct D -> struct C -> struct A
1389/// @endcode
1390std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1391 std::string PathDisplayStr;
1392 std::set<unsigned> DisplayedPaths;
1393 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1394 Path != Paths.end(); ++Path) {
1395 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1396 // We haven't displayed a path to this particular base
1397 // class subobject yet.
1398 PathDisplayStr += "\n ";
1399 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1400 for (CXXBasePath::const_iterator Element = Path->begin();
1401 Element != Path->end(); ++Element)
1402 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1403 }
1404 }
1405
1406 return PathDisplayStr;
1407}
1408
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001409//===----------------------------------------------------------------------===//
1410// C++ class member Handling
1411//===----------------------------------------------------------------------===//
1412
Abramo Bagnara6206d532010-06-05 05:09:32 +00001413/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001414bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1415 SourceLocation ASLoc,
1416 SourceLocation ColonLoc,
1417 AttributeList *Attrs) {
Abramo Bagnara6206d532010-06-05 05:09:32 +00001418 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCalld226f652010-08-21 09:40:31 +00001419 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnara6206d532010-06-05 05:09:32 +00001420 ASLoc, ColonLoc);
1421 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001422 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnara6206d532010-06-05 05:09:32 +00001423}
1424
Anders Carlsson9e682d92011-01-20 05:57:14 +00001425/// CheckOverrideControl - Check C++0x override control semantics.
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001426void Sema::CheckOverrideControl(const Decl *D) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001427 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001428 if (!MD || !MD->isVirtual())
1429 return;
1430
Anders Carlsson3ffe1832011-01-20 06:33:26 +00001431 if (MD->isDependentContext())
1432 return;
1433
Anders Carlsson9e682d92011-01-20 05:57:14 +00001434 // C++0x [class.virtual]p3:
1435 // If a virtual function is marked with the virt-specifier override and does
1436 // not override a member function of a base class,
1437 // the program is ill-formed.
1438 bool HasOverriddenMethods =
1439 MD->begin_overridden_methods() != MD->end_overridden_methods();
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001440 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) {
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001441 Diag(MD->getLocation(),
Anders Carlsson9e682d92011-01-20 05:57:14 +00001442 diag::err_function_marked_override_not_overriding)
1443 << MD->getDeclName();
1444 return;
1445 }
1446}
1447
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001448/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
1449/// function overrides a virtual member function marked 'final', according to
1450/// C++0x [class.virtual]p3.
1451bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1452 const CXXMethodDecl *Old) {
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001453 if (!Old->hasAttr<FinalAttr>())
Anders Carlssonf89e0422011-01-23 21:07:30 +00001454 return false;
1455
1456 Diag(New->getLocation(), diag::err_final_function_overridden)
1457 << New->getDeclName();
1458 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1459 return true;
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001460}
1461
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001462/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1463/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith7a614d82011-06-11 17:19:42 +00001464/// bitfield width if there is one, 'InitExpr' specifies the initializer if
1465/// one has been parsed, and 'HasDeferredInit' is true if an initializer is
1466/// present but parsing it has been deferred.
John McCalld226f652010-08-21 09:40:31 +00001467Decl *
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001468Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +00001469 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001470 Expr *BW, const VirtSpecifiers &VS,
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00001471 bool HasDeferredInit) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001472 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00001473 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1474 DeclarationName Name = NameInfo.getName();
1475 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001476
1477 // For anonymous bitfields, the location should point to the type.
1478 if (Loc.isInvalid())
1479 Loc = D.getSourceRange().getBegin();
1480
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001481 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001482
John McCall4bde1e12010-06-04 08:34:12 +00001483 assert(isa<CXXRecordDecl>(CurContext));
John McCall67d1a672009-08-06 02:15:43 +00001484 assert(!DS.isFriendSpecified());
1485
Richard Smith1ab0d902011-06-25 02:28:38 +00001486 bool isFunc = D.isDeclarationOfFunction();
John McCall4bde1e12010-06-04 08:34:12 +00001487
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001488 // C++ 9.2p6: A member shall not be declared to have automatic storage
1489 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001490 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1491 // data members and cannot be applied to names declared const or static,
1492 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001493 switch (DS.getStorageClassSpec()) {
1494 case DeclSpec::SCS_unspecified:
1495 case DeclSpec::SCS_typedef:
1496 case DeclSpec::SCS_static:
1497 // FALL THROUGH.
1498 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +00001499 case DeclSpec::SCS_mutable:
1500 if (isFunc) {
1501 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001502 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +00001503 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001504 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +00001505
Sebastian Redla11f42f2008-11-17 23:24:37 +00001506 // FIXME: It would be nicer if the keyword was ignored only for this
1507 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001508 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redl669d5d72008-11-14 23:42:31 +00001509 }
1510 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001511 default:
1512 if (DS.getStorageClassSpecLoc().isValid())
1513 Diag(DS.getStorageClassSpecLoc(),
1514 diag::err_storageclass_invalid_for_member);
1515 else
1516 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
1517 D.getMutableDeclSpec().ClearStorageClassSpecs();
1518 }
1519
Sebastian Redl669d5d72008-11-14 23:42:31 +00001520 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1521 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +00001522 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001523
1524 Decl *Member;
Chris Lattner24793662009-03-05 22:45:59 +00001525 if (isInstField) {
Douglas Gregor922fff22010-10-13 22:19:53 +00001526 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorb5a01872011-10-09 18:55:59 +00001527
1528 // Data members must have identifiers for names.
1529 if (Name.getNameKind() != DeclarationName::Identifier) {
1530 Diag(Loc, diag::err_bad_variable_name)
1531 << Name;
1532 return 0;
1533 }
Douglas Gregor922fff22010-10-13 22:19:53 +00001534
Douglas Gregorf2503652011-09-21 14:40:46 +00001535 IdentifierInfo *II = Name.getAsIdentifierInfo();
1536
1537 // Member field could not be with "template" keyword.
1538 // So TemplateParameterLists should be empty in this case.
1539 if (TemplateParameterLists.size()) {
1540 TemplateParameterList* TemplateParams = TemplateParameterLists.get()[0];
1541 if (TemplateParams->size()) {
1542 // There is no such thing as a member field template.
1543 Diag(D.getIdentifierLoc(), diag::err_template_member)
1544 << II
1545 << SourceRange(TemplateParams->getTemplateLoc(),
1546 TemplateParams->getRAngleLoc());
1547 } else {
1548 // There is an extraneous 'template<>' for this member.
1549 Diag(TemplateParams->getTemplateLoc(),
1550 diag::err_template_member_noparams)
1551 << II
1552 << SourceRange(TemplateParams->getTemplateLoc(),
1553 TemplateParams->getRAngleLoc());
1554 }
1555 return 0;
1556 }
1557
Douglas Gregor922fff22010-10-13 22:19:53 +00001558 if (SS.isSet() && !SS.isInvalid()) {
1559 // The user provided a superfluous scope specifier inside a class
1560 // definition:
1561 //
1562 // class X {
1563 // int X::member;
1564 // };
1565 DeclContext *DC = 0;
1566 if ((DC = computeDeclContext(SS, false)) && DC->Equals(CurContext))
1567 Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification)
Douglas Gregor5d8419c2011-11-01 22:13:30 +00001568 << Name << FixItHint::CreateRemoval(SS.getRange());
Douglas Gregor922fff22010-10-13 22:19:53 +00001569 else
1570 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1571 << Name << SS.getRange();
Douglas Gregor5d8419c2011-11-01 22:13:30 +00001572
Douglas Gregor922fff22010-10-13 22:19:53 +00001573 SS.clear();
1574 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001575
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001576 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
Richard Smith7a614d82011-06-11 17:19:42 +00001577 HasDeferredInit, AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001578 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +00001579 } else {
Richard Smith7a614d82011-06-11 17:19:42 +00001580 assert(!HasDeferredInit);
1581
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00001582 Member = HandleDeclarator(S, D, move(TemplateParameterLists));
Chris Lattner6f8ce142009-03-05 23:03:49 +00001583 if (!Member) {
John McCalld226f652010-08-21 09:40:31 +00001584 return 0;
Chris Lattner6f8ce142009-03-05 23:03:49 +00001585 }
Chris Lattner8b963ef2009-03-05 23:01:03 +00001586
1587 // Non-instance-fields can't have a bitfield.
1588 if (BitWidth) {
1589 if (Member->isInvalidDecl()) {
1590 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00001591 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00001592 // C++ 9.6p3: A bit-field shall not be a static member.
1593 // "static member 'A' cannot be a bit-field"
1594 Diag(Loc, diag::err_static_not_bitfield)
1595 << Name << BitWidth->getSourceRange();
1596 } else if (isa<TypedefDecl>(Member)) {
1597 // "typedef member 'x' cannot be a bit-field"
1598 Diag(Loc, diag::err_typedef_not_bitfield)
1599 << Name << BitWidth->getSourceRange();
1600 } else {
1601 // A function typedef ("typedef int f(); f a;").
1602 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1603 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +00001604 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +00001605 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +00001606 }
Mike Stump1eb44332009-09-09 15:08:12 +00001607
Chris Lattner8b963ef2009-03-05 23:01:03 +00001608 BitWidth = 0;
1609 Member->setInvalidDecl();
1610 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001611
1612 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +00001613
Douglas Gregor37b372b2009-08-20 22:52:58 +00001614 // If we have declared a member function template, set the access of the
1615 // templated declaration as well.
1616 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1617 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +00001618 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001619
Anders Carlssonaae5af22011-01-20 04:34:22 +00001620 if (VS.isOverrideSpecified()) {
1621 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1622 if (!MD || !MD->isVirtual()) {
1623 Diag(Member->getLocStart(),
1624 diag::override_keyword_only_allowed_on_virtual_member_functions)
1625 << "override" << FixItHint::CreateRemoval(VS.getOverrideLoc());
Anders Carlsson9e682d92011-01-20 05:57:14 +00001626 } else
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001627 MD->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
Anders Carlssonaae5af22011-01-20 04:34:22 +00001628 }
1629 if (VS.isFinalSpecified()) {
1630 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1631 if (!MD || !MD->isVirtual()) {
1632 Diag(Member->getLocStart(),
1633 diag::override_keyword_only_allowed_on_virtual_member_functions)
1634 << "final" << FixItHint::CreateRemoval(VS.getFinalLoc());
Anders Carlsson9e682d92011-01-20 05:57:14 +00001635 } else
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001636 MD->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlssonaae5af22011-01-20 04:34:22 +00001637 }
Anders Carlsson9e682d92011-01-20 05:57:14 +00001638
Douglas Gregorf5251602011-03-08 17:10:18 +00001639 if (VS.getLastLocation().isValid()) {
1640 // Update the end location of a method that has a virt-specifiers.
1641 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1642 MD->setRangeEnd(VS.getLastLocation());
1643 }
1644
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001645 CheckOverrideControl(Member);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001646
Douglas Gregor10bd3682008-11-17 22:58:34 +00001647 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001648
John McCallb25b2952011-02-15 07:12:36 +00001649 if (isInstField)
Douglas Gregor44b43212008-12-11 16:49:14 +00001650 FieldCollector->Add(cast<FieldDecl>(Member));
John McCalld226f652010-08-21 09:40:31 +00001651 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001652}
1653
Richard Smith7a614d82011-06-11 17:19:42 +00001654/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
Richard Smith0ff6f8f2011-07-20 00:12:52 +00001655/// in-class initializer for a non-static C++ class member, and after
1656/// instantiating an in-class initializer in a class template. Such actions
1657/// are deferred until the class is complete.
Richard Smith7a614d82011-06-11 17:19:42 +00001658void
1659Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation EqualLoc,
1660 Expr *InitExpr) {
1661 FieldDecl *FD = cast<FieldDecl>(D);
1662
1663 if (!InitExpr) {
1664 FD->setInvalidDecl();
1665 FD->removeInClassInitializer();
1666 return;
1667 }
1668
Peter Collingbournefef21892011-10-23 18:59:44 +00001669 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
1670 FD->setInvalidDecl();
1671 FD->removeInClassInitializer();
1672 return;
1673 }
1674
Richard Smith7a614d82011-06-11 17:19:42 +00001675 ExprResult Init = InitExpr;
1676 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
1677 // FIXME: if there is no EqualLoc, this is list-initialization.
1678 Init = PerformCopyInitialization(
1679 InitializedEntity::InitializeMember(FD), EqualLoc, InitExpr);
1680 if (Init.isInvalid()) {
1681 FD->setInvalidDecl();
1682 return;
1683 }
1684
1685 CheckImplicitConversions(Init.get(), EqualLoc);
1686 }
1687
1688 // C++0x [class.base.init]p7:
1689 // The initialization of each base and member constitutes a
1690 // full-expression.
1691 Init = MaybeCreateExprWithCleanups(Init);
1692 if (Init.isInvalid()) {
1693 FD->setInvalidDecl();
1694 return;
1695 }
1696
1697 InitExpr = Init.release();
1698
1699 FD->setInClassInitializer(InitExpr);
1700}
1701
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001702/// \brief Find the direct and/or virtual base specifiers that
1703/// correspond to the given base type, for use in base initialization
1704/// within a constructor.
1705static bool FindBaseInitializer(Sema &SemaRef,
1706 CXXRecordDecl *ClassDecl,
1707 QualType BaseType,
1708 const CXXBaseSpecifier *&DirectBaseSpec,
1709 const CXXBaseSpecifier *&VirtualBaseSpec) {
1710 // First, check for a direct base class.
1711 DirectBaseSpec = 0;
1712 for (CXXRecordDecl::base_class_const_iterator Base
1713 = ClassDecl->bases_begin();
1714 Base != ClassDecl->bases_end(); ++Base) {
1715 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1716 // We found a direct base of this type. That's what we're
1717 // initializing.
1718 DirectBaseSpec = &*Base;
1719 break;
1720 }
1721 }
1722
1723 // Check for a virtual base class.
1724 // FIXME: We might be able to short-circuit this if we know in advance that
1725 // there are no virtual bases.
1726 VirtualBaseSpec = 0;
1727 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1728 // We haven't found a base yet; search the class hierarchy for a
1729 // virtual base class.
1730 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1731 /*DetectVirtual=*/false);
1732 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1733 BaseType, Paths)) {
1734 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1735 Path != Paths.end(); ++Path) {
1736 if (Path->back().Base->isVirtual()) {
1737 VirtualBaseSpec = Path->back().Base;
1738 break;
1739 }
1740 }
1741 }
1742 }
1743
1744 return DirectBaseSpec || VirtualBaseSpec;
1745}
1746
Sebastian Redl6df65482011-09-24 17:48:25 +00001747/// \brief Handle a C++ member initializer using braced-init-list syntax.
1748MemInitResult
1749Sema::ActOnMemInitializer(Decl *ConstructorD,
1750 Scope *S,
1751 CXXScopeSpec &SS,
1752 IdentifierInfo *MemberOrBase,
1753 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00001754 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00001755 SourceLocation IdLoc,
1756 Expr *InitList,
1757 SourceLocation EllipsisLoc) {
1758 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00001759 DS, IdLoc, MultiInitializer(InitList),
1760 EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00001761}
1762
1763/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallf312b1e2010-08-26 23:41:50 +00001764MemInitResult
John McCalld226f652010-08-21 09:40:31 +00001765Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001766 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001767 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001768 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00001769 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00001770 const DeclSpec &DS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001771 SourceLocation IdLoc,
1772 SourceLocation LParenLoc,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001773 Expr **Args, unsigned NumArgs,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001774 SourceLocation RParenLoc,
1775 SourceLocation EllipsisLoc) {
Sebastian Redl6df65482011-09-24 17:48:25 +00001776 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00001777 DS, IdLoc, MultiInitializer(LParenLoc, Args,
1778 NumArgs, RParenLoc),
Sebastian Redl6df65482011-09-24 17:48:25 +00001779 EllipsisLoc);
1780}
1781
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001782namespace {
1783
Kaelyn Uhraindc98cd02012-01-11 21:17:51 +00001784// Callback to only accept typo corrections that can be a valid C++ member
1785// intializer: either a non-static field member or a base class.
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001786class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
1787 public:
1788 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
1789 : ClassDecl(ClassDecl) {}
1790
1791 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
1792 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
1793 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
1794 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
1795 else
1796 return isa<TypeDecl>(ND);
1797 }
1798 return false;
1799 }
1800
1801 private:
1802 CXXRecordDecl *ClassDecl;
1803};
1804
1805}
1806
Sebastian Redl6df65482011-09-24 17:48:25 +00001807/// \brief Handle a C++ member initializer.
1808MemInitResult
1809Sema::BuildMemInitializer(Decl *ConstructorD,
1810 Scope *S,
1811 CXXScopeSpec &SS,
1812 IdentifierInfo *MemberOrBase,
1813 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00001814 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00001815 SourceLocation IdLoc,
1816 const MultiInitializer &Args,
1817 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001818 if (!ConstructorD)
1819 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001820
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001821 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00001822
1823 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00001824 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001825 if (!Constructor) {
1826 // The user wrote a constructor initializer on a function that is
1827 // not a C++ constructor. Ignore the error for now, because we may
1828 // have more member initializers coming; we'll diagnose it just
1829 // once in ActOnMemInitializers.
1830 return true;
1831 }
1832
1833 CXXRecordDecl *ClassDecl = Constructor->getParent();
1834
1835 // C++ [class.base.init]p2:
1836 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky7663f392010-11-20 01:29:55 +00001837 // constructor's class and, if not found in that scope, are looked
1838 // up in the scope containing the constructor's definition.
1839 // [Note: if the constructor's class contains a member with the
1840 // same name as a direct or virtual base class of the class, a
1841 // mem-initializer-id naming the member or base class and composed
1842 // of a single identifier refers to the class member. A
Douglas Gregor7ad83902008-11-05 04:29:56 +00001843 // mem-initializer-id for the hidden base class may be specified
1844 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00001845 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001846 // Look for a member, first.
Mike Stump1eb44332009-09-09 15:08:12 +00001847 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001848 = ClassDecl->lookup(MemberOrBase);
Francois Pichet87c2e122010-11-21 06:08:52 +00001849 if (Result.first != Result.second) {
Peter Collingbournedc69be22011-10-23 18:59:37 +00001850 ValueDecl *Member;
1851 if ((Member = dyn_cast<FieldDecl>(*Result.first)) ||
1852 (Member = dyn_cast<IndirectFieldDecl>(*Result.first))) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001853 if (EllipsisLoc.isValid())
1854 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redl6df65482011-09-24 17:48:25 +00001855 << MemberOrBase << SourceRange(IdLoc, Args.getEndLoc());
1856
1857 return BuildMemberInitializer(Member, Args, IdLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001858 }
Francois Pichet00eb3f92010-12-04 09:14:42 +00001859 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001860 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001861 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00001862 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00001863 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00001864
1865 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00001866 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikief2116622012-01-24 06:03:59 +00001867 } else if (DS.getTypeSpecType() == TST_decltype) {
1868 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCall2b194412009-12-21 10:41:20 +00001869 } else {
1870 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1871 LookupParsedName(R, S, &SS);
1872
1873 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1874 if (!TyD) {
1875 if (R.isAmbiguous()) return true;
1876
John McCallfd225442010-04-09 19:01:14 +00001877 // We don't want access-control diagnostics here.
1878 R.suppressDiagnostics();
1879
Douglas Gregor7a886e12010-01-19 06:46:48 +00001880 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1881 bool NotUnknownSpecialization = false;
1882 DeclContext *DC = computeDeclContext(SS, false);
1883 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1884 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1885
1886 if (!NotUnknownSpecialization) {
1887 // When the scope specifier can refer to a member of an unknown
1888 // specialization, we take it as a type name.
Douglas Gregore29425b2011-02-28 22:42:13 +00001889 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
1890 SS.getWithLocInContext(Context),
1891 *MemberOrBase, IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00001892 if (BaseType.isNull())
1893 return true;
1894
Douglas Gregor7a886e12010-01-19 06:46:48 +00001895 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00001896 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001897 }
1898 }
1899
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001900 // If no results were found, try to correct typos.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001901 TypoCorrection Corr;
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001902 MemInitializerValidatorCCC Validator(ClassDecl);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001903 if (R.empty() && BaseType.isNull() &&
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001904 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00001905 Validator, ClassDecl))) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001906 std::string CorrectedStr(Corr.getAsString(getLangOptions()));
1907 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOptions()));
1908 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001909 // We have found a non-static data member with a similar
1910 // name to what was typed; complain and initialize that
1911 // member.
1912 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1913 << MemberOrBase << true << CorrectedQuotedStr
1914 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1915 Diag(Member->getLocation(), diag::note_previous_decl)
1916 << CorrectedQuotedStr;
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001917
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001918 return BuildMemberInitializer(Member, Args, IdLoc);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001919 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001920 const CXXBaseSpecifier *DirectBaseSpec;
1921 const CXXBaseSpecifier *VirtualBaseSpec;
1922 if (FindBaseInitializer(*this, ClassDecl,
1923 Context.getTypeDeclType(Type),
1924 DirectBaseSpec, VirtualBaseSpec)) {
1925 // We have found a direct or virtual base class with a
1926 // similar name to what was typed; complain and initialize
1927 // that base class.
1928 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001929 << MemberOrBase << false << CorrectedQuotedStr
1930 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor0d535c82010-01-07 00:26:25 +00001931
1932 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1933 : VirtualBaseSpec;
1934 Diag(BaseSpec->getSourceRange().getBegin(),
1935 diag::note_base_class_specified_here)
1936 << BaseSpec->getType()
1937 << BaseSpec->getSourceRange();
1938
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001939 TyD = Type;
1940 }
1941 }
1942 }
1943
Douglas Gregor7a886e12010-01-19 06:46:48 +00001944 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001945 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redl6df65482011-09-24 17:48:25 +00001946 << MemberOrBase << SourceRange(IdLoc, Args.getEndLoc());
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001947 return true;
1948 }
John McCall2b194412009-12-21 10:41:20 +00001949 }
1950
Douglas Gregor7a886e12010-01-19 06:46:48 +00001951 if (BaseType.isNull()) {
1952 BaseType = Context.getTypeDeclType(TyD);
1953 if (SS.isSet()) {
1954 NestedNameSpecifier *Qualifier =
1955 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00001956
Douglas Gregor7a886e12010-01-19 06:46:48 +00001957 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001958 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001959 }
John McCall2b194412009-12-21 10:41:20 +00001960 }
1961 }
Mike Stump1eb44332009-09-09 15:08:12 +00001962
John McCalla93c9342009-12-07 02:54:59 +00001963 if (!TInfo)
1964 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001965
Sebastian Redl6df65482011-09-24 17:48:25 +00001966 return BuildBaseInitializer(BaseType, TInfo, Args, ClassDecl, EllipsisLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00001967}
1968
Chandler Carruth81c64772011-09-03 01:14:15 +00001969/// Checks a member initializer expression for cases where reference (or
1970/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth81c64772011-09-03 01:14:15 +00001971static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
1972 Expr *Init,
1973 SourceLocation IdLoc) {
1974 QualType MemberTy = Member->getType();
1975
1976 // We only handle pointers and references currently.
1977 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
1978 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
1979 return;
1980
1981 const bool IsPointer = MemberTy->isPointerType();
1982 if (IsPointer) {
1983 if (const UnaryOperator *Op
1984 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
1985 // The only case we're worried about with pointers requires taking the
1986 // address.
1987 if (Op->getOpcode() != UO_AddrOf)
1988 return;
1989
1990 Init = Op->getSubExpr();
1991 } else {
1992 // We only handle address-of expression initializers for pointers.
1993 return;
1994 }
1995 }
1996
Chandler Carruthbf3380a2011-09-03 02:21:57 +00001997 if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) {
1998 // Taking the address of a temporary will be diagnosed as a hard error.
1999 if (IsPointer)
2000 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002001
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002002 S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary)
2003 << Member << Init->getSourceRange();
2004 } else if (const DeclRefExpr *DRE
2005 = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
2006 // We only warn when referring to a non-reference parameter declaration.
2007 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2008 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth81c64772011-09-03 01:14:15 +00002009 return;
2010
2011 S.Diag(Init->getExprLoc(),
2012 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2013 : diag::warn_bind_ref_member_to_parameter)
2014 << Member << Parameter << Init->getSourceRange();
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002015 } else {
2016 // Other initializers are fine.
2017 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002018 }
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002019
2020 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2021 << (unsigned)IsPointer;
Chandler Carruth81c64772011-09-03 01:14:15 +00002022}
2023
John McCallb4190042009-11-04 23:02:40 +00002024/// Checks an initializer expression for use of uninitialized fields, such as
2025/// containing the field that is being initialized. Returns true if there is an
2026/// uninitialized field was used an updates the SourceLocation parameter; false
2027/// otherwise.
Nick Lewycky43ad1822010-06-15 07:32:55 +00002028static bool InitExprContainsUninitializedFields(const Stmt *S,
Francois Pichet00eb3f92010-12-04 09:14:42 +00002029 const ValueDecl *LhsField,
Nick Lewycky43ad1822010-06-15 07:32:55 +00002030 SourceLocation *L) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002031 assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField));
2032
Nick Lewycky43ad1822010-06-15 07:32:55 +00002033 if (isa<CallExpr>(S)) {
2034 // Do not descend into function calls or constructors, as the use
2035 // of an uninitialized field may be valid. One would have to inspect
2036 // the contents of the function/ctor to determine if it is safe or not.
2037 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
2038 // may be safe, depending on what the function/ctor does.
2039 return false;
2040 }
2041 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
2042 const NamedDecl *RhsField = ME->getMemberDecl();
Anders Carlsson175ffbf2010-10-06 02:43:25 +00002043
2044 if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) {
2045 // The member expression points to a static data member.
2046 assert(VD->isStaticDataMember() &&
2047 "Member points to non-static data member!");
Nick Lewyckyedd59112010-10-06 18:37:39 +00002048 (void)VD;
Anders Carlsson175ffbf2010-10-06 02:43:25 +00002049 return false;
2050 }
2051
2052 if (isa<EnumConstantDecl>(RhsField)) {
2053 // The member expression points to an enum.
2054 return false;
2055 }
2056
John McCallb4190042009-11-04 23:02:40 +00002057 if (RhsField == LhsField) {
2058 // Initializing a field with itself. Throw a warning.
2059 // But wait; there are exceptions!
2060 // Exception #1: The field may not belong to this record.
2061 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
Nick Lewycky43ad1822010-06-15 07:32:55 +00002062 const Expr *base = ME->getBase();
John McCallb4190042009-11-04 23:02:40 +00002063 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
2064 // Even though the field matches, it does not belong to this record.
2065 return false;
2066 }
2067 // None of the exceptions triggered; return true to indicate an
2068 // uninitialized field was used.
2069 *L = ME->getMemberLoc();
2070 return true;
2071 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002072 } else if (isa<UnaryExprOrTypeTraitExpr>(S)) {
Argyrios Kyrtzidisff8819b2010-09-21 10:47:20 +00002073 // sizeof/alignof doesn't reference contents, do not warn.
2074 return false;
2075 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) {
2076 // address-of doesn't reference contents (the pointer may be dereferenced
2077 // in the same expression but it would be rare; and weird).
2078 if (UOE->getOpcode() == UO_AddrOf)
2079 return false;
John McCallb4190042009-11-04 23:02:40 +00002080 }
John McCall7502c1d2011-02-13 04:07:26 +00002081 for (Stmt::const_child_range it = S->children(); it; ++it) {
Nick Lewycky43ad1822010-06-15 07:32:55 +00002082 if (!*it) {
2083 // An expression such as 'member(arg ?: "")' may trigger this.
John McCallb4190042009-11-04 23:02:40 +00002084 continue;
2085 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00002086 if (InitExprContainsUninitializedFields(*it, LhsField, L))
2087 return true;
John McCallb4190042009-11-04 23:02:40 +00002088 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00002089 return false;
John McCallb4190042009-11-04 23:02:40 +00002090}
2091
John McCallf312b1e2010-08-26 23:41:50 +00002092MemInitResult
Sebastian Redl6df65482011-09-24 17:48:25 +00002093Sema::BuildMemberInitializer(ValueDecl *Member,
2094 const MultiInitializer &Args,
2095 SourceLocation IdLoc) {
Chandler Carruth894aed92010-12-06 09:23:57 +00002096 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2097 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2098 assert((DirectMember || IndirectMember) &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00002099 "Member must be a FieldDecl or IndirectFieldDecl");
2100
Peter Collingbournefef21892011-10-23 18:59:44 +00002101 if (Args.DiagnoseUnexpandedParameterPack(*this))
2102 return true;
2103
Douglas Gregor464b2f02010-11-05 22:21:31 +00002104 if (Member->isInvalidDecl())
2105 return true;
Chandler Carruth894aed92010-12-06 09:23:57 +00002106
John McCallb4190042009-11-04 23:02:40 +00002107 // Diagnose value-uses of fields to initialize themselves, e.g.
2108 // foo(foo)
2109 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00002110 // TODO: implement -Wuninitialized and fold this into that framework.
Sebastian Redl6df65482011-09-24 17:48:25 +00002111 for (MultiInitializer::iterator I = Args.begin(), E = Args.end();
2112 I != E; ++I) {
John McCallb4190042009-11-04 23:02:40 +00002113 SourceLocation L;
Sebastian Redl6df65482011-09-24 17:48:25 +00002114 Expr *Arg = *I;
2115 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Arg))
2116 Arg = DIE->getInit();
2117 if (InitExprContainsUninitializedFields(Arg, Member, &L)) {
John McCallb4190042009-11-04 23:02:40 +00002118 // FIXME: Return true in the case when other fields are used before being
2119 // uninitialized. For example, let this field be the i'th field. When
2120 // initializing the i'th field, throw a warning if any of the >= i'th
2121 // fields are used, as they are not yet initialized.
2122 // Right now we are only handling the case where the i'th field uses
2123 // itself in its initializer.
2124 Diag(L, diag::warn_field_is_uninit);
2125 }
2126 }
2127
Sebastian Redl6df65482011-09-24 17:48:25 +00002128 bool HasDependentArg = Args.isTypeDependent();
Eli Friedman59c04372009-07-29 19:44:27 +00002129
Chandler Carruth894aed92010-12-06 09:23:57 +00002130 Expr *Init;
Eli Friedman0f2b97d2010-07-24 21:19:15 +00002131 if (Member->getType()->isDependentType() || HasDependentArg) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002132 // Can't check initialization for a member of dependent type or when
2133 // any of the arguments are type-dependent expressions.
Sebastian Redl6df65482011-09-24 17:48:25 +00002134 Init = Args.CreateInitExpr(Context,Member->getType().getNonReferenceType());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002135
John McCallf85e1932011-06-15 23:02:42 +00002136 DiscardCleanupsInEvaluationContext();
Chandler Carruth894aed92010-12-06 09:23:57 +00002137 } else {
2138 // Initialize the member.
2139 InitializedEntity MemberEntity =
2140 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2141 : InitializedEntity::InitializeMember(IndirectMember, 0);
2142 InitializationKind Kind =
Sebastian Redl6df65482011-09-24 17:48:25 +00002143 InitializationKind::CreateDirect(IdLoc, Args.getStartLoc(),
2144 Args.getEndLoc());
John McCallb4eb64d2010-10-08 02:01:28 +00002145
Sebastian Redl6df65482011-09-24 17:48:25 +00002146 ExprResult MemberInit = Args.PerformInit(*this, MemberEntity, Kind);
Chandler Carruth894aed92010-12-06 09:23:57 +00002147 if (MemberInit.isInvalid())
2148 return true;
2149
Sebastian Redl6df65482011-09-24 17:48:25 +00002150 CheckImplicitConversions(MemberInit.get(), Args.getStartLoc());
Chandler Carruth894aed92010-12-06 09:23:57 +00002151
2152 // C++0x [class.base.init]p7:
2153 // The initialization of each base and member constitutes a
2154 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00002155 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Chandler Carruth894aed92010-12-06 09:23:57 +00002156 if (MemberInit.isInvalid())
2157 return true;
2158
2159 // If we are in a dependent context, template instantiation will
2160 // perform this type-checking again. Just save the arguments that we
2161 // received in a ParenListExpr.
2162 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2163 // of the information that we have about the member
2164 // initializer. However, deconstructing the ASTs is a dicey process,
2165 // and this approach is far more likely to get the corner cases right.
Chandler Carruth81c64772011-09-03 01:14:15 +00002166 if (CurContext->isDependentContext()) {
Sebastian Redl6df65482011-09-24 17:48:25 +00002167 Init = Args.CreateInitExpr(Context,
2168 Member->getType().getNonReferenceType());
Chandler Carruth81c64772011-09-03 01:14:15 +00002169 } else {
Chandler Carruth894aed92010-12-06 09:23:57 +00002170 Init = MemberInit.get();
Chandler Carruth81c64772011-09-03 01:14:15 +00002171 CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc);
2172 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002173 }
2174
Chandler Carruth894aed92010-12-06 09:23:57 +00002175 if (DirectMember) {
Sean Huntcbb67482011-01-08 20:30:50 +00002176 return new (Context) CXXCtorInitializer(Context, DirectMember,
Sebastian Redl6df65482011-09-24 17:48:25 +00002177 IdLoc, Args.getStartLoc(),
2178 Init, Args.getEndLoc());
Chandler Carruth894aed92010-12-06 09:23:57 +00002179 } else {
Sean Huntcbb67482011-01-08 20:30:50 +00002180 return new (Context) CXXCtorInitializer(Context, IndirectMember,
Sebastian Redl6df65482011-09-24 17:48:25 +00002181 IdLoc, Args.getStartLoc(),
2182 Init, Args.getEndLoc());
Chandler Carruth894aed92010-12-06 09:23:57 +00002183 }
Eli Friedman59c04372009-07-29 19:44:27 +00002184}
2185
John McCallf312b1e2010-08-26 23:41:50 +00002186MemInitResult
Sean Hunt97fcc492011-01-08 19:20:43 +00002187Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00002188 const MultiInitializer &Args,
Sean Hunt41717662011-02-26 19:13:13 +00002189 CXXRecordDecl *ClassDecl) {
Douglas Gregor76852c22011-11-01 01:16:03 +00002190 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sean Hunt97fcc492011-01-08 19:20:43 +00002191 if (!LangOpts.CPlusPlus0x)
Douglas Gregor76852c22011-11-01 01:16:03 +00002192 return Diag(NameLoc, diag::err_delegating_ctor)
Sean Hunt97fcc492011-01-08 19:20:43 +00002193 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor76852c22011-11-01 01:16:03 +00002194 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redlf9c32eb2011-03-12 13:53:51 +00002195
Sean Hunt41717662011-02-26 19:13:13 +00002196 // Initialize the object.
2197 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2198 QualType(ClassDecl->getTypeForDecl(), 0));
2199 InitializationKind Kind =
Sebastian Redl6df65482011-09-24 17:48:25 +00002200 InitializationKind::CreateDirect(NameLoc, Args.getStartLoc(),
2201 Args.getEndLoc());
Sean Hunt41717662011-02-26 19:13:13 +00002202
Sebastian Redl6df65482011-09-24 17:48:25 +00002203 ExprResult DelegationInit = Args.PerformInit(*this, DelegationEntity, Kind);
Sean Hunt41717662011-02-26 19:13:13 +00002204 if (DelegationInit.isInvalid())
2205 return true;
2206
Matt Beaumont-Gay2eb0ce32011-11-01 18:10:22 +00002207 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2208 "Delegating constructor with no target?");
Sean Hunt41717662011-02-26 19:13:13 +00002209
Sebastian Redl6df65482011-09-24 17:48:25 +00002210 CheckImplicitConversions(DelegationInit.get(), Args.getStartLoc());
Sean Hunt41717662011-02-26 19:13:13 +00002211
2212 // C++0x [class.base.init]p7:
2213 // The initialization of each base and member constitutes a
2214 // full-expression.
2215 DelegationInit = MaybeCreateExprWithCleanups(DelegationInit);
2216 if (DelegationInit.isInvalid())
2217 return true;
2218
Douglas Gregor76852c22011-11-01 01:16:03 +00002219 return new (Context) CXXCtorInitializer(Context, TInfo, Args.getStartLoc(),
Sean Hunt41717662011-02-26 19:13:13 +00002220 DelegationInit.takeAs<Expr>(),
Sebastian Redl6df65482011-09-24 17:48:25 +00002221 Args.getEndLoc());
Sean Hunt97fcc492011-01-08 19:20:43 +00002222}
2223
2224MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00002225Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00002226 const MultiInitializer &Args,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002227 CXXRecordDecl *ClassDecl,
2228 SourceLocation EllipsisLoc) {
Sebastian Redl6df65482011-09-24 17:48:25 +00002229 bool HasDependentArg = Args.isTypeDependent();
Eli Friedman59c04372009-07-29 19:44:27 +00002230
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002231 SourceLocation BaseLoc
2232 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redl6df65482011-09-24 17:48:25 +00002233
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002234 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2235 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2236 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2237
2238 // C++ [class.base.init]p2:
2239 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00002240 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002241 // of that class, the mem-initializer is ill-formed. A
2242 // mem-initializer-list can initialize a base class using any
2243 // name that denotes that base class type.
2244 bool Dependent = BaseType->isDependentType() || HasDependentArg;
2245
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002246 if (EllipsisLoc.isValid()) {
2247 // This is a pack expansion.
2248 if (!BaseType->containsUnexpandedParameterPack()) {
2249 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redl6df65482011-09-24 17:48:25 +00002250 << SourceRange(BaseLoc, Args.getEndLoc());
2251
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002252 EllipsisLoc = SourceLocation();
2253 }
2254 } else {
2255 // Check for any unexpanded parameter packs.
2256 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2257 return true;
Sebastian Redl6df65482011-09-24 17:48:25 +00002258
2259 if (Args.DiagnoseUnexpandedParameterPack(*this))
2260 return true;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002261 }
Sebastian Redl6df65482011-09-24 17:48:25 +00002262
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002263 // Check for direct and virtual base classes.
2264 const CXXBaseSpecifier *DirectBaseSpec = 0;
2265 const CXXBaseSpecifier *VirtualBaseSpec = 0;
2266 if (!Dependent) {
Sean Hunt97fcc492011-01-08 19:20:43 +00002267 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2268 BaseType))
Douglas Gregor76852c22011-11-01 01:16:03 +00002269 return BuildDelegatingInitializer(BaseTInfo, Args, ClassDecl);
Sean Hunt97fcc492011-01-08 19:20:43 +00002270
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002271 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2272 VirtualBaseSpec);
2273
2274 // C++ [base.class.init]p2:
2275 // Unless the mem-initializer-id names a nonstatic data member of the
2276 // constructor's class or a direct or virtual base of that class, the
2277 // mem-initializer is ill-formed.
2278 if (!DirectBaseSpec && !VirtualBaseSpec) {
2279 // If the class has any dependent bases, then it's possible that
2280 // one of those types will resolve to the same type as
2281 // BaseType. Therefore, just treat this as a dependent base
2282 // class initialization. FIXME: Should we try to check the
2283 // initialization anyway? It seems odd.
2284 if (ClassDecl->hasAnyDependentBases())
2285 Dependent = true;
2286 else
2287 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2288 << BaseType << Context.getTypeDeclType(ClassDecl)
2289 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2290 }
2291 }
2292
2293 if (Dependent) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002294 // Can't check initialization for a base of dependent type or when
2295 // any of the arguments are type-dependent expressions.
Sebastian Redl6df65482011-09-24 17:48:25 +00002296 Expr *BaseInit = Args.CreateInitExpr(Context, BaseType);
Eli Friedman59c04372009-07-29 19:44:27 +00002297
John McCallf85e1932011-06-15 23:02:42 +00002298 DiscardCleanupsInEvaluationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002299
Sebastian Redl6df65482011-09-24 17:48:25 +00002300 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2301 /*IsVirtual=*/false,
2302 Args.getStartLoc(), BaseInit,
2303 Args.getEndLoc(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002304 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002305
2306 // C++ [base.class.init]p2:
2307 // If a mem-initializer-id is ambiguous because it designates both
2308 // a direct non-virtual base class and an inherited virtual base
2309 // class, the mem-initializer is ill-formed.
2310 if (DirectBaseSpec && VirtualBaseSpec)
2311 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002312 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002313
2314 CXXBaseSpecifier *BaseSpec
2315 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
2316 if (!BaseSpec)
2317 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
2318
2319 // Initialize the base.
2320 InitializedEntity BaseEntity =
Anders Carlsson711f34a2010-04-21 19:52:01 +00002321 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002322 InitializationKind Kind =
Sebastian Redl6df65482011-09-24 17:48:25 +00002323 InitializationKind::CreateDirect(BaseLoc, Args.getStartLoc(),
2324 Args.getEndLoc());
2325
2326 ExprResult BaseInit = Args.PerformInit(*this, BaseEntity, Kind);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002327 if (BaseInit.isInvalid())
2328 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00002329
Sebastian Redl6df65482011-09-24 17:48:25 +00002330 CheckImplicitConversions(BaseInit.get(), Args.getStartLoc());
2331
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002332 // C++0x [class.base.init]p7:
2333 // The initialization of each base and member constitutes a
2334 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00002335 BaseInit = MaybeCreateExprWithCleanups(BaseInit);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002336 if (BaseInit.isInvalid())
2337 return true;
2338
2339 // If we are in a dependent context, template instantiation will
2340 // perform this type-checking again. Just save the arguments that we
2341 // received in a ParenListExpr.
2342 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2343 // of the information that we have about the base
2344 // initializer. However, deconstructing the ASTs is a dicey process,
2345 // and this approach is far more likely to get the corner cases right.
Sebastian Redl6df65482011-09-24 17:48:25 +00002346 if (CurContext->isDependentContext())
2347 BaseInit = Owned(Args.CreateInitExpr(Context, BaseType));
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002348
Sean Huntcbb67482011-01-08 20:30:50 +00002349 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00002350 BaseSpec->isVirtual(),
2351 Args.getStartLoc(),
2352 BaseInit.takeAs<Expr>(),
2353 Args.getEndLoc(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002354}
2355
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002356// Create a static_cast\<T&&>(expr).
2357static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
2358 QualType ExprType = E->getType();
2359 QualType TargetType = SemaRef.Context.getRValueReferenceType(ExprType);
2360 SourceLocation ExprLoc = E->getLocStart();
2361 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2362 TargetType, ExprLoc);
2363
2364 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2365 SourceRange(ExprLoc, ExprLoc),
2366 E->getSourceRange()).take();
2367}
2368
Anders Carlssone5ef7402010-04-23 03:10:23 +00002369/// ImplicitInitializerKind - How an implicit base or member initializer should
2370/// initialize its base or member.
2371enum ImplicitInitializerKind {
2372 IIK_Default,
2373 IIK_Copy,
2374 IIK_Move
2375};
2376
Anders Carlssondefefd22010-04-23 02:00:02 +00002377static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002378BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002379 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002380 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00002381 bool IsInheritedVirtualBase,
Sean Huntcbb67482011-01-08 20:30:50 +00002382 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00002383 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00002384 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2385 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00002386
John McCall60d7b3a2010-08-24 06:29:42 +00002387 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002388
2389 switch (ImplicitInitKind) {
2390 case IIK_Default: {
2391 InitializationKind InitKind
2392 = InitializationKind::CreateDefault(Constructor->getLocation());
2393 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
2394 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00002395 MultiExprArg(SemaRef, 0, 0));
Anders Carlssone5ef7402010-04-23 03:10:23 +00002396 break;
2397 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002398
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002399 case IIK_Move:
Anders Carlssone5ef7402010-04-23 03:10:23 +00002400 case IIK_Copy: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002401 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002402 ParmVarDecl *Param = Constructor->getParamDecl(0);
2403 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedmancf7c14c2012-01-16 21:00:51 +00002404
Anders Carlssone5ef7402010-04-23 03:10:23 +00002405 Expr *CopyCtorArg =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002406 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
2407 SourceLocation(), Param,
John McCallf89e55a2010-11-18 06:31:45 +00002408 Constructor->getLocation(), ParamType,
2409 VK_LValue, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002410
Eli Friedman5f2987c2012-02-02 03:46:19 +00002411 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
2412
Anders Carlssonc7957502010-04-24 22:02:54 +00002413 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00002414 QualType ArgTy =
2415 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2416 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00002417
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002418 if (Moving) {
2419 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2420 }
2421
John McCallf871d0c2010-08-07 06:22:56 +00002422 CXXCastPath BasePath;
2423 BasePath.push_back(BaseSpec);
John Wiegley429bb272011-04-08 18:41:53 +00002424 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2425 CK_UncheckedDerivedToBase,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002426 Moving ? VK_XValue : VK_LValue,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002427 &BasePath).take();
Anders Carlssonc7957502010-04-24 22:02:54 +00002428
Anders Carlssone5ef7402010-04-23 03:10:23 +00002429 InitializationKind InitKind
2430 = InitializationKind::CreateDirect(Constructor->getLocation(),
2431 SourceLocation(), SourceLocation());
2432 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
2433 &CopyCtorArg, 1);
2434 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00002435 MultiExprArg(&CopyCtorArg, 1));
Anders Carlssone5ef7402010-04-23 03:10:23 +00002436 break;
2437 }
Anders Carlssone5ef7402010-04-23 03:10:23 +00002438 }
John McCall9ae2f072010-08-23 23:25:46 +00002439
Douglas Gregor53c374f2010-12-07 00:41:46 +00002440 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00002441 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00002442 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00002443
Anders Carlssondefefd22010-04-23 02:00:02 +00002444 CXXBaseInit =
Sean Huntcbb67482011-01-08 20:30:50 +00002445 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlsson84688f22010-04-20 23:11:20 +00002446 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2447 SourceLocation()),
2448 BaseSpec->isVirtual(),
2449 SourceLocation(),
2450 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002451 SourceLocation(),
Anders Carlsson84688f22010-04-20 23:11:20 +00002452 SourceLocation());
2453
Anders Carlssondefefd22010-04-23 02:00:02 +00002454 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00002455}
2456
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002457static bool RefersToRValueRef(Expr *MemRef) {
2458 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2459 return Referenced->getType()->isRValueReferenceType();
2460}
2461
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002462static bool
2463BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002464 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002465 FieldDecl *Field, IndirectFieldDecl *Indirect,
Sean Huntcbb67482011-01-08 20:30:50 +00002466 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002467 if (Field->isInvalidDecl())
2468 return true;
2469
Chandler Carruthf186b542010-06-29 23:50:44 +00002470 SourceLocation Loc = Constructor->getLocation();
2471
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002472 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2473 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002474 ParmVarDecl *Param = Constructor->getParamDecl(0);
2475 QualType ParamType = Param->getType().getNonReferenceType();
John McCallb77115d2011-06-17 00:18:42 +00002476
2477 // Suppress copying zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002478 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
2479 return false;
Douglas Gregorddb21472011-11-02 23:04:16 +00002480
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002481 Expr *MemberExprBase =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002482 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
2483 SourceLocation(), Param,
John McCallf89e55a2010-11-18 06:31:45 +00002484 Loc, ParamType, VK_LValue, 0);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002485
Eli Friedman5f2987c2012-02-02 03:46:19 +00002486 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
2487
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002488 if (Moving) {
2489 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2490 }
2491
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002492 // Build a reference to this field within the parameter.
2493 CXXScopeSpec SS;
2494 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2495 Sema::LookupMemberName);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002496 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2497 : cast<ValueDecl>(Field), AS_public);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002498 MemberLookup.resolveKind();
Sebastian Redl74e611a2011-09-04 18:14:28 +00002499 ExprResult CtorArg
John McCall9ae2f072010-08-23 23:25:46 +00002500 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002501 ParamType, Loc,
2502 /*IsArrow=*/false,
2503 SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002504 /*TemplateKWLoc=*/SourceLocation(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002505 /*FirstQualifierInScope=*/0,
2506 MemberLookup,
2507 /*TemplateArgs=*/0);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002508 if (CtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002509 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002510
2511 // C++11 [class.copy]p15:
2512 // - if a member m has rvalue reference type T&&, it is direct-initialized
2513 // with static_cast<T&&>(x.m);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002514 if (RefersToRValueRef(CtorArg.get())) {
2515 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002516 }
2517
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002518 // When the field we are copying is an array, create index variables for
2519 // each dimension of the array. We use these index variables to subscript
2520 // the source array, and other clients (e.g., CodeGen) will perform the
2521 // necessary iteration with these index variables.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002522 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002523 QualType BaseType = Field->getType();
2524 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002525 bool InitializingArray = false;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002526 while (const ConstantArrayType *Array
2527 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002528 InitializingArray = true;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002529 // Create the iteration variable for this array index.
2530 IdentifierInfo *IterationVarName = 0;
2531 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002532 SmallString<8> Str;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002533 llvm::raw_svector_ostream OS(Str);
2534 OS << "__i" << IndexVariables.size();
2535 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
2536 }
2537 VarDecl *IterationVar
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002538 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002539 IterationVarName, SizeType,
2540 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00002541 SC_None, SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002542 IndexVariables.push_back(IterationVar);
2543
2544 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00002545 ExprResult IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00002546 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002547 assert(!IterationVarRef.isInvalid() &&
2548 "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00002549 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
2550 assert(!IterationVarRef.isInvalid() &&
2551 "Conversion of invented variable cannot fail!");
Sebastian Redl74e611a2011-09-04 18:14:28 +00002552
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002553 // Subscript the array with this iteration variable.
Sebastian Redl74e611a2011-09-04 18:14:28 +00002554 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCall9ae2f072010-08-23 23:25:46 +00002555 IterationVarRef.take(),
Sebastian Redl74e611a2011-09-04 18:14:28 +00002556 Loc);
2557 if (CtorArg.isInvalid())
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002558 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002559
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002560 BaseType = Array->getElementType();
2561 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002562
2563 // The array subscript expression is an lvalue, which is wrong for moving.
2564 if (Moving && InitializingArray)
Sebastian Redl74e611a2011-09-04 18:14:28 +00002565 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002566
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002567 // Construct the entity that we will be initializing. For an array, this
2568 // will be first element in the array, which may require several levels
2569 // of array-subscript entities.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002570 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002571 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002572 if (Indirect)
2573 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
2574 else
2575 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002576 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
2577 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
2578 0,
2579 Entities.back()));
2580
2581 // Direct-initialize to use the copy constructor.
2582 InitializationKind InitKind =
2583 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
2584
Sebastian Redl74e611a2011-09-04 18:14:28 +00002585 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002586 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002587 &CtorArgE, 1);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002588
John McCall60d7b3a2010-08-24 06:29:42 +00002589 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002590 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002591 MultiExprArg(&CtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00002592 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002593 if (MemberInit.isInvalid())
2594 return true;
2595
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002596 if (Indirect) {
2597 assert(IndexVariables.size() == 0 &&
2598 "Indirect field improperly initialized");
2599 CXXMemberInit
2600 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2601 Loc, Loc,
2602 MemberInit.takeAs<Expr>(),
2603 Loc);
2604 } else
2605 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
2606 Loc, MemberInit.takeAs<Expr>(),
2607 Loc,
2608 IndexVariables.data(),
2609 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00002610 return false;
2611 }
2612
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002613 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
2614
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002615 QualType FieldBaseElementType =
2616 SemaRef.Context.getBaseElementType(Field->getType());
2617
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002618 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002619 InitializedEntity InitEntity
2620 = Indirect? InitializedEntity::InitializeMember(Indirect)
2621 : InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002622 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00002623 InitializationKind::CreateDefault(Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002624
2625 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00002626 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00002627 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCall9ae2f072010-08-23 23:25:46 +00002628
Douglas Gregor53c374f2010-12-07 00:41:46 +00002629 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002630 if (MemberInit.isInvalid())
2631 return true;
2632
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002633 if (Indirect)
2634 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2635 Indirect, Loc,
2636 Loc,
2637 MemberInit.get(),
2638 Loc);
2639 else
2640 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2641 Field, Loc, Loc,
2642 MemberInit.get(),
2643 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002644 return false;
2645 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002646
Sean Hunt1f2f3842011-05-17 00:19:05 +00002647 if (!Field->getParent()->isUnion()) {
2648 if (FieldBaseElementType->isReferenceType()) {
2649 SemaRef.Diag(Constructor->getLocation(),
2650 diag::err_uninitialized_member_in_ctor)
2651 << (int)Constructor->isImplicit()
2652 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2653 << 0 << Field->getDeclName();
2654 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2655 return true;
2656 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002657
Sean Hunt1f2f3842011-05-17 00:19:05 +00002658 if (FieldBaseElementType.isConstQualified()) {
2659 SemaRef.Diag(Constructor->getLocation(),
2660 diag::err_uninitialized_member_in_ctor)
2661 << (int)Constructor->isImplicit()
2662 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2663 << 1 << Field->getDeclName();
2664 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2665 return true;
2666 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002667 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002668
John McCallf85e1932011-06-15 23:02:42 +00002669 if (SemaRef.getLangOptions().ObjCAutoRefCount &&
2670 FieldBaseElementType->isObjCRetainableType() &&
2671 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
2672 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
2673 // Instant objects:
2674 // Default-initialize Objective-C pointers to NULL.
2675 CXXMemberInit
2676 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2677 Loc, Loc,
2678 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
2679 Loc);
2680 return false;
2681 }
2682
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002683 // Nothing to initialize.
2684 CXXMemberInit = 0;
2685 return false;
2686}
John McCallf1860e52010-05-20 23:23:51 +00002687
2688namespace {
2689struct BaseAndFieldInfo {
2690 Sema &S;
2691 CXXConstructorDecl *Ctor;
2692 bool AnyErrorsInInits;
2693 ImplicitInitializerKind IIK;
Sean Huntcbb67482011-01-08 20:30:50 +00002694 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002695 SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallf1860e52010-05-20 23:23:51 +00002696
2697 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
2698 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002699 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
2700 if (Generated && Ctor->isCopyConstructor())
John McCallf1860e52010-05-20 23:23:51 +00002701 IIK = IIK_Copy;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002702 else if (Generated && Ctor->isMoveConstructor())
2703 IIK = IIK_Move;
John McCallf1860e52010-05-20 23:23:51 +00002704 else
2705 IIK = IIK_Default;
2706 }
Douglas Gregorf4853882011-11-28 20:03:15 +00002707
2708 bool isImplicitCopyOrMove() const {
2709 switch (IIK) {
2710 case IIK_Copy:
2711 case IIK_Move:
2712 return true;
2713
2714 case IIK_Default:
2715 return false;
2716 }
David Blaikie30263482012-01-20 21:50:17 +00002717
2718 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregorf4853882011-11-28 20:03:15 +00002719 }
John McCallf1860e52010-05-20 23:23:51 +00002720};
2721}
2722
Richard Smitha4950662011-09-19 13:34:43 +00002723/// \brief Determine whether the given indirect field declaration is somewhere
2724/// within an anonymous union.
2725static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
2726 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
2727 CEnd = F->chain_end();
2728 C != CEnd; ++C)
2729 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
2730 if (Record->isUnion())
2731 return true;
2732
2733 return false;
2734}
2735
Douglas Gregorddb21472011-11-02 23:04:16 +00002736/// \brief Determine whether the given type is an incomplete or zero-lenfgth
2737/// array type.
2738static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
2739 if (T->isIncompleteArrayType())
2740 return true;
2741
2742 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
2743 if (!ArrayT->getSize())
2744 return true;
2745
2746 T = ArrayT->getElementType();
2747 }
2748
2749 return false;
2750}
2751
Richard Smith7a614d82011-06-11 17:19:42 +00002752static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002753 FieldDecl *Field,
2754 IndirectFieldDecl *Indirect = 0) {
John McCallf1860e52010-05-20 23:23:51 +00002755
Chandler Carruthe861c602010-06-30 02:59:29 +00002756 // Overwhelmingly common case: we have a direct initializer for this field.
Sean Huntcbb67482011-01-08 20:30:50 +00002757 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002758 Info.AllToInit.push_back(Init);
John McCallf1860e52010-05-20 23:23:51 +00002759 return false;
2760 }
2761
Richard Smith7a614d82011-06-11 17:19:42 +00002762 // C++0x [class.base.init]p8: if the entity is a non-static data member that
2763 // has a brace-or-equal-initializer, the entity is initialized as specified
2764 // in [dcl.init].
Douglas Gregorf4853882011-11-28 20:03:15 +00002765 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002766 CXXCtorInitializer *Init;
2767 if (Indirect)
2768 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2769 SourceLocation(),
2770 SourceLocation(), 0,
2771 SourceLocation());
2772 else
2773 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2774 SourceLocation(),
2775 SourceLocation(), 0,
2776 SourceLocation());
2777 Info.AllToInit.push_back(Init);
Richard Smith7a614d82011-06-11 17:19:42 +00002778 return false;
2779 }
2780
Richard Smithc115f632011-09-18 11:14:50 +00002781 // Don't build an implicit initializer for union members if none was
2782 // explicitly specified.
Richard Smitha4950662011-09-19 13:34:43 +00002783 if (Field->getParent()->isUnion() ||
2784 (Indirect && isWithinAnonymousUnion(Indirect)))
Richard Smithc115f632011-09-18 11:14:50 +00002785 return false;
2786
Douglas Gregorddb21472011-11-02 23:04:16 +00002787 // Don't initialize incomplete or zero-length arrays.
2788 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
2789 return false;
2790
John McCallf1860e52010-05-20 23:23:51 +00002791 // Don't try to build an implicit initializer if there were semantic
2792 // errors in any of the initializers (and therefore we might be
2793 // missing some that the user actually wrote).
Richard Smith7a614d82011-06-11 17:19:42 +00002794 if (Info.AnyErrorsInInits || Field->isInvalidDecl())
John McCallf1860e52010-05-20 23:23:51 +00002795 return false;
2796
Sean Huntcbb67482011-01-08 20:30:50 +00002797 CXXCtorInitializer *Init = 0;
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002798 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
2799 Indirect, Init))
John McCallf1860e52010-05-20 23:23:51 +00002800 return true;
John McCallf1860e52010-05-20 23:23:51 +00002801
Francois Pichet00eb3f92010-12-04 09:14:42 +00002802 if (Init)
2803 Info.AllToInit.push_back(Init);
2804
John McCallf1860e52010-05-20 23:23:51 +00002805 return false;
2806}
Sean Hunt059ce0d2011-05-01 07:04:31 +00002807
2808bool
2809Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
2810 CXXCtorInitializer *Initializer) {
Sean Huntfe57eef2011-05-04 05:57:24 +00002811 assert(Initializer->isDelegatingInitializer());
Sean Hunt01aacc02011-05-03 20:43:02 +00002812 Constructor->setNumCtorInitializers(1);
2813 CXXCtorInitializer **initializer =
2814 new (Context) CXXCtorInitializer*[1];
2815 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
2816 Constructor->setCtorInitializers(initializer);
2817
Sean Huntb76af9c2011-05-03 23:05:34 +00002818 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00002819 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Sean Huntb76af9c2011-05-03 23:05:34 +00002820 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
2821 }
2822
Sean Huntc1598702011-05-05 00:05:47 +00002823 DelegatingCtorDecls.push_back(Constructor);
Sean Huntfe57eef2011-05-04 05:57:24 +00002824
Sean Hunt059ce0d2011-05-01 07:04:31 +00002825 return false;
2826}
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002827
John McCallb77115d2011-06-17 00:18:42 +00002828bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
2829 CXXCtorInitializer **Initializers,
2830 unsigned NumInitializers,
2831 bool AnyErrors) {
Douglas Gregord836c0d2011-09-22 23:04:35 +00002832 if (Constructor->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002833 // Just store the initializers as written, they will be checked during
2834 // instantiation.
2835 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00002836 Constructor->setNumCtorInitializers(NumInitializers);
2837 CXXCtorInitializer **baseOrMemberInitializers =
2838 new (Context) CXXCtorInitializer*[NumInitializers];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002839 memcpy(baseOrMemberInitializers, Initializers,
Sean Huntcbb67482011-01-08 20:30:50 +00002840 NumInitializers * sizeof(CXXCtorInitializer*));
2841 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002842 }
2843
2844 return false;
2845 }
2846
John McCallf1860e52010-05-20 23:23:51 +00002847 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00002848
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002849 // We need to build the initializer AST according to order of construction
2850 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00002851 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00002852 if (!ClassDecl)
2853 return true;
2854
Eli Friedman80c30da2009-11-09 19:20:36 +00002855 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002856
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002857 for (unsigned i = 0; i < NumInitializers; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00002858 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002859
2860 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00002861 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002862 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00002863 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002864 }
2865
Anders Carlsson711f34a2010-04-21 19:52:01 +00002866 // Keep track of the direct virtual bases.
2867 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
2868 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
2869 E = ClassDecl->bases_end(); I != E; ++I) {
2870 if (I->isVirtual())
2871 DirectVBases.insert(I);
2872 }
2873
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002874 // Push virtual bases before others.
2875 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2876 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2877
Sean Huntcbb67482011-01-08 20:30:50 +00002878 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00002879 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
2880 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002881 } else if (!AnyErrors) {
Anders Carlsson711f34a2010-04-21 19:52:01 +00002882 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00002883 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00002884 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002885 VBase, IsInheritedVirtualBase,
2886 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002887 HadError = true;
2888 continue;
2889 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002890
John McCallf1860e52010-05-20 23:23:51 +00002891 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002892 }
2893 }
Mike Stump1eb44332009-09-09 15:08:12 +00002894
John McCallf1860e52010-05-20 23:23:51 +00002895 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002896 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2897 E = ClassDecl->bases_end(); Base != E; ++Base) {
2898 // Virtuals are in the virtual base list and already constructed.
2899 if (Base->isVirtual())
2900 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00002901
Sean Huntcbb67482011-01-08 20:30:50 +00002902 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00002903 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
2904 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002905 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00002906 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00002907 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002908 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00002909 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002910 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002911 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002912 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00002913
John McCallf1860e52010-05-20 23:23:51 +00002914 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002915 }
2916 }
Mike Stump1eb44332009-09-09 15:08:12 +00002917
John McCallf1860e52010-05-20 23:23:51 +00002918 // Fields.
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002919 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
2920 MemEnd = ClassDecl->decls_end();
2921 Mem != MemEnd; ++Mem) {
2922 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
Douglas Gregord61db332011-10-10 17:22:13 +00002923 // C++ [class.bit]p2:
2924 // A declaration for a bit-field that omits the identifier declares an
2925 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
2926 // initialized.
2927 if (F->isUnnamedBitfield())
2928 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00002929
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002930 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002931 // handle anonymous struct/union fields based on their individual
2932 // indirect fields.
2933 if (F->isAnonymousStructOrUnion() && Info.IIK == IIK_Default)
2934 continue;
2935
2936 if (CollectFieldInitializer(*this, Info, F))
2937 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00002938 continue;
2939 }
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002940
2941 // Beyond this point, we only consider default initialization.
2942 if (Info.IIK != IIK_Default)
2943 continue;
2944
2945 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
2946 if (F->getType()->isIncompleteArrayType()) {
2947 assert(ClassDecl->hasFlexibleArrayMember() &&
2948 "Incomplete array type is not valid");
2949 continue;
2950 }
2951
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002952 // Initialize each field of an anonymous struct individually.
2953 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
2954 HadError = true;
2955
2956 continue;
2957 }
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00002958 }
Mike Stump1eb44332009-09-09 15:08:12 +00002959
John McCallf1860e52010-05-20 23:23:51 +00002960 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002961 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00002962 Constructor->setNumCtorInitializers(NumInitializers);
2963 CXXCtorInitializer **baseOrMemberInitializers =
2964 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00002965 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00002966 NumInitializers * sizeof(CXXCtorInitializer*));
2967 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00002968
John McCallef027fe2010-03-16 21:39:52 +00002969 // Constructors implicitly reference the base and member
2970 // destructors.
2971 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
2972 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002973 }
Eli Friedman80c30da2009-11-09 19:20:36 +00002974
2975 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002976}
2977
Eli Friedman6347f422009-07-21 19:28:10 +00002978static void *GetKeyForTopLevelField(FieldDecl *Field) {
2979 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00002980 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00002981 if (RT->getDecl()->isAnonymousStructOrUnion())
2982 return static_cast<void *>(RT->getDecl());
2983 }
2984 return static_cast<void *>(Field);
2985}
2986
Anders Carlssonea356fb2010-04-02 05:42:15 +00002987static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCallf4c73712011-01-19 06:33:43 +00002988 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssoncdc83c72009-09-01 06:22:14 +00002989}
2990
Anders Carlssonea356fb2010-04-02 05:42:15 +00002991static void *GetKeyForMember(ASTContext &Context,
Sean Huntcbb67482011-01-08 20:30:50 +00002992 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002993 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00002994 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00002995
Eli Friedman6347f422009-07-21 19:28:10 +00002996 // For fields injected into the class via declaration of an anonymous union,
2997 // use its anonymous union class declaration as the unique key.
Francois Pichet00eb3f92010-12-04 09:14:42 +00002998 FieldDecl *Field = Member->getAnyMember();
2999
John McCall3c3ccdb2010-04-10 09:28:51 +00003000 // If the field is a member of an anonymous struct or union, our key
3001 // is the anonymous record decl that's a direct child of the class.
Anders Carlssonee11b2d2010-03-30 16:19:37 +00003002 RecordDecl *RD = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003003 if (RD->isAnonymousStructOrUnion()) {
3004 while (true) {
3005 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
3006 if (Parent->isAnonymousStructOrUnion())
3007 RD = Parent;
3008 else
3009 break;
3010 }
3011
Anders Carlssonee11b2d2010-03-30 16:19:37 +00003012 return static_cast<void *>(RD);
John McCall3c3ccdb2010-04-10 09:28:51 +00003013 }
Mike Stump1eb44332009-09-09 15:08:12 +00003014
Anders Carlsson8f1a2402010-03-30 15:39:27 +00003015 return static_cast<void *>(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00003016}
3017
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003018static void
3019DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson071d6102010-04-02 03:38:04 +00003020 const CXXConstructorDecl *Constructor,
Sean Huntcbb67482011-01-08 20:30:50 +00003021 CXXCtorInitializer **Inits,
John McCalld6ca8da2010-04-10 07:37:23 +00003022 unsigned NumInits) {
3023 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00003024 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003025
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003026 // Don't check initializers order unless the warning is enabled at the
3027 // location of at least one initializer.
3028 bool ShouldCheckOrder = false;
3029 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003030 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003031 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3032 Init->getSourceLocation())
David Blaikied6471f72011-09-25 23:23:43 +00003033 != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003034 ShouldCheckOrder = true;
3035 break;
3036 }
3037 }
3038 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003039 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003040
John McCalld6ca8da2010-04-10 07:37:23 +00003041 // Build the list of bases and members in the order that they'll
3042 // actually be initialized. The explicit initializers should be in
3043 // this same order but may be missing things.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003044 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00003045
Anders Carlsson071d6102010-04-02 03:38:04 +00003046 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3047
John McCalld6ca8da2010-04-10 07:37:23 +00003048 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003049 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003050 ClassDecl->vbases_begin(),
3051 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00003052 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003053
John McCalld6ca8da2010-04-10 07:37:23 +00003054 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003055 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003056 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003057 if (Base->isVirtual())
3058 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00003059 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003060 }
Mike Stump1eb44332009-09-09 15:08:12 +00003061
John McCalld6ca8da2010-04-10 07:37:23 +00003062 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003063 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Douglas Gregord61db332011-10-10 17:22:13 +00003064 E = ClassDecl->field_end(); Field != E; ++Field) {
3065 if (Field->isUnnamedBitfield())
3066 continue;
3067
John McCalld6ca8da2010-04-10 07:37:23 +00003068 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Douglas Gregord61db332011-10-10 17:22:13 +00003069 }
3070
John McCalld6ca8da2010-04-10 07:37:23 +00003071 unsigned NumIdealInits = IdealInitKeys.size();
3072 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00003073
Sean Huntcbb67482011-01-08 20:30:50 +00003074 CXXCtorInitializer *PrevInit = 0;
John McCalld6ca8da2010-04-10 07:37:23 +00003075 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003076 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichet00eb3f92010-12-04 09:14:42 +00003077 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00003078
3079 // Scan forward to try to find this initializer in the idealized
3080 // initializers list.
3081 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3082 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003083 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003084
3085 // If we didn't find this initializer, it must be because we
3086 // scanned past it on a previous iteration. That can only
3087 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00003088 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00003089 Sema::SemaDiagnosticBuilder D =
3090 SemaRef.Diag(PrevInit->getSourceLocation(),
3091 diag::warn_initializer_out_of_order);
3092
Francois Pichet00eb3f92010-12-04 09:14:42 +00003093 if (PrevInit->isAnyMemberInitializer())
3094 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003095 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003096 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003097
Francois Pichet00eb3f92010-12-04 09:14:42 +00003098 if (Init->isAnyMemberInitializer())
3099 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003100 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003101 D << 1 << Init->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003102
3103 // Move back to the initializer's location in the ideal list.
3104 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3105 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003106 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003107
3108 assert(IdealIndex != NumIdealInits &&
3109 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003110 }
John McCalld6ca8da2010-04-10 07:37:23 +00003111
3112 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003113 }
Anders Carlssona7b35212009-03-25 02:58:17 +00003114}
3115
John McCall3c3ccdb2010-04-10 09:28:51 +00003116namespace {
3117bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003118 CXXCtorInitializer *Init,
3119 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003120 if (!PrevInit) {
3121 PrevInit = Init;
3122 return false;
3123 }
3124
3125 if (FieldDecl *Field = Init->getMember())
3126 S.Diag(Init->getSourceLocation(),
3127 diag::err_multiple_mem_initialization)
3128 << Field->getDeclName()
3129 << Init->getSourceRange();
3130 else {
John McCallf4c73712011-01-19 06:33:43 +00003131 const Type *BaseClass = Init->getBaseClass();
John McCall3c3ccdb2010-04-10 09:28:51 +00003132 assert(BaseClass && "neither field nor base");
3133 S.Diag(Init->getSourceLocation(),
3134 diag::err_multiple_base_initialization)
3135 << QualType(BaseClass, 0)
3136 << Init->getSourceRange();
3137 }
3138 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3139 << 0 << PrevInit->getSourceRange();
3140
3141 return true;
3142}
3143
Sean Huntcbb67482011-01-08 20:30:50 +00003144typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00003145typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3146
3147bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003148 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00003149 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003150 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003151 RecordDecl *Parent = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003152 NamedDecl *Child = Field;
David Blaikie6fe29652011-11-17 06:01:57 +00003153
3154 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003155 if (Parent->isUnion()) {
3156 UnionEntry &En = Unions[Parent];
3157 if (En.first && En.first != Child) {
3158 S.Diag(Init->getSourceLocation(),
3159 diag::err_multiple_mem_union_initialization)
3160 << Field->getDeclName()
3161 << Init->getSourceRange();
3162 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3163 << 0 << En.second->getSourceRange();
3164 return true;
David Blaikie5bbe8162011-11-12 20:54:14 +00003165 }
3166 if (!En.first) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003167 En.first = Child;
3168 En.second = Init;
3169 }
David Blaikie6fe29652011-11-17 06:01:57 +00003170 if (!Parent->isAnonymousStructOrUnion())
3171 return false;
John McCall3c3ccdb2010-04-10 09:28:51 +00003172 }
3173
3174 Child = Parent;
3175 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie6fe29652011-11-17 06:01:57 +00003176 }
John McCall3c3ccdb2010-04-10 09:28:51 +00003177
3178 return false;
3179}
3180}
3181
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003182/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00003183void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003184 SourceLocation ColonLoc,
Richard Trieu90ab75b2011-09-09 03:18:59 +00003185 CXXCtorInitializer **meminits,
3186 unsigned NumMemInits,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003187 bool AnyErrors) {
3188 if (!ConstructorDecl)
3189 return;
3190
3191 AdjustDeclIfTemplate(ConstructorDecl);
3192
3193 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003194 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003195
3196 if (!Constructor) {
3197 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3198 return;
3199 }
3200
Sean Huntcbb67482011-01-08 20:30:50 +00003201 CXXCtorInitializer **MemInits =
3202 reinterpret_cast<CXXCtorInitializer **>(meminits);
John McCall3c3ccdb2010-04-10 09:28:51 +00003203
3204 // Mapping for the duplicate initializers check.
3205 // For member initializers, this is keyed with a FieldDecl*.
3206 // For base initializers, this is keyed with a Type*.
Sean Huntcbb67482011-01-08 20:30:50 +00003207 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00003208
3209 // Mapping for the inconsistent anonymous-union initializers check.
3210 RedundantUnionMap MemberUnions;
3211
Anders Carlssonea356fb2010-04-02 05:42:15 +00003212 bool HadError = false;
3213 for (unsigned i = 0; i < NumMemInits; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003214 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003215
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00003216 // Set the source order index.
3217 Init->setSourceOrder(i);
3218
Francois Pichet00eb3f92010-12-04 09:14:42 +00003219 if (Init->isAnyMemberInitializer()) {
3220 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003221 if (CheckRedundantInit(*this, Init, Members[Field]) ||
3222 CheckRedundantUnionInit(*this, Init, MemberUnions))
3223 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003224 } else if (Init->isBaseInitializer()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003225 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
3226 if (CheckRedundantInit(*this, Init, Members[Key]))
3227 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003228 } else {
3229 assert(Init->isDelegatingInitializer());
3230 // This must be the only initializer
3231 if (i != 0 || NumMemInits > 1) {
3232 Diag(MemInits[0]->getSourceLocation(),
3233 diag::err_delegating_initializer_alone)
3234 << MemInits[0]->getSourceRange();
3235 HadError = true;
Sean Hunt059ce0d2011-05-01 07:04:31 +00003236 // We will treat this as being the only initializer.
Sean Hunt41717662011-02-26 19:13:13 +00003237 }
Sean Huntfe57eef2011-05-04 05:57:24 +00003238 SetDelegatingInitializer(Constructor, MemInits[i]);
Sean Hunt059ce0d2011-05-01 07:04:31 +00003239 // Return immediately as the initializer is set.
3240 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003241 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003242 }
3243
Anders Carlssonea356fb2010-04-02 05:42:15 +00003244 if (HadError)
3245 return;
3246
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003247 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00003248
Sean Huntcbb67482011-01-08 20:30:50 +00003249 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003250}
3251
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003252void
John McCallef027fe2010-03-16 21:39:52 +00003253Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3254 CXXRecordDecl *ClassDecl) {
Richard Smith416f63e2011-09-18 12:11:43 +00003255 // Ignore dependent contexts. Also ignore unions, since their members never
3256 // have destructors implicitly called.
3257 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003258 return;
John McCall58e6f342010-03-16 05:22:47 +00003259
3260 // FIXME: all the access-control diagnostics are positioned on the
3261 // field/base declaration. That's probably good; that said, the
3262 // user might reasonably want to know why the destructor is being
3263 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003264
Anders Carlsson9f853df2009-11-17 04:44:12 +00003265 // Non-static data members.
3266 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3267 E = ClassDecl->field_end(); I != E; ++I) {
3268 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00003269 if (Field->isInvalidDecl())
3270 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003271
3272 // Don't destroy incomplete or zero-length arrays.
3273 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3274 continue;
3275
Anders Carlsson9f853df2009-11-17 04:44:12 +00003276 QualType FieldType = Context.getBaseElementType(Field->getType());
3277
3278 const RecordType* RT = FieldType->getAs<RecordType>();
3279 if (!RT)
3280 continue;
3281
3282 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003283 if (FieldClassDecl->isInvalidDecl())
3284 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00003285 if (FieldClassDecl->hasTrivialDestructor())
3286 continue;
3287
Douglas Gregordb89f282010-07-01 22:47:18 +00003288 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003289 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003290 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003291 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00003292 << Field->getDeclName()
3293 << FieldType);
3294
Eli Friedman5f2987c2012-02-02 03:46:19 +00003295 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00003296 }
3297
John McCall58e6f342010-03-16 05:22:47 +00003298 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3299
Anders Carlsson9f853df2009-11-17 04:44:12 +00003300 // Bases.
3301 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3302 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00003303 // Bases are always records in a well-formed non-dependent class.
3304 const RecordType *RT = Base->getType()->getAs<RecordType>();
3305
3306 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003307 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00003308 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003309
John McCall58e6f342010-03-16 05:22:47 +00003310 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003311 // If our base class is invalid, we probably can't get its dtor anyway.
3312 if (BaseClassDecl->isInvalidDecl())
3313 continue;
3314 // Ignore trivial destructors.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003315 if (BaseClassDecl->hasTrivialDestructor())
3316 continue;
John McCall58e6f342010-03-16 05:22:47 +00003317
Douglas Gregordb89f282010-07-01 22:47:18 +00003318 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003319 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003320
3321 // FIXME: caret should be on the start of the class name
3322 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003323 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00003324 << Base->getType()
3325 << Base->getSourceRange());
Anders Carlsson9f853df2009-11-17 04:44:12 +00003326
Eli Friedman5f2987c2012-02-02 03:46:19 +00003327 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00003328 }
3329
3330 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003331 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3332 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00003333
3334 // Bases are always records in a well-formed non-dependent class.
3335 const RecordType *RT = VBase->getType()->getAs<RecordType>();
3336
3337 // Ignore direct virtual bases.
3338 if (DirectVirtualBases.count(RT))
3339 continue;
3340
John McCall58e6f342010-03-16 05:22:47 +00003341 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003342 // If our base class is invalid, we probably can't get its dtor anyway.
3343 if (BaseClassDecl->isInvalidDecl())
3344 continue;
3345 // Ignore trivial destructors.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003346 if (BaseClassDecl->hasTrivialDestructor())
3347 continue;
John McCall58e6f342010-03-16 05:22:47 +00003348
Douglas Gregordb89f282010-07-01 22:47:18 +00003349 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003350 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003351 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003352 PDiag(diag::err_access_dtor_vbase)
John McCall58e6f342010-03-16 05:22:47 +00003353 << VBase->getType());
3354
Eli Friedman5f2987c2012-02-02 03:46:19 +00003355 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003356 }
3357}
3358
John McCalld226f652010-08-21 09:40:31 +00003359void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00003360 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003361 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003362
Mike Stump1eb44332009-09-09 15:08:12 +00003363 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003364 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Sean Huntcbb67482011-01-08 20:30:50 +00003365 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003366}
3367
Mike Stump1eb44332009-09-09 15:08:12 +00003368bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00003369 unsigned DiagID, AbstractDiagSelID SelID) {
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003370 if (SelID == -1)
John McCall94c3b562010-08-18 09:41:07 +00003371 return RequireNonAbstractType(Loc, T, PDiag(DiagID));
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003372 else
John McCall94c3b562010-08-18 09:41:07 +00003373 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
Mike Stump1eb44332009-09-09 15:08:12 +00003374}
3375
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003376bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00003377 const PartialDiagnostic &PD) {
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003378 if (!getLangOptions().CPlusPlus)
3379 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003380
Anders Carlsson11f21a02009-03-23 19:10:31 +00003381 if (const ArrayType *AT = Context.getAsArrayType(T))
John McCall94c3b562010-08-18 09:41:07 +00003382 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Mike Stump1eb44332009-09-09 15:08:12 +00003383
Ted Kremenek6217b802009-07-29 21:53:49 +00003384 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003385 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00003386 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003387 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00003388
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003389 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
John McCall94c3b562010-08-18 09:41:07 +00003390 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003391 }
Mike Stump1eb44332009-09-09 15:08:12 +00003392
Ted Kremenek6217b802009-07-29 21:53:49 +00003393 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003394 if (!RT)
3395 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003396
John McCall86ff3082010-02-04 22:26:26 +00003397 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003398
John McCall94c3b562010-08-18 09:41:07 +00003399 // We can't answer whether something is abstract until it has a
3400 // definition. If it's currently being defined, we'll walk back
3401 // over all the declarations when we have a full definition.
3402 const CXXRecordDecl *Def = RD->getDefinition();
3403 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00003404 return false;
3405
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003406 if (!RD->isAbstract())
3407 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003408
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003409 Diag(Loc, PD) << RD->getDeclName();
John McCall94c3b562010-08-18 09:41:07 +00003410 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00003411
John McCall94c3b562010-08-18 09:41:07 +00003412 return true;
3413}
3414
3415void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
3416 // Check if we've already emitted the list of pure virtual functions
3417 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003418 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00003419 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003420
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003421 CXXFinalOverriderMap FinalOverriders;
3422 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00003423
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003424 // Keep a set of seen pure methods so we won't diagnose the same method
3425 // more than once.
3426 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
3427
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003428 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
3429 MEnd = FinalOverriders.end();
3430 M != MEnd;
3431 ++M) {
3432 for (OverridingMethods::iterator SO = M->second.begin(),
3433 SOEnd = M->second.end();
3434 SO != SOEnd; ++SO) {
3435 // C++ [class.abstract]p4:
3436 // A class is abstract if it contains or inherits at least one
3437 // pure virtual function for which the final overrider is pure
3438 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00003439
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003440 //
3441 if (SO->second.size() != 1)
3442 continue;
3443
3444 if (!SO->second.front().Method->isPure())
3445 continue;
3446
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003447 if (!SeenPureMethods.insert(SO->second.front().Method))
3448 continue;
3449
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003450 Diag(SO->second.front().Method->getLocation(),
3451 diag::note_pure_virtual_function)
Chandler Carruth45f11b72011-02-18 23:59:51 +00003452 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003453 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003454 }
3455
3456 if (!PureVirtualClassDiagSet)
3457 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
3458 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003459}
3460
Anders Carlsson8211eff2009-03-24 01:19:16 +00003461namespace {
John McCall94c3b562010-08-18 09:41:07 +00003462struct AbstractUsageInfo {
3463 Sema &S;
3464 CXXRecordDecl *Record;
3465 CanQualType AbstractType;
3466 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00003467
John McCall94c3b562010-08-18 09:41:07 +00003468 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
3469 : S(S), Record(Record),
3470 AbstractType(S.Context.getCanonicalType(
3471 S.Context.getTypeDeclType(Record))),
3472 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00003473
John McCall94c3b562010-08-18 09:41:07 +00003474 void DiagnoseAbstractType() {
3475 if (Invalid) return;
3476 S.DiagnoseAbstractType(Record);
3477 Invalid = true;
3478 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00003479
John McCall94c3b562010-08-18 09:41:07 +00003480 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
3481};
3482
3483struct CheckAbstractUsage {
3484 AbstractUsageInfo &Info;
3485 const NamedDecl *Ctx;
3486
3487 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
3488 : Info(Info), Ctx(Ctx) {}
3489
3490 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3491 switch (TL.getTypeLocClass()) {
3492#define ABSTRACT_TYPELOC(CLASS, PARENT)
3493#define TYPELOC(CLASS, PARENT) \
3494 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
3495#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00003496 }
John McCall94c3b562010-08-18 09:41:07 +00003497 }
Mike Stump1eb44332009-09-09 15:08:12 +00003498
John McCall94c3b562010-08-18 09:41:07 +00003499 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3500 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
3501 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor70191862011-02-22 23:21:06 +00003502 if (!TL.getArg(I))
3503 continue;
3504
John McCall94c3b562010-08-18 09:41:07 +00003505 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
3506 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003507 }
John McCall94c3b562010-08-18 09:41:07 +00003508 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003509
John McCall94c3b562010-08-18 09:41:07 +00003510 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3511 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
3512 }
Mike Stump1eb44332009-09-09 15:08:12 +00003513
John McCall94c3b562010-08-18 09:41:07 +00003514 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3515 // Visit the type parameters from a permissive context.
3516 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3517 TemplateArgumentLoc TAL = TL.getArgLoc(I);
3518 if (TAL.getArgument().getKind() == TemplateArgument::Type)
3519 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
3520 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
3521 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00003522 }
John McCall94c3b562010-08-18 09:41:07 +00003523 }
Mike Stump1eb44332009-09-09 15:08:12 +00003524
John McCall94c3b562010-08-18 09:41:07 +00003525 // Visit pointee types from a permissive context.
3526#define CheckPolymorphic(Type) \
3527 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
3528 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
3529 }
3530 CheckPolymorphic(PointerTypeLoc)
3531 CheckPolymorphic(ReferenceTypeLoc)
3532 CheckPolymorphic(MemberPointerTypeLoc)
3533 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedmanb001de72011-10-06 23:00:33 +00003534 CheckPolymorphic(AtomicTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00003535
John McCall94c3b562010-08-18 09:41:07 +00003536 /// Handle all the types we haven't given a more specific
3537 /// implementation for above.
3538 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3539 // Every other kind of type that we haven't called out already
3540 // that has an inner type is either (1) sugar or (2) contains that
3541 // inner type in some way as a subobject.
3542 if (TypeLoc Next = TL.getNextTypeLoc())
3543 return Visit(Next, Sel);
3544
3545 // If there's no inner type and we're in a permissive context,
3546 // don't diagnose.
3547 if (Sel == Sema::AbstractNone) return;
3548
3549 // Check whether the type matches the abstract type.
3550 QualType T = TL.getType();
3551 if (T->isArrayType()) {
3552 Sel = Sema::AbstractArrayType;
3553 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003554 }
John McCall94c3b562010-08-18 09:41:07 +00003555 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
3556 if (CT != Info.AbstractType) return;
3557
3558 // It matched; do some magic.
3559 if (Sel == Sema::AbstractArrayType) {
3560 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
3561 << T << TL.getSourceRange();
3562 } else {
3563 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
3564 << Sel << T << TL.getSourceRange();
3565 }
3566 Info.DiagnoseAbstractType();
3567 }
3568};
3569
3570void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
3571 Sema::AbstractDiagSelID Sel) {
3572 CheckAbstractUsage(*this, D).Visit(TL, Sel);
3573}
3574
3575}
3576
3577/// Check for invalid uses of an abstract type in a method declaration.
3578static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3579 CXXMethodDecl *MD) {
3580 // No need to do the check on definitions, which require that
3581 // the return/param types be complete.
Sean Hunt10620eb2011-05-06 20:44:56 +00003582 if (MD->doesThisDeclarationHaveABody())
John McCall94c3b562010-08-18 09:41:07 +00003583 return;
3584
3585 // For safety's sake, just ignore it if we don't have type source
3586 // information. This should never happen for non-implicit methods,
3587 // but...
3588 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
3589 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
3590}
3591
3592/// Check for invalid uses of an abstract type within a class definition.
3593static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3594 CXXRecordDecl *RD) {
3595 for (CXXRecordDecl::decl_iterator
3596 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
3597 Decl *D = *I;
3598 if (D->isImplicit()) continue;
3599
3600 // Methods and method templates.
3601 if (isa<CXXMethodDecl>(D)) {
3602 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
3603 } else if (isa<FunctionTemplateDecl>(D)) {
3604 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
3605 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
3606
3607 // Fields and static variables.
3608 } else if (isa<FieldDecl>(D)) {
3609 FieldDecl *FD = cast<FieldDecl>(D);
3610 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
3611 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
3612 } else if (isa<VarDecl>(D)) {
3613 VarDecl *VD = cast<VarDecl>(D);
3614 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
3615 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
3616
3617 // Nested classes and class templates.
3618 } else if (isa<CXXRecordDecl>(D)) {
3619 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
3620 } else if (isa<ClassTemplateDecl>(D)) {
3621 CheckAbstractClassUsage(Info,
3622 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
3623 }
3624 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003625}
3626
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003627/// \brief Perform semantic checks on a class definition that has been
3628/// completing, introducing implicitly-declared members, checking for
3629/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00003630void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00003631 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003632 return;
3633
John McCall94c3b562010-08-18 09:41:07 +00003634 if (Record->isAbstract() && !Record->isInvalidDecl()) {
3635 AbstractUsageInfo Info(*this, Record);
3636 CheckAbstractClassUsage(Info, Record);
3637 }
Douglas Gregor325e5932010-04-15 00:00:53 +00003638
3639 // If this is not an aggregate type and has no user-declared constructor,
3640 // complain about any non-static data members of reference or const scalar
3641 // type, since they will never get initializers.
3642 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregor5e058eb2012-02-09 02:20:38 +00003643 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
3644 !Record->isLambda()) {
Douglas Gregor325e5932010-04-15 00:00:53 +00003645 bool Complained = false;
3646 for (RecordDecl::field_iterator F = Record->field_begin(),
3647 FEnd = Record->field_end();
3648 F != FEnd; ++F) {
Douglas Gregord61db332011-10-10 17:22:13 +00003649 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith7a614d82011-06-11 17:19:42 +00003650 continue;
3651
Douglas Gregor325e5932010-04-15 00:00:53 +00003652 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00003653 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00003654 if (!Complained) {
3655 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
3656 << Record->getTagKind() << Record;
3657 Complained = true;
3658 }
3659
3660 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
3661 << F->getType()->isReferenceType()
3662 << F->getDeclName();
3663 }
3664 }
3665 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003666
Anders Carlssona5c6c2a2011-01-25 18:08:22 +00003667 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003668 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00003669
3670 if (Record->getIdentifier()) {
3671 // C++ [class.mem]p13:
3672 // If T is the name of a class, then each of the following shall have a
3673 // name different from T:
3674 // - every member of every anonymous union that is a member of class T.
3675 //
3676 // C++ [class.mem]p14:
3677 // In addition, if class T has a user-declared constructor (12.1), every
3678 // non-static data member of class T shall have a name different from T.
3679 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
Francois Pichet87c2e122010-11-21 06:08:52 +00003680 R.first != R.second; ++R.first) {
3681 NamedDecl *D = *R.first;
3682 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
3683 isa<IndirectFieldDecl>(D)) {
3684 Diag(D->getLocation(), diag::err_member_name_of_class)
3685 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00003686 break;
3687 }
Francois Pichet87c2e122010-11-21 06:08:52 +00003688 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00003689 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003690
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003691 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregorf4b793c2011-02-19 19:14:36 +00003692 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003693 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003694 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003695 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
3696 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
3697 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003698
3699 // See if a method overloads virtual methods in a base
3700 /// class without overriding any.
3701 if (!Record->isDependentType()) {
3702 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3703 MEnd = Record->method_end();
3704 M != MEnd; ++M) {
Argyrios Kyrtzidis0266aa32011-03-03 22:58:57 +00003705 if (!(*M)->isStatic())
3706 DiagnoseHiddenVirtualMethods(Record, *M);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003707 }
3708 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00003709
Richard Smith9f569cc2011-10-01 02:31:28 +00003710 // C++0x [dcl.constexpr]p8: A constexpr specifier for a non-static member
3711 // function that is not a constructor declares that member function to be
3712 // const. [...] The class of which that function is a member shall be
3713 // a literal type.
3714 //
3715 // It's fine to diagnose constructors here too: such constructors cannot
3716 // produce a constant expression, so are ill-formed (no diagnostic required).
3717 //
3718 // If the class has virtual bases, any constexpr members will already have
3719 // been diagnosed by the checks performed on the member declaration, so
3720 // suppress this (less useful) diagnostic.
3721 if (LangOpts.CPlusPlus0x && !Record->isDependentType() &&
3722 !Record->isLiteral() && !Record->getNumVBases()) {
3723 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3724 MEnd = Record->method_end();
3725 M != MEnd; ++M) {
Eli Friedman9ec0ef32012-01-13 02:31:53 +00003726 if (M->isConstexpr() && M->isInstance()) {
Richard Smith9f569cc2011-10-01 02:31:28 +00003727 switch (Record->getTemplateSpecializationKind()) {
3728 case TSK_ImplicitInstantiation:
3729 case TSK_ExplicitInstantiationDeclaration:
3730 case TSK_ExplicitInstantiationDefinition:
3731 // If a template instantiates to a non-literal type, but its members
3732 // instantiate to constexpr functions, the template is technically
3733 // ill-formed, but we allow it for sanity. Such members are treated as
3734 // non-constexpr.
3735 (*M)->setConstexpr(false);
3736 continue;
3737
3738 case TSK_Undeclared:
3739 case TSK_ExplicitSpecialization:
3740 RequireLiteralType((*M)->getLocation(), Context.getRecordType(Record),
3741 PDiag(diag::err_constexpr_method_non_literal));
3742 break;
3743 }
3744
3745 // Only produce one error per class.
3746 break;
3747 }
3748 }
3749 }
3750
Sebastian Redlf677ea32011-02-05 19:23:19 +00003751 // Declare inherited constructors. We do this eagerly here because:
3752 // - The standard requires an eager diagnostic for conflicting inherited
3753 // constructors from different classes.
3754 // - The lazy declaration of the other implicit constructors is so as to not
3755 // waste space and performance on classes that are not meant to be
3756 // instantiated (e.g. meta-functions). This doesn't apply to classes that
3757 // have inherited constructors.
Sebastian Redlcaa35e42011-03-12 13:44:32 +00003758 DeclareInheritedConstructors(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00003759
Sean Hunteb88ae52011-05-23 21:07:59 +00003760 if (!Record->isDependentType())
3761 CheckExplicitlyDefaultedMethods(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00003762}
3763
3764void Sema::CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00003765 for (CXXRecordDecl::method_iterator MI = Record->method_begin(),
3766 ME = Record->method_end();
3767 MI != ME; ++MI) {
3768 if (!MI->isInvalidDecl() && MI->isExplicitlyDefaulted()) {
3769 switch (getSpecialMember(*MI)) {
3770 case CXXDefaultConstructor:
3771 CheckExplicitlyDefaultedDefaultConstructor(
3772 cast<CXXConstructorDecl>(*MI));
3773 break;
Sean Hunt001cad92011-05-10 00:49:42 +00003774
Sean Huntcb45a0f2011-05-12 22:46:25 +00003775 case CXXDestructor:
3776 CheckExplicitlyDefaultedDestructor(cast<CXXDestructorDecl>(*MI));
3777 break;
3778
3779 case CXXCopyConstructor:
Sean Hunt49634cf2011-05-13 06:10:58 +00003780 CheckExplicitlyDefaultedCopyConstructor(cast<CXXConstructorDecl>(*MI));
3781 break;
3782
Sean Huntcb45a0f2011-05-12 22:46:25 +00003783 case CXXCopyAssignment:
Sean Hunt2b188082011-05-14 05:23:28 +00003784 CheckExplicitlyDefaultedCopyAssignment(*MI);
Sean Huntcb45a0f2011-05-12 22:46:25 +00003785 break;
3786
Sean Hunt82713172011-05-25 23:16:36 +00003787 case CXXMoveConstructor:
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003788 CheckExplicitlyDefaultedMoveConstructor(cast<CXXConstructorDecl>(*MI));
Sean Hunt82713172011-05-25 23:16:36 +00003789 break;
3790
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003791 case CXXMoveAssignment:
3792 CheckExplicitlyDefaultedMoveAssignment(*MI);
3793 break;
3794
3795 case CXXInvalid:
Sean Huntcb45a0f2011-05-12 22:46:25 +00003796 llvm_unreachable("non-special member explicitly defaulted!");
3797 }
Sean Hunt001cad92011-05-10 00:49:42 +00003798 }
3799 }
3800
Sean Hunt001cad92011-05-10 00:49:42 +00003801}
3802
3803void Sema::CheckExplicitlyDefaultedDefaultConstructor(CXXConstructorDecl *CD) {
3804 assert(CD->isExplicitlyDefaulted() && CD->isDefaultConstructor());
3805
3806 // Whether this was the first-declared instance of the constructor.
3807 // This affects whether we implicitly add an exception spec (and, eventually,
3808 // constexpr). It is also ill-formed to explicitly default a constructor such
3809 // that it would be deleted. (C++0x [decl.fct.def.default])
3810 bool First = CD == CD->getCanonicalDecl();
3811
Sean Hunt49634cf2011-05-13 06:10:58 +00003812 bool HadError = false;
Sean Hunt001cad92011-05-10 00:49:42 +00003813 if (CD->getNumParams() != 0) {
3814 Diag(CD->getLocation(), diag::err_defaulted_default_ctor_params)
3815 << CD->getSourceRange();
Sean Hunt49634cf2011-05-13 06:10:58 +00003816 HadError = true;
Sean Hunt001cad92011-05-10 00:49:42 +00003817 }
3818
3819 ImplicitExceptionSpecification Spec
3820 = ComputeDefaultedDefaultCtorExceptionSpec(CD->getParent());
3821 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Richard Smith7a614d82011-06-11 17:19:42 +00003822 if (EPI.ExceptionSpecType == EST_Delayed) {
3823 // Exception specification depends on some deferred part of the class. We'll
3824 // try again when the class's definition has been fully processed.
3825 return;
3826 }
Sean Hunt001cad92011-05-10 00:49:42 +00003827 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3828 *ExceptionType = Context.getFunctionType(
3829 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3830
Richard Smith61802452011-12-22 02:22:31 +00003831 // C++11 [dcl.fct.def.default]p2:
3832 // An explicitly-defaulted function may be declared constexpr only if it
3833 // would have been implicitly declared as constexpr,
3834 if (CD->isConstexpr()) {
3835 if (!CD->getParent()->defaultedDefaultConstructorIsConstexpr()) {
3836 Diag(CD->getLocStart(), diag::err_incorrect_defaulted_constexpr)
3837 << CXXDefaultConstructor;
3838 HadError = true;
3839 }
3840 }
3841 // and may have an explicit exception-specification only if it is compatible
3842 // with the exception-specification on the implicit declaration.
Sean Hunt001cad92011-05-10 00:49:42 +00003843 if (CtorType->hasExceptionSpec()) {
3844 if (CheckEquivalentExceptionSpec(
Sean Huntcb45a0f2011-05-12 22:46:25 +00003845 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00003846 << CXXDefaultConstructor,
Sean Hunt001cad92011-05-10 00:49:42 +00003847 PDiag(),
3848 ExceptionType, SourceLocation(),
3849 CtorType, CD->getLocation())) {
Sean Hunt49634cf2011-05-13 06:10:58 +00003850 HadError = true;
Sean Hunt001cad92011-05-10 00:49:42 +00003851 }
Richard Smith61802452011-12-22 02:22:31 +00003852 }
3853
3854 // If a function is explicitly defaulted on its first declaration,
3855 if (First) {
3856 // -- it is implicitly considered to be constexpr if the implicit
3857 // definition would be,
3858 CD->setConstexpr(CD->getParent()->defaultedDefaultConstructorIsConstexpr());
3859
3860 // -- it is implicitly considered to have the same
3861 // exception-specification as if it had been implicitly declared
3862 //
3863 // FIXME: a compatible, but different, explicit exception specification
3864 // will be silently overridden. We should issue a warning if this happens.
Sean Hunt2b188082011-05-14 05:23:28 +00003865 EPI.ExtInfo = CtorType->getExtInfo();
Sean Hunt001cad92011-05-10 00:49:42 +00003866 }
Sean Huntca46d132011-05-12 03:51:48 +00003867
Sean Hunt49634cf2011-05-13 06:10:58 +00003868 if (HadError) {
3869 CD->setInvalidDecl();
3870 return;
3871 }
3872
Sean Hunte16da072011-10-10 06:18:57 +00003873 if (ShouldDeleteSpecialMember(CD, CXXDefaultConstructor)) {
Sean Hunt49634cf2011-05-13 06:10:58 +00003874 if (First) {
Sean Huntca46d132011-05-12 03:51:48 +00003875 CD->setDeletedAsWritten();
Sean Hunt49634cf2011-05-13 06:10:58 +00003876 } else {
Sean Huntca46d132011-05-12 03:51:48 +00003877 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00003878 << CXXDefaultConstructor;
Sean Hunt49634cf2011-05-13 06:10:58 +00003879 CD->setInvalidDecl();
3880 }
3881 }
3882}
3883
3884void Sema::CheckExplicitlyDefaultedCopyConstructor(CXXConstructorDecl *CD) {
3885 assert(CD->isExplicitlyDefaulted() && CD->isCopyConstructor());
3886
3887 // Whether this was the first-declared instance of the constructor.
3888 bool First = CD == CD->getCanonicalDecl();
3889
3890 bool HadError = false;
3891 if (CD->getNumParams() != 1) {
3892 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_params)
3893 << CD->getSourceRange();
3894 HadError = true;
3895 }
3896
3897 ImplicitExceptionSpecification Spec(Context);
3898 bool Const;
3899 llvm::tie(Spec, Const) =
3900 ComputeDefaultedCopyCtorExceptionSpecAndConst(CD->getParent());
3901
3902 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3903 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3904 *ExceptionType = Context.getFunctionType(
3905 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3906
3907 // Check for parameter type matching.
3908 // This is a copy ctor so we know it's a cv-qualified reference to T.
3909 QualType ArgType = CtorType->getArgType(0);
3910 if (ArgType->getPointeeType().isVolatileQualified()) {
3911 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_volatile_param);
3912 HadError = true;
3913 }
3914 if (ArgType->getPointeeType().isConstQualified() && !Const) {
3915 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_const_param);
3916 HadError = true;
3917 }
3918
Richard Smith61802452011-12-22 02:22:31 +00003919 // C++11 [dcl.fct.def.default]p2:
3920 // An explicitly-defaulted function may be declared constexpr only if it
3921 // would have been implicitly declared as constexpr,
3922 if (CD->isConstexpr()) {
3923 if (!CD->getParent()->defaultedCopyConstructorIsConstexpr()) {
3924 Diag(CD->getLocStart(), diag::err_incorrect_defaulted_constexpr)
3925 << CXXCopyConstructor;
3926 HadError = true;
3927 }
3928 }
3929 // and may have an explicit exception-specification only if it is compatible
3930 // with the exception-specification on the implicit declaration.
Sean Hunt49634cf2011-05-13 06:10:58 +00003931 if (CtorType->hasExceptionSpec()) {
3932 if (CheckEquivalentExceptionSpec(
3933 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00003934 << CXXCopyConstructor,
Sean Hunt49634cf2011-05-13 06:10:58 +00003935 PDiag(),
3936 ExceptionType, SourceLocation(),
3937 CtorType, CD->getLocation())) {
3938 HadError = true;
3939 }
Richard Smith61802452011-12-22 02:22:31 +00003940 }
3941
3942 // If a function is explicitly defaulted on its first declaration,
3943 if (First) {
3944 // -- it is implicitly considered to be constexpr if the implicit
3945 // definition would be,
3946 CD->setConstexpr(CD->getParent()->defaultedCopyConstructorIsConstexpr());
3947
3948 // -- it is implicitly considered to have the same
3949 // exception-specification as if it had been implicitly declared, and
3950 //
3951 // FIXME: a compatible, but different, explicit exception specification
3952 // will be silently overridden. We should issue a warning if this happens.
Sean Hunt2b188082011-05-14 05:23:28 +00003953 EPI.ExtInfo = CtorType->getExtInfo();
Richard Smith61802452011-12-22 02:22:31 +00003954
3955 // -- [...] it shall have the same parameter type as if it had been
3956 // implicitly declared.
Sean Hunt49634cf2011-05-13 06:10:58 +00003957 CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
3958 }
3959
3960 if (HadError) {
3961 CD->setInvalidDecl();
3962 return;
3963 }
3964
Sean Huntc32d6842011-10-11 04:55:36 +00003965 if (ShouldDeleteSpecialMember(CD, CXXCopyConstructor)) {
Sean Hunt49634cf2011-05-13 06:10:58 +00003966 if (First) {
3967 CD->setDeletedAsWritten();
3968 } else {
3969 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00003970 << CXXCopyConstructor;
Sean Hunt49634cf2011-05-13 06:10:58 +00003971 CD->setInvalidDecl();
3972 }
Sean Huntca46d132011-05-12 03:51:48 +00003973 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00003974}
Sean Hunt001cad92011-05-10 00:49:42 +00003975
Sean Hunt2b188082011-05-14 05:23:28 +00003976void Sema::CheckExplicitlyDefaultedCopyAssignment(CXXMethodDecl *MD) {
3977 assert(MD->isExplicitlyDefaulted());
3978
3979 // Whether this was the first-declared instance of the operator
3980 bool First = MD == MD->getCanonicalDecl();
3981
3982 bool HadError = false;
3983 if (MD->getNumParams() != 1) {
3984 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_params)
3985 << MD->getSourceRange();
3986 HadError = true;
3987 }
3988
3989 QualType ReturnType =
3990 MD->getType()->getAs<FunctionType>()->getResultType();
3991 if (!ReturnType->isLValueReferenceType() ||
3992 !Context.hasSameType(
3993 Context.getCanonicalType(ReturnType->getPointeeType()),
3994 Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
3995 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_return_type);
3996 HadError = true;
3997 }
3998
3999 ImplicitExceptionSpecification Spec(Context);
4000 bool Const;
4001 llvm::tie(Spec, Const) =
4002 ComputeDefaultedCopyCtorExceptionSpecAndConst(MD->getParent());
4003
4004 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4005 const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
4006 *ExceptionType = Context.getFunctionType(
4007 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4008
Sean Hunt2b188082011-05-14 05:23:28 +00004009 QualType ArgType = OperType->getArgType(0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004010 if (!ArgType->isLValueReferenceType()) {
Sean Huntbe631222011-05-17 20:44:43 +00004011 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Sean Hunt2b188082011-05-14 05:23:28 +00004012 HadError = true;
Sean Huntbe631222011-05-17 20:44:43 +00004013 } else {
4014 if (ArgType->getPointeeType().isVolatileQualified()) {
4015 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_volatile_param);
4016 HadError = true;
4017 }
4018 if (ArgType->getPointeeType().isConstQualified() && !Const) {
4019 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_const_param);
4020 HadError = true;
4021 }
Sean Hunt2b188082011-05-14 05:23:28 +00004022 }
Sean Huntbe631222011-05-17 20:44:43 +00004023
Sean Hunt2b188082011-05-14 05:23:28 +00004024 if (OperType->getTypeQuals()) {
4025 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_quals);
4026 HadError = true;
4027 }
4028
4029 if (OperType->hasExceptionSpec()) {
4030 if (CheckEquivalentExceptionSpec(
4031 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00004032 << CXXCopyAssignment,
Sean Hunt2b188082011-05-14 05:23:28 +00004033 PDiag(),
4034 ExceptionType, SourceLocation(),
4035 OperType, MD->getLocation())) {
4036 HadError = true;
4037 }
Richard Smith61802452011-12-22 02:22:31 +00004038 }
4039 if (First) {
Sean Hunt2b188082011-05-14 05:23:28 +00004040 // We set the declaration to have the computed exception spec here.
4041 // We duplicate the one parameter type.
4042 EPI.RefQualifier = OperType->getRefQualifier();
4043 EPI.ExtInfo = OperType->getExtInfo();
4044 MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
4045 }
4046
4047 if (HadError) {
4048 MD->setInvalidDecl();
4049 return;
4050 }
4051
4052 if (ShouldDeleteCopyAssignmentOperator(MD)) {
4053 if (First) {
4054 MD->setDeletedAsWritten();
4055 } else {
4056 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00004057 << CXXCopyAssignment;
Sean Hunt2b188082011-05-14 05:23:28 +00004058 MD->setInvalidDecl();
4059 }
4060 }
4061}
4062
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004063void Sema::CheckExplicitlyDefaultedMoveConstructor(CXXConstructorDecl *CD) {
4064 assert(CD->isExplicitlyDefaulted() && CD->isMoveConstructor());
4065
4066 // Whether this was the first-declared instance of the constructor.
4067 bool First = CD == CD->getCanonicalDecl();
4068
4069 bool HadError = false;
4070 if (CD->getNumParams() != 1) {
4071 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_params)
4072 << CD->getSourceRange();
4073 HadError = true;
4074 }
4075
4076 ImplicitExceptionSpecification Spec(
4077 ComputeDefaultedMoveCtorExceptionSpec(CD->getParent()));
4078
4079 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4080 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
4081 *ExceptionType = Context.getFunctionType(
4082 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4083
4084 // Check for parameter type matching.
4085 // This is a move ctor so we know it's a cv-qualified rvalue reference to T.
4086 QualType ArgType = CtorType->getArgType(0);
4087 if (ArgType->getPointeeType().isVolatileQualified()) {
4088 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_volatile_param);
4089 HadError = true;
4090 }
4091 if (ArgType->getPointeeType().isConstQualified()) {
4092 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_const_param);
4093 HadError = true;
4094 }
4095
Richard Smith61802452011-12-22 02:22:31 +00004096 // C++11 [dcl.fct.def.default]p2:
4097 // An explicitly-defaulted function may be declared constexpr only if it
4098 // would have been implicitly declared as constexpr,
4099 if (CD->isConstexpr()) {
4100 if (!CD->getParent()->defaultedMoveConstructorIsConstexpr()) {
4101 Diag(CD->getLocStart(), diag::err_incorrect_defaulted_constexpr)
4102 << CXXMoveConstructor;
4103 HadError = true;
4104 }
4105 }
4106 // and may have an explicit exception-specification only if it is compatible
4107 // with the exception-specification on the implicit declaration.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004108 if (CtorType->hasExceptionSpec()) {
4109 if (CheckEquivalentExceptionSpec(
4110 PDiag(diag::err_incorrect_defaulted_exception_spec)
4111 << CXXMoveConstructor,
4112 PDiag(),
4113 ExceptionType, SourceLocation(),
4114 CtorType, CD->getLocation())) {
4115 HadError = true;
4116 }
Richard Smith61802452011-12-22 02:22:31 +00004117 }
4118
4119 // If a function is explicitly defaulted on its first declaration,
4120 if (First) {
4121 // -- it is implicitly considered to be constexpr if the implicit
4122 // definition would be,
4123 CD->setConstexpr(CD->getParent()->defaultedMoveConstructorIsConstexpr());
4124
4125 // -- it is implicitly considered to have the same
4126 // exception-specification as if it had been implicitly declared, and
4127 //
4128 // FIXME: a compatible, but different, explicit exception specification
4129 // will be silently overridden. We should issue a warning if this happens.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004130 EPI.ExtInfo = CtorType->getExtInfo();
Richard Smith61802452011-12-22 02:22:31 +00004131
4132 // -- [...] it shall have the same parameter type as if it had been
4133 // implicitly declared.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004134 CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
4135 }
4136
4137 if (HadError) {
4138 CD->setInvalidDecl();
4139 return;
4140 }
4141
Sean Hunt769bb2d2011-10-11 06:43:29 +00004142 if (ShouldDeleteSpecialMember(CD, CXXMoveConstructor)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004143 if (First) {
4144 CD->setDeletedAsWritten();
4145 } else {
4146 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
4147 << CXXMoveConstructor;
4148 CD->setInvalidDecl();
4149 }
4150 }
4151}
4152
4153void Sema::CheckExplicitlyDefaultedMoveAssignment(CXXMethodDecl *MD) {
4154 assert(MD->isExplicitlyDefaulted());
4155
4156 // Whether this was the first-declared instance of the operator
4157 bool First = MD == MD->getCanonicalDecl();
4158
4159 bool HadError = false;
4160 if (MD->getNumParams() != 1) {
4161 Diag(MD->getLocation(), diag::err_defaulted_move_assign_params)
4162 << MD->getSourceRange();
4163 HadError = true;
4164 }
4165
4166 QualType ReturnType =
4167 MD->getType()->getAs<FunctionType>()->getResultType();
4168 if (!ReturnType->isLValueReferenceType() ||
4169 !Context.hasSameType(
4170 Context.getCanonicalType(ReturnType->getPointeeType()),
4171 Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
4172 Diag(MD->getLocation(), diag::err_defaulted_move_assign_return_type);
4173 HadError = true;
4174 }
4175
4176 ImplicitExceptionSpecification Spec(
4177 ComputeDefaultedMoveCtorExceptionSpec(MD->getParent()));
4178
4179 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4180 const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
4181 *ExceptionType = Context.getFunctionType(
4182 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4183
4184 QualType ArgType = OperType->getArgType(0);
4185 if (!ArgType->isRValueReferenceType()) {
4186 Diag(MD->getLocation(), diag::err_defaulted_move_assign_not_ref);
4187 HadError = true;
4188 } else {
4189 if (ArgType->getPointeeType().isVolatileQualified()) {
4190 Diag(MD->getLocation(), diag::err_defaulted_move_assign_volatile_param);
4191 HadError = true;
4192 }
4193 if (ArgType->getPointeeType().isConstQualified()) {
4194 Diag(MD->getLocation(), diag::err_defaulted_move_assign_const_param);
4195 HadError = true;
4196 }
4197 }
4198
4199 if (OperType->getTypeQuals()) {
4200 Diag(MD->getLocation(), diag::err_defaulted_move_assign_quals);
4201 HadError = true;
4202 }
4203
4204 if (OperType->hasExceptionSpec()) {
4205 if (CheckEquivalentExceptionSpec(
4206 PDiag(diag::err_incorrect_defaulted_exception_spec)
4207 << CXXMoveAssignment,
4208 PDiag(),
4209 ExceptionType, SourceLocation(),
4210 OperType, MD->getLocation())) {
4211 HadError = true;
4212 }
Richard Smith61802452011-12-22 02:22:31 +00004213 }
4214 if (First) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004215 // We set the declaration to have the computed exception spec here.
4216 // We duplicate the one parameter type.
4217 EPI.RefQualifier = OperType->getRefQualifier();
4218 EPI.ExtInfo = OperType->getExtInfo();
4219 MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
4220 }
4221
4222 if (HadError) {
4223 MD->setInvalidDecl();
4224 return;
4225 }
4226
4227 if (ShouldDeleteMoveAssignmentOperator(MD)) {
4228 if (First) {
4229 MD->setDeletedAsWritten();
4230 } else {
4231 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
4232 << CXXMoveAssignment;
4233 MD->setInvalidDecl();
4234 }
4235 }
4236}
4237
Sean Huntcb45a0f2011-05-12 22:46:25 +00004238void Sema::CheckExplicitlyDefaultedDestructor(CXXDestructorDecl *DD) {
4239 assert(DD->isExplicitlyDefaulted());
4240
4241 // Whether this was the first-declared instance of the destructor.
4242 bool First = DD == DD->getCanonicalDecl();
4243
4244 ImplicitExceptionSpecification Spec
4245 = ComputeDefaultedDtorExceptionSpec(DD->getParent());
4246 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4247 const FunctionProtoType *DtorType = DD->getType()->getAs<FunctionProtoType>(),
4248 *ExceptionType = Context.getFunctionType(
4249 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4250
4251 if (DtorType->hasExceptionSpec()) {
4252 if (CheckEquivalentExceptionSpec(
4253 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00004254 << CXXDestructor,
Sean Huntcb45a0f2011-05-12 22:46:25 +00004255 PDiag(),
4256 ExceptionType, SourceLocation(),
4257 DtorType, DD->getLocation())) {
4258 DD->setInvalidDecl();
4259 return;
4260 }
Richard Smith61802452011-12-22 02:22:31 +00004261 }
4262 if (First) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00004263 // We set the declaration to have the computed exception spec here.
4264 // There are no parameters.
Sean Hunt2b188082011-05-14 05:23:28 +00004265 EPI.ExtInfo = DtorType->getExtInfo();
Sean Huntcb45a0f2011-05-12 22:46:25 +00004266 DD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
4267 }
4268
4269 if (ShouldDeleteDestructor(DD)) {
Sean Hunt49634cf2011-05-13 06:10:58 +00004270 if (First) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00004271 DD->setDeletedAsWritten();
Sean Hunt49634cf2011-05-13 06:10:58 +00004272 } else {
Sean Huntcb45a0f2011-05-12 22:46:25 +00004273 Diag(DD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00004274 << CXXDestructor;
Sean Hunt49634cf2011-05-13 06:10:58 +00004275 DD->setInvalidDecl();
4276 }
Sean Huntcb45a0f2011-05-12 22:46:25 +00004277 }
Sean Huntcb45a0f2011-05-12 22:46:25 +00004278}
4279
Sean Hunte16da072011-10-10 06:18:57 +00004280/// This function implements the following C++0x paragraphs:
4281/// - [class.ctor]/5
Sean Huntc32d6842011-10-11 04:55:36 +00004282/// - [class.copy]/11
Sean Hunte16da072011-10-10 06:18:57 +00004283bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM) {
4284 assert(!MD->isInvalidDecl());
4285 CXXRecordDecl *RD = MD->getParent();
Sean Huntcdee3fe2011-05-11 22:34:38 +00004286 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaracdb80762011-07-11 08:52:40 +00004287 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004288 return false;
4289
Sean Hunte16da072011-10-10 06:18:57 +00004290 bool IsUnion = RD->isUnion();
4291 bool IsConstructor = false;
4292 bool IsAssignment = false;
4293 bool IsMove = false;
4294
4295 bool ConstArg = false;
4296
4297 switch (CSM) {
4298 case CXXDefaultConstructor:
4299 IsConstructor = true;
4300 break;
Sean Huntc32d6842011-10-11 04:55:36 +00004301 case CXXCopyConstructor:
4302 IsConstructor = true;
4303 ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4304 break;
Sean Hunt769bb2d2011-10-11 06:43:29 +00004305 case CXXMoveConstructor:
4306 IsConstructor = true;
4307 IsMove = true;
4308 break;
Sean Hunte16da072011-10-10 06:18:57 +00004309 default:
4310 llvm_unreachable("function only currently implemented for default ctors");
4311 }
4312
4313 SourceLocation Loc = MD->getLocation();
Sean Hunt71a682f2011-05-18 03:41:58 +00004314
Sean Huntc32d6842011-10-11 04:55:36 +00004315 // Do access control from the special member function
Sean Hunte16da072011-10-10 06:18:57 +00004316 ContextRAII MethodContext(*this, MD);
Sean Huntcdee3fe2011-05-11 22:34:38 +00004317
Sean Huntcdee3fe2011-05-11 22:34:38 +00004318 bool AllConst = true;
4319
Sean Huntcdee3fe2011-05-11 22:34:38 +00004320 // We do this because we should never actually use an anonymous
4321 // union's constructor.
Sean Hunte16da072011-10-10 06:18:57 +00004322 if (IsUnion && RD->isAnonymousStructOrUnion())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004323 return false;
4324
4325 // FIXME: We should put some diagnostic logic right into this function.
4326
Sean Huntcdee3fe2011-05-11 22:34:38 +00004327 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4328 BE = RD->bases_end();
4329 BI != BE; ++BI) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00004330 // We'll handle this one later
4331 if (BI->isVirtual())
4332 continue;
4333
Sean Huntcdee3fe2011-05-11 22:34:38 +00004334 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4335 assert(BaseDecl && "base isn't a CXXRecordDecl");
4336
Sean Hunte16da072011-10-10 06:18:57 +00004337 // Unless we have an assignment operator, the base's destructor must
4338 // be accessible and not deleted.
4339 if (!IsAssignment) {
4340 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4341 if (BaseDtor->isDeleted())
4342 return true;
4343 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
4344 AR_accessible)
4345 return true;
4346 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004347
Sean Hunte16da072011-10-10 06:18:57 +00004348 // Finding the corresponding member in the base should lead to a
Sean Huntc32d6842011-10-11 04:55:36 +00004349 // unique, accessible, non-deleted function. If we are doing
4350 // a destructor, we have already checked this case.
Sean Hunte16da072011-10-10 06:18:57 +00004351 if (CSM != CXXDestructor) {
4352 SpecialMemberOverloadResult *SMOR =
Sean Hunt769bb2d2011-10-11 06:43:29 +00004353 LookupSpecialMember(BaseDecl, CSM, ConstArg, false, false, false,
Sean Hunte16da072011-10-10 06:18:57 +00004354 false);
4355 if (!SMOR->hasSuccess())
4356 return true;
4357 CXXMethodDecl *BaseMember = SMOR->getMethod();
4358 if (IsConstructor) {
4359 CXXConstructorDecl *BaseCtor = cast<CXXConstructorDecl>(BaseMember);
4360 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(),
4361 PDiag()) != AR_accessible)
4362 return true;
Sean Hunt769bb2d2011-10-11 06:43:29 +00004363
4364 // For a move operation, the corresponding operation must actually
4365 // be a move operation (and not a copy selected by overload
4366 // resolution) unless we are working on a trivially copyable class.
4367 if (IsMove && !BaseCtor->isMoveConstructor() &&
4368 !BaseDecl->isTriviallyCopyable())
4369 return true;
Sean Hunte16da072011-10-10 06:18:57 +00004370 }
4371 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004372 }
4373
4374 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4375 BE = RD->vbases_end();
4376 BI != BE; ++BI) {
4377 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4378 assert(BaseDecl && "base isn't a CXXRecordDecl");
4379
Sean Hunte16da072011-10-10 06:18:57 +00004380 // Unless we have an assignment operator, the base's destructor must
4381 // be accessible and not deleted.
4382 if (!IsAssignment) {
4383 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4384 if (BaseDtor->isDeleted())
4385 return true;
4386 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
4387 AR_accessible)
4388 return true;
4389 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004390
Sean Hunte16da072011-10-10 06:18:57 +00004391 // Finding the corresponding member in the base should lead to a
4392 // unique, accessible, non-deleted function.
4393 if (CSM != CXXDestructor) {
4394 SpecialMemberOverloadResult *SMOR =
Sean Hunt769bb2d2011-10-11 06:43:29 +00004395 LookupSpecialMember(BaseDecl, CSM, ConstArg, false, false, false,
Sean Hunte16da072011-10-10 06:18:57 +00004396 false);
4397 if (!SMOR->hasSuccess())
4398 return true;
4399 CXXMethodDecl *BaseMember = SMOR->getMethod();
4400 if (IsConstructor) {
4401 CXXConstructorDecl *BaseCtor = cast<CXXConstructorDecl>(BaseMember);
4402 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(),
4403 PDiag()) != AR_accessible)
4404 return true;
Sean Hunt769bb2d2011-10-11 06:43:29 +00004405
4406 // For a move operation, the corresponding operation must actually
4407 // be a move operation (and not a copy selected by overload
4408 // resolution) unless we are working on a trivially copyable class.
4409 if (IsMove && !BaseCtor->isMoveConstructor() &&
4410 !BaseDecl->isTriviallyCopyable())
4411 return true;
Sean Hunte16da072011-10-10 06:18:57 +00004412 }
4413 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004414 }
4415
4416 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4417 FE = RD->field_end();
4418 FI != FE; ++FI) {
Douglas Gregord61db332011-10-10 17:22:13 +00004419 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
Richard Smith7a614d82011-06-11 17:19:42 +00004420 continue;
4421
Sean Huntcdee3fe2011-05-11 22:34:38 +00004422 QualType FieldType = Context.getBaseElementType(FI->getType());
4423 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
Richard Smith7a614d82011-06-11 17:19:42 +00004424
Sean Hunte16da072011-10-10 06:18:57 +00004425 // For a default constructor, all references must be initialized in-class
4426 // and, if a union, it must have a non-const member.
4427 if (CSM == CXXDefaultConstructor) {
4428 if (FieldType->isReferenceType() && !FI->hasInClassInitializer())
4429 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004430
Sean Hunte16da072011-10-10 06:18:57 +00004431 if (IsUnion && !FieldType.isConstQualified())
4432 AllConst = false;
Sean Huntc32d6842011-10-11 04:55:36 +00004433 // For a copy constructor, data members must not be of rvalue reference
4434 // type.
4435 } else if (CSM == CXXCopyConstructor) {
4436 if (FieldType->isRValueReferenceType())
4437 return true;
Sean Hunte16da072011-10-10 06:18:57 +00004438 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004439
4440 if (FieldRecord) {
Sean Hunte16da072011-10-10 06:18:57 +00004441 // For a default constructor, a const member must have a user-provided
4442 // default constructor or else be explicitly initialized.
4443 if (CSM == CXXDefaultConstructor && FieldType.isConstQualified() &&
Richard Smith7a614d82011-06-11 17:19:42 +00004444 !FI->hasInClassInitializer() &&
Sean Huntcdee3fe2011-05-11 22:34:38 +00004445 !FieldRecord->hasUserProvidedDefaultConstructor())
4446 return true;
4447
Sean Huntc32d6842011-10-11 04:55:36 +00004448 // Some additional restrictions exist on the variant members.
4449 if (!IsUnion && FieldRecord->isUnion() &&
Sean Huntcdee3fe2011-05-11 22:34:38 +00004450 FieldRecord->isAnonymousStructOrUnion()) {
4451 // We're okay to reuse AllConst here since we only care about the
4452 // value otherwise if we're in a union.
4453 AllConst = true;
4454
4455 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4456 UE = FieldRecord->field_end();
4457 UI != UE; ++UI) {
4458 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4459 CXXRecordDecl *UnionFieldRecord =
4460 UnionFieldType->getAsCXXRecordDecl();
4461
4462 if (!UnionFieldType.isConstQualified())
4463 AllConst = false;
4464
Sean Huntc32d6842011-10-11 04:55:36 +00004465 if (UnionFieldRecord) {
4466 // FIXME: Checking for accessibility and validity of this
4467 // destructor is technically going beyond the
4468 // standard, but this is believed to be a defect.
4469 if (!IsAssignment) {
4470 CXXDestructorDecl *FieldDtor = LookupDestructor(UnionFieldRecord);
4471 if (FieldDtor->isDeleted())
4472 return true;
4473 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
4474 AR_accessible)
4475 return true;
4476 if (!FieldDtor->isTrivial())
4477 return true;
4478 }
4479
4480 if (CSM != CXXDestructor) {
4481 SpecialMemberOverloadResult *SMOR =
4482 LookupSpecialMember(UnionFieldRecord, CSM, ConstArg, false,
Sean Hunt769bb2d2011-10-11 06:43:29 +00004483 false, false, false);
Sean Huntc32d6842011-10-11 04:55:36 +00004484 // FIXME: Checking for accessibility and validity of this
4485 // corresponding member is technically going beyond the
4486 // standard, but this is believed to be a defect.
4487 if (!SMOR->hasSuccess())
4488 return true;
4489
4490 CXXMethodDecl *FieldMember = SMOR->getMethod();
4491 // A member of a union must have a trivial corresponding
4492 // constructor.
4493 if (!FieldMember->isTrivial())
4494 return true;
4495
4496 if (IsConstructor) {
4497 CXXConstructorDecl *FieldCtor = cast<CXXConstructorDecl>(FieldMember);
4498 if (CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getAccess(),
4499 PDiag()) != AR_accessible)
4500 return true;
4501 }
4502 }
4503 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004504 }
Sean Hunt2be7e902011-05-12 22:46:29 +00004505
Sean Huntc32d6842011-10-11 04:55:36 +00004506 // At least one member in each anonymous union must be non-const
4507 if (CSM == CXXDefaultConstructor && AllConst)
Sean Huntcdee3fe2011-05-11 22:34:38 +00004508 return true;
4509
4510 // Don't try to initialize the anonymous union
Sean Hunta6bff2c2011-05-11 22:50:12 +00004511 // This is technically non-conformant, but sanity demands it.
Sean Huntcdee3fe2011-05-11 22:34:38 +00004512 continue;
4513 }
Sean Huntb320e0c2011-06-10 03:50:41 +00004514
Sean Huntc32d6842011-10-11 04:55:36 +00004515 // Unless we're doing assignment, the field's destructor must be
4516 // accessible and not deleted.
4517 if (!IsAssignment) {
4518 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
4519 if (FieldDtor->isDeleted())
4520 return true;
4521 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
4522 AR_accessible)
4523 return true;
4524 }
4525
Sean Hunte16da072011-10-10 06:18:57 +00004526 // Check that the corresponding member of the field is accessible,
4527 // unique, and non-deleted. We don't do this if it has an explicit
4528 // initialization when default-constructing.
4529 if (CSM != CXXDestructor &&
4530 (CSM != CXXDefaultConstructor || !FI->hasInClassInitializer())) {
4531 SpecialMemberOverloadResult *SMOR =
Sean Hunt769bb2d2011-10-11 06:43:29 +00004532 LookupSpecialMember(FieldRecord, CSM, ConstArg, false, false, false,
Sean Hunte16da072011-10-10 06:18:57 +00004533 false);
4534 if (!SMOR->hasSuccess())
Richard Smith7a614d82011-06-11 17:19:42 +00004535 return true;
Sean Hunte16da072011-10-10 06:18:57 +00004536
4537 CXXMethodDecl *FieldMember = SMOR->getMethod();
4538 if (IsConstructor) {
4539 CXXConstructorDecl *FieldCtor = cast<CXXConstructorDecl>(FieldMember);
4540 if (CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getAccess(),
4541 PDiag()) != AR_accessible)
4542 return true;
Sean Hunt769bb2d2011-10-11 06:43:29 +00004543
4544 // For a move operation, the corresponding operation must actually
4545 // be a move operation (and not a copy selected by overload
4546 // resolution) unless we are working on a trivially copyable class.
4547 if (IsMove && !FieldCtor->isMoveConstructor() &&
4548 !FieldRecord->isTriviallyCopyable())
4549 return true;
Sean Hunte16da072011-10-10 06:18:57 +00004550 }
4551
4552 // We need the corresponding member of a union to be trivial so that
4553 // we can safely copy them all simultaneously.
4554 // FIXME: Note that performing the check here (where we rely on the lack
4555 // of an in-class initializer) is technically ill-formed. However, this
4556 // seems most obviously to be a bug in the standard.
4557 if (IsUnion && !FieldMember->isTrivial())
Richard Smith7a614d82011-06-11 17:19:42 +00004558 return true;
4559 }
Sean Hunte16da072011-10-10 06:18:57 +00004560 } else if (CSM == CXXDefaultConstructor && !IsUnion &&
4561 FieldType.isConstQualified() && !FI->hasInClassInitializer()) {
4562 // We can't initialize a const member of non-class type to any value.
Sean Hunte3406822011-05-20 21:43:47 +00004563 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004564 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004565 }
4566
Sean Hunte16da072011-10-10 06:18:57 +00004567 // We can't have all const members in a union when default-constructing,
4568 // or else they're all nonsensical garbage values that can't be changed.
4569 if (CSM == CXXDefaultConstructor && IsUnion && AllConst)
Sean Huntcdee3fe2011-05-11 22:34:38 +00004570 return true;
4571
4572 return false;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004573}
4574
Sean Hunt7f410192011-05-14 05:23:24 +00004575bool Sema::ShouldDeleteCopyAssignmentOperator(CXXMethodDecl *MD) {
4576 CXXRecordDecl *RD = MD->getParent();
4577 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaracdb80762011-07-11 08:52:40 +00004578 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Sean Hunt7f410192011-05-14 05:23:24 +00004579 return false;
4580
Sean Hunt71a682f2011-05-18 03:41:58 +00004581 SourceLocation Loc = MD->getLocation();
4582
Sean Hunt7f410192011-05-14 05:23:24 +00004583 // Do access control from the constructor
4584 ContextRAII MethodContext(*this, MD);
4585
4586 bool Union = RD->isUnion();
4587
Sean Hunt661c67a2011-06-21 23:42:56 +00004588 unsigned ArgQuals =
4589 MD->getParamDecl(0)->getType()->getPointeeType().isConstQualified() ?
4590 Qualifiers::Const : 0;
Sean Hunt7f410192011-05-14 05:23:24 +00004591
4592 // We do this because we should never actually use an anonymous
4593 // union's constructor.
4594 if (Union && RD->isAnonymousStructOrUnion())
4595 return false;
4596
Sean Hunt7f410192011-05-14 05:23:24 +00004597 // FIXME: We should put some diagnostic logic right into this function.
4598
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004599 // C++0x [class.copy]/20
Sean Hunt7f410192011-05-14 05:23:24 +00004600 // A defaulted [copy] assignment operator for class X is defined as deleted
4601 // if X has:
4602
4603 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4604 BE = RD->bases_end();
4605 BI != BE; ++BI) {
4606 // We'll handle this one later
4607 if (BI->isVirtual())
4608 continue;
4609
4610 QualType BaseType = BI->getType();
4611 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4612 assert(BaseDecl && "base isn't a CXXRecordDecl");
4613
4614 // -- a [direct base class] B that cannot be [copied] because overload
4615 // resolution, as applied to B's [copy] assignment operator, results in
Sean Hunt2b188082011-05-14 05:23:28 +00004616 // an ambiguity or a function that is deleted or inaccessible from the
Sean Hunt7f410192011-05-14 05:23:24 +00004617 // assignment operator
Sean Hunt661c67a2011-06-21 23:42:56 +00004618 CXXMethodDecl *CopyOper = LookupCopyingAssignment(BaseDecl, ArgQuals, false,
4619 0);
4620 if (!CopyOper || CopyOper->isDeleted())
4621 return true;
4622 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Sean Hunt7f410192011-05-14 05:23:24 +00004623 return true;
4624 }
4625
4626 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4627 BE = RD->vbases_end();
4628 BI != BE; ++BI) {
4629 QualType BaseType = BI->getType();
4630 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4631 assert(BaseDecl && "base isn't a CXXRecordDecl");
4632
Sean Hunt7f410192011-05-14 05:23:24 +00004633 // -- a [virtual base class] B that cannot be [copied] because overload
Sean Hunt2b188082011-05-14 05:23:28 +00004634 // resolution, as applied to B's [copy] assignment operator, results in
4635 // an ambiguity or a function that is deleted or inaccessible from the
4636 // assignment operator
Sean Hunt661c67a2011-06-21 23:42:56 +00004637 CXXMethodDecl *CopyOper = LookupCopyingAssignment(BaseDecl, ArgQuals, false,
4638 0);
4639 if (!CopyOper || CopyOper->isDeleted())
4640 return true;
4641 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Sean Hunt7f410192011-05-14 05:23:24 +00004642 return true;
Sean Hunt7f410192011-05-14 05:23:24 +00004643 }
4644
4645 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4646 FE = RD->field_end();
4647 FI != FE; ++FI) {
Douglas Gregord61db332011-10-10 17:22:13 +00004648 if (FI->isUnnamedBitfield())
4649 continue;
4650
Sean Hunt7f410192011-05-14 05:23:24 +00004651 QualType FieldType = Context.getBaseElementType(FI->getType());
4652
4653 // -- a non-static data member of reference type
4654 if (FieldType->isReferenceType())
4655 return true;
4656
4657 // -- a non-static data member of const non-class type (or array thereof)
4658 if (FieldType.isConstQualified() && !FieldType->isRecordType())
4659 return true;
4660
4661 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4662
4663 if (FieldRecord) {
4664 // This is an anonymous union
4665 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4666 // Anonymous unions inside unions do not variant members create
4667 if (!Union) {
4668 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4669 UE = FieldRecord->field_end();
4670 UI != UE; ++UI) {
4671 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4672 CXXRecordDecl *UnionFieldRecord =
4673 UnionFieldType->getAsCXXRecordDecl();
4674
4675 // -- a variant member with a non-trivial [copy] assignment operator
4676 // and X is a union-like class
4677 if (UnionFieldRecord &&
4678 !UnionFieldRecord->hasTrivialCopyAssignment())
4679 return true;
4680 }
4681 }
4682
4683 // Don't try to initalize an anonymous union
4684 continue;
4685 // -- a variant member with a non-trivial [copy] assignment operator
4686 // and X is a union-like class
4687 } else if (Union && !FieldRecord->hasTrivialCopyAssignment()) {
4688 return true;
4689 }
Sean Hunt7f410192011-05-14 05:23:24 +00004690
Sean Hunt661c67a2011-06-21 23:42:56 +00004691 CXXMethodDecl *CopyOper = LookupCopyingAssignment(FieldRecord, ArgQuals,
4692 false, 0);
4693 if (!CopyOper || CopyOper->isDeleted())
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004694 return true;
Sean Hunt661c67a2011-06-21 23:42:56 +00004695 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004696 return true;
4697 }
4698 }
4699
4700 return false;
4701}
4702
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004703bool Sema::ShouldDeleteMoveAssignmentOperator(CXXMethodDecl *MD) {
4704 CXXRecordDecl *RD = MD->getParent();
4705 assert(!RD->isDependentType() && "do deletion after instantiation");
4706 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
4707 return false;
4708
4709 SourceLocation Loc = MD->getLocation();
4710
4711 // Do access control from the constructor
4712 ContextRAII MethodContext(*this, MD);
4713
4714 bool Union = RD->isUnion();
4715
4716 // We do this because we should never actually use an anonymous
4717 // union's constructor.
4718 if (Union && RD->isAnonymousStructOrUnion())
4719 return false;
4720
4721 // C++0x [class.copy]/20
4722 // A defaulted [move] assignment operator for class X is defined as deleted
4723 // if X has:
4724
4725 // -- for the move constructor, [...] any direct or indirect virtual base
4726 // class.
4727 if (RD->getNumVBases() != 0)
4728 return true;
4729
4730 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4731 BE = RD->bases_end();
4732 BI != BE; ++BI) {
4733
4734 QualType BaseType = BI->getType();
4735 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4736 assert(BaseDecl && "base isn't a CXXRecordDecl");
4737
4738 // -- a [direct base class] B that cannot be [moved] because overload
4739 // resolution, as applied to B's [move] assignment operator, results in
4740 // an ambiguity or a function that is deleted or inaccessible from the
4741 // assignment operator
4742 CXXMethodDecl *MoveOper = LookupMovingAssignment(BaseDecl, false, 0);
4743 if (!MoveOper || MoveOper->isDeleted())
4744 return true;
4745 if (CheckDirectMemberAccess(Loc, MoveOper, PDiag()) != AR_accessible)
4746 return true;
4747
4748 // -- for the move assignment operator, a [direct base class] with a type
4749 // that does not have a move assignment operator and is not trivially
4750 // copyable.
4751 if (!MoveOper->isMoveAssignmentOperator() &&
4752 !BaseDecl->isTriviallyCopyable())
4753 return true;
4754 }
4755
4756 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4757 FE = RD->field_end();
4758 FI != FE; ++FI) {
Douglas Gregord61db332011-10-10 17:22:13 +00004759 if (FI->isUnnamedBitfield())
4760 continue;
4761
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004762 QualType FieldType = Context.getBaseElementType(FI->getType());
4763
4764 // -- a non-static data member of reference type
4765 if (FieldType->isReferenceType())
4766 return true;
4767
4768 // -- a non-static data member of const non-class type (or array thereof)
4769 if (FieldType.isConstQualified() && !FieldType->isRecordType())
4770 return true;
4771
4772 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4773
4774 if (FieldRecord) {
4775 // This is an anonymous union
4776 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4777 // Anonymous unions inside unions do not variant members create
4778 if (!Union) {
4779 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4780 UE = FieldRecord->field_end();
4781 UI != UE; ++UI) {
4782 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4783 CXXRecordDecl *UnionFieldRecord =
4784 UnionFieldType->getAsCXXRecordDecl();
4785
4786 // -- a variant member with a non-trivial [move] assignment operator
4787 // and X is a union-like class
4788 if (UnionFieldRecord &&
4789 !UnionFieldRecord->hasTrivialMoveAssignment())
4790 return true;
4791 }
4792 }
4793
4794 // Don't try to initalize an anonymous union
4795 continue;
4796 // -- a variant member with a non-trivial [move] assignment operator
4797 // and X is a union-like class
4798 } else if (Union && !FieldRecord->hasTrivialMoveAssignment()) {
4799 return true;
4800 }
4801
4802 CXXMethodDecl *MoveOper = LookupMovingAssignment(FieldRecord, false, 0);
4803 if (!MoveOper || MoveOper->isDeleted())
4804 return true;
4805 if (CheckDirectMemberAccess(Loc, MoveOper, PDiag()) != AR_accessible)
4806 return true;
4807
4808 // -- for the move assignment operator, a [non-static data member] with a
4809 // type that does not have a move assignment operator and is not
4810 // trivially copyable.
4811 if (!MoveOper->isMoveAssignmentOperator() &&
4812 !FieldRecord->isTriviallyCopyable())
4813 return true;
Sean Hunt2b188082011-05-14 05:23:28 +00004814 }
Sean Hunt7f410192011-05-14 05:23:24 +00004815 }
4816
4817 return false;
4818}
4819
Sean Huntcb45a0f2011-05-12 22:46:25 +00004820bool Sema::ShouldDeleteDestructor(CXXDestructorDecl *DD) {
4821 CXXRecordDecl *RD = DD->getParent();
4822 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaracdb80762011-07-11 08:52:40 +00004823 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Sean Huntcb45a0f2011-05-12 22:46:25 +00004824 return false;
4825
Sean Hunt71a682f2011-05-18 03:41:58 +00004826 SourceLocation Loc = DD->getLocation();
4827
Sean Huntcb45a0f2011-05-12 22:46:25 +00004828 // Do access control from the destructor
4829 ContextRAII CtorContext(*this, DD);
4830
4831 bool Union = RD->isUnion();
4832
Sean Hunt49634cf2011-05-13 06:10:58 +00004833 // We do this because we should never actually use an anonymous
4834 // union's destructor.
4835 if (Union && RD->isAnonymousStructOrUnion())
4836 return false;
4837
Sean Huntcb45a0f2011-05-12 22:46:25 +00004838 // C++0x [class.dtor]p5
4839 // A defaulted destructor for a class X is defined as deleted if:
4840 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4841 BE = RD->bases_end();
4842 BI != BE; ++BI) {
4843 // We'll handle this one later
4844 if (BI->isVirtual())
4845 continue;
4846
4847 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4848 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4849 assert(BaseDtor && "base has no destructor");
4850
4851 // -- any direct or virtual base class has a deleted destructor or
4852 // a destructor that is inaccessible from the defaulted destructor
4853 if (BaseDtor->isDeleted())
4854 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00004855 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Huntcb45a0f2011-05-12 22:46:25 +00004856 AR_accessible)
4857 return true;
4858 }
4859
4860 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4861 BE = RD->vbases_end();
4862 BI != BE; ++BI) {
4863 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4864 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4865 assert(BaseDtor && "base has no destructor");
4866
4867 // -- any direct or virtual base class has a deleted destructor or
4868 // a destructor that is inaccessible from the defaulted destructor
4869 if (BaseDtor->isDeleted())
4870 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00004871 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Huntcb45a0f2011-05-12 22:46:25 +00004872 AR_accessible)
4873 return true;
4874 }
4875
4876 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4877 FE = RD->field_end();
4878 FI != FE; ++FI) {
4879 QualType FieldType = Context.getBaseElementType(FI->getType());
4880 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4881 if (FieldRecord) {
4882 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4883 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4884 UE = FieldRecord->field_end();
4885 UI != UE; ++UI) {
4886 QualType UnionFieldType = Context.getBaseElementType(FI->getType());
4887 CXXRecordDecl *UnionFieldRecord =
4888 UnionFieldType->getAsCXXRecordDecl();
4889
4890 // -- X is a union-like class that has a variant member with a non-
4891 // trivial destructor.
4892 if (UnionFieldRecord && !UnionFieldRecord->hasTrivialDestructor())
4893 return true;
4894 }
4895 // Technically we are supposed to do this next check unconditionally.
4896 // But that makes absolutely no sense.
4897 } else {
4898 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
4899
4900 // -- any of the non-static data members has class type M (or array
4901 // thereof) and M has a deleted destructor or a destructor that is
4902 // inaccessible from the defaulted destructor
4903 if (FieldDtor->isDeleted())
4904 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00004905 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
Sean Huntcb45a0f2011-05-12 22:46:25 +00004906 AR_accessible)
4907 return true;
4908
4909 // -- X is a union-like class that has a variant member with a non-
4910 // trivial destructor.
4911 if (Union && !FieldDtor->isTrivial())
4912 return true;
4913 }
4914 }
4915 }
4916
4917 if (DD->isVirtual()) {
4918 FunctionDecl *OperatorDelete = 0;
4919 DeclarationName Name =
4920 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Sean Hunt71a682f2011-05-18 03:41:58 +00004921 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete,
Sean Huntcb45a0f2011-05-12 22:46:25 +00004922 false))
4923 return true;
4924 }
4925
4926
4927 return false;
4928}
4929
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004930/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramerc54061a2011-03-04 13:12:48 +00004931namespace {
4932 struct FindHiddenVirtualMethodData {
4933 Sema *S;
4934 CXXMethodDecl *Method;
4935 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004936 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramerc54061a2011-03-04 13:12:48 +00004937 };
4938}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004939
4940/// \brief Member lookup function that determines whether a given C++
4941/// method overloads virtual methods in a base class without overriding any,
4942/// to be used with CXXRecordDecl::lookupInBases().
4943static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
4944 CXXBasePath &Path,
4945 void *UserData) {
4946 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
4947
4948 FindHiddenVirtualMethodData &Data
4949 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
4950
4951 DeclarationName Name = Data.Method->getDeclName();
4952 assert(Name.getNameKind() == DeclarationName::Identifier);
4953
4954 bool foundSameNameMethod = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004955 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004956 for (Path.Decls = BaseRecord->lookup(Name);
4957 Path.Decls.first != Path.Decls.second;
4958 ++Path.Decls.first) {
4959 NamedDecl *D = *Path.Decls.first;
4960 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00004961 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004962 foundSameNameMethod = true;
4963 // Interested only in hidden virtual methods.
4964 if (!MD->isVirtual())
4965 continue;
4966 // If the method we are checking overrides a method from its base
4967 // don't warn about the other overloaded methods.
4968 if (!Data.S->IsOverload(Data.Method, MD, false))
4969 return true;
4970 // Collect the overload only if its hidden.
4971 if (!Data.OverridenAndUsingBaseMethods.count(MD))
4972 overloadedMethods.push_back(MD);
4973 }
4974 }
4975
4976 if (foundSameNameMethod)
4977 Data.OverloadedMethods.append(overloadedMethods.begin(),
4978 overloadedMethods.end());
4979 return foundSameNameMethod;
4980}
4981
4982/// \brief See if a method overloads virtual methods in a base class without
4983/// overriding any.
4984void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
4985 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
David Blaikied6471f72011-09-25 23:23:43 +00004986 MD->getLocation()) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004987 return;
4988 if (MD->getDeclName().getNameKind() != DeclarationName::Identifier)
4989 return;
4990
4991 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
4992 /*bool RecordPaths=*/false,
4993 /*bool DetectVirtual=*/false);
4994 FindHiddenVirtualMethodData Data;
4995 Data.Method = MD;
4996 Data.S = this;
4997
4998 // Keep the base methods that were overriden or introduced in the subclass
4999 // by 'using' in a set. A base method not in this set is hidden.
5000 for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
5001 res.first != res.second; ++res.first) {
5002 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first))
5003 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5004 E = MD->end_overridden_methods();
5005 I != E; ++I)
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00005006 Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005007 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
5008 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl()))
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00005009 Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005010 }
5011
5012 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
5013 !Data.OverloadedMethods.empty()) {
5014 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
5015 << MD << (Data.OverloadedMethods.size() > 1);
5016
5017 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
5018 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
5019 Diag(overloadedMD->getLocation(),
5020 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
5021 }
5022 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005023}
5024
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005025void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00005026 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005027 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00005028 SourceLocation RBrac,
5029 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005030 if (!TagDecl)
5031 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005032
Douglas Gregor42af25f2009-05-11 19:58:34 +00005033 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005034
David Blaikie77b6de02011-09-22 02:58:26 +00005035 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCalld226f652010-08-21 09:40:31 +00005036 // strict aliasing violation!
5037 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie77b6de02011-09-22 02:58:26 +00005038 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00005039
Douglas Gregor23c94db2010-07-02 17:43:08 +00005040 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00005041 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005042}
5043
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005044/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5045/// special functions, such as the default constructor, copy
5046/// constructor, or destructor, to the given C++ class (C++
5047/// [special]p1). This routine can only be executed just before the
5048/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00005049void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00005050 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00005051 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005052
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005053 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregor22584312010-07-02 23:41:54 +00005054 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005055
Richard Smithb701d3d2011-12-24 21:56:24 +00005056 if (getLangOptions().CPlusPlus0x && ClassDecl->needsImplicitMoveConstructor())
5057 ++ASTContext::NumImplicitMoveConstructors;
5058
Douglas Gregora376d102010-07-02 21:50:04 +00005059 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
5060 ++ASTContext::NumImplicitCopyAssignmentOperators;
5061
5062 // If we have a dynamic class, then the copy assignment operator may be
5063 // virtual, so we have to declare it immediately. This ensures that, e.g.,
5064 // it shows up in the right place in the vtable and that we diagnose
5065 // problems with the implicit exception specification.
5066 if (ClassDecl->isDynamicClass())
5067 DeclareImplicitCopyAssignment(ClassDecl);
5068 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00005069
Richard Smithb701d3d2011-12-24 21:56:24 +00005070 if (getLangOptions().CPlusPlus0x && ClassDecl->needsImplicitMoveAssignment()){
5071 ++ASTContext::NumImplicitMoveAssignmentOperators;
5072
5073 // Likewise for the move assignment operator.
5074 if (ClassDecl->isDynamicClass())
5075 DeclareImplicitMoveAssignment(ClassDecl);
5076 }
5077
Douglas Gregor4923aa22010-07-02 20:37:36 +00005078 if (!ClassDecl->hasUserDeclaredDestructor()) {
5079 ++ASTContext::NumImplicitDestructors;
5080
5081 // If we have a dynamic class, then the destructor may be virtual, so we
5082 // have to declare the destructor immediately. This ensures that, e.g., it
5083 // shows up in the right place in the vtable and that we diagnose problems
5084 // with the implicit exception specification.
5085 if (ClassDecl->isDynamicClass())
5086 DeclareImplicitDestructor(ClassDecl);
5087 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005088}
5089
Francois Pichet8387e2a2011-04-22 22:18:13 +00005090void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
5091 if (!D)
5092 return;
5093
5094 int NumParamList = D->getNumTemplateParameterLists();
5095 for (int i = 0; i < NumParamList; i++) {
5096 TemplateParameterList* Params = D->getTemplateParameterList(i);
5097 for (TemplateParameterList::iterator Param = Params->begin(),
5098 ParamEnd = Params->end();
5099 Param != ParamEnd; ++Param) {
5100 NamedDecl *Named = cast<NamedDecl>(*Param);
5101 if (Named->getDeclName()) {
5102 S->AddDecl(Named);
5103 IdResolver.AddDecl(Named);
5104 }
5105 }
5106 }
5107}
5108
John McCalld226f652010-08-21 09:40:31 +00005109void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00005110 if (!D)
5111 return;
5112
5113 TemplateParameterList *Params = 0;
5114 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
5115 Params = Template->getTemplateParameters();
5116 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
5117 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
5118 Params = PartialSpec->getTemplateParameters();
5119 else
Douglas Gregor6569d682009-05-27 23:11:45 +00005120 return;
5121
Douglas Gregor6569d682009-05-27 23:11:45 +00005122 for (TemplateParameterList::iterator Param = Params->begin(),
5123 ParamEnd = Params->end();
5124 Param != ParamEnd; ++Param) {
5125 NamedDecl *Named = cast<NamedDecl>(*Param);
5126 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00005127 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00005128 IdResolver.AddDecl(Named);
5129 }
5130 }
5131}
5132
John McCalld226f652010-08-21 09:40:31 +00005133void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005134 if (!RecordD) return;
5135 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00005136 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00005137 PushDeclContext(S, Record);
5138}
5139
John McCalld226f652010-08-21 09:40:31 +00005140void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005141 if (!RecordD) return;
5142 PopDeclContext();
5143}
5144
Douglas Gregor72b505b2008-12-16 21:30:33 +00005145/// ActOnStartDelayedCXXMethodDeclaration - We have completed
5146/// parsing a top-level (non-nested) C++ class, and we are now
5147/// parsing those parts of the given Method declaration that could
5148/// not be parsed earlier (C++ [class.mem]p2), such as default
5149/// arguments. This action should enter the scope of the given
5150/// Method declaration as if we had just parsed the qualified method
5151/// name. However, it should not bring the parameters into scope;
5152/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00005153void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005154}
5155
5156/// ActOnDelayedCXXMethodParameter - We've already started a delayed
5157/// C++ method declaration. We're (re-)introducing the given
5158/// function parameter into scope for use in parsing later parts of
5159/// the method declaration. For example, we could see an
5160/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00005161void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005162 if (!ParamD)
5163 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005164
John McCalld226f652010-08-21 09:40:31 +00005165 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00005166
5167 // If this parameter has an unparsed default argument, clear it out
5168 // to make way for the parsed default argument.
5169 if (Param->hasUnparsedDefaultArg())
5170 Param->setDefaultArg(0);
5171
John McCalld226f652010-08-21 09:40:31 +00005172 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005173 if (Param->getDeclName())
5174 IdResolver.AddDecl(Param);
5175}
5176
5177/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
5178/// processing the delayed method declaration for Method. The method
5179/// declaration is now considered finished. There may be a separate
5180/// ActOnStartOfFunctionDef action later (not necessarily
5181/// immediately!) for this method, if it was also defined inside the
5182/// class body.
John McCalld226f652010-08-21 09:40:31 +00005183void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005184 if (!MethodD)
5185 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005186
Douglas Gregorefd5bda2009-08-24 11:57:43 +00005187 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00005188
John McCalld226f652010-08-21 09:40:31 +00005189 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005190
5191 // Now that we have our default arguments, check the constructor
5192 // again. It could produce additional diagnostics or affect whether
5193 // the class has implicitly-declared destructors, among other
5194 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00005195 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
5196 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005197
5198 // Check the default arguments, which we may have added.
5199 if (!Method->isInvalidDecl())
5200 CheckCXXDefaultArguments(Method);
5201}
5202
Douglas Gregor42a552f2008-11-05 20:51:48 +00005203/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00005204/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00005205/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005206/// emit diagnostics and set the invalid bit to true. In any case, the type
5207/// will be updated to reflect a well-formed type for the constructor and
5208/// returned.
5209QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005210 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005211 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005212
5213 // C++ [class.ctor]p3:
5214 // A constructor shall not be virtual (10.3) or static (9.4). A
5215 // constructor can be invoked for a const, volatile or const
5216 // volatile object. A constructor shall not be declared const,
5217 // volatile, or const volatile (9.3.2).
5218 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00005219 if (!D.isInvalidType())
5220 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5221 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
5222 << SourceRange(D.getIdentifierLoc());
5223 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005224 }
John McCalld931b082010-08-26 03:08:43 +00005225 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005226 if (!D.isInvalidType())
5227 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5228 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5229 << SourceRange(D.getIdentifierLoc());
5230 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005231 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005232 }
Mike Stump1eb44332009-09-09 15:08:12 +00005233
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005234 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005235 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00005236 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005237 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5238 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005239 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005240 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5241 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005242 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005243 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5244 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00005245 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005246 }
Mike Stump1eb44332009-09-09 15:08:12 +00005247
Douglas Gregorc938c162011-01-26 05:01:58 +00005248 // C++0x [class.ctor]p4:
5249 // A constructor shall not be declared with a ref-qualifier.
5250 if (FTI.hasRefQualifier()) {
5251 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
5252 << FTI.RefQualifierIsLValueRef
5253 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5254 D.setInvalidType();
5255 }
5256
Douglas Gregor42a552f2008-11-05 20:51:48 +00005257 // Rebuild the function type "R" without any type qualifiers (in
5258 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00005259 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00005260 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005261 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
5262 return R;
5263
5264 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5265 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005266 EPI.RefQualifier = RQ_None;
5267
Chris Lattner65401802009-04-25 08:28:21 +00005268 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00005269 Proto->getNumArgs(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005270}
5271
Douglas Gregor72b505b2008-12-16 21:30:33 +00005272/// CheckConstructor - Checks a fully-formed constructor for
5273/// well-formedness, issuing any diagnostics required. Returns true if
5274/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00005275void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00005276 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00005277 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
5278 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00005279 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005280
5281 // C++ [class.copy]p3:
5282 // A declaration of a constructor for a class X is ill-formed if
5283 // its first parameter is of type (optionally cv-qualified) X and
5284 // either there are no other parameters or else all other
5285 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00005286 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00005287 ((Constructor->getNumParams() == 1) ||
5288 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00005289 Constructor->getParamDecl(1)->hasDefaultArg())) &&
5290 Constructor->getTemplateSpecializationKind()
5291 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005292 QualType ParamType = Constructor->getParamDecl(0)->getType();
5293 QualType ClassTy = Context.getTagDeclType(ClassDecl);
5294 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00005295 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005296 const char *ConstRef
5297 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
5298 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00005299 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005300 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00005301
5302 // FIXME: Rather that making the constructor invalid, we should endeavor
5303 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00005304 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005305 }
5306 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00005307}
5308
John McCall15442822010-08-04 01:04:25 +00005309/// CheckDestructor - Checks a fully-formed destructor definition for
5310/// well-formedness, issuing any diagnostics required. Returns true
5311/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005312bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00005313 CXXRecordDecl *RD = Destructor->getParent();
5314
5315 if (Destructor->isVirtual()) {
5316 SourceLocation Loc;
5317
5318 if (!Destructor->isImplicit())
5319 Loc = Destructor->getLocation();
5320 else
5321 Loc = RD->getLocation();
5322
5323 // If we have a virtual destructor, look up the deallocation function
5324 FunctionDecl *OperatorDelete = 0;
5325 DeclarationName Name =
5326 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005327 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00005328 return true;
John McCall5efd91a2010-07-03 18:33:00 +00005329
Eli Friedman5f2987c2012-02-02 03:46:19 +00005330 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00005331
5332 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00005333 }
Anders Carlsson37909802009-11-30 21:24:50 +00005334
5335 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00005336}
5337
Mike Stump1eb44332009-09-09 15:08:12 +00005338static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005339FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
5340 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5341 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00005342 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005343}
5344
Douglas Gregor42a552f2008-11-05 20:51:48 +00005345/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
5346/// the well-formednes of the destructor declarator @p D with type @p
5347/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005348/// emit diagnostics and set the declarator to invalid. Even if this happens,
5349/// will be updated to reflect a well-formed type for the destructor and
5350/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00005351QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005352 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005353 // C++ [class.dtor]p1:
5354 // [...] A typedef-name that names a class is a class-name
5355 // (7.1.3); however, a typedef-name that names a class shall not
5356 // be used as the identifier in the declarator for a destructor
5357 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005358 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smith162e1c12011-04-15 14:24:37 +00005359 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner65401802009-04-25 08:28:21 +00005360 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smith162e1c12011-04-15 14:24:37 +00005361 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00005362 else if (const TemplateSpecializationType *TST =
5363 DeclaratorType->getAs<TemplateSpecializationType>())
5364 if (TST->isTypeAlias())
5365 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5366 << DeclaratorType << 1;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005367
5368 // C++ [class.dtor]p2:
5369 // A destructor is used to destroy objects of its class type. A
5370 // destructor takes no parameters, and no return type can be
5371 // specified for it (not even void). The address of a destructor
5372 // shall not be taken. A destructor shall not be static. A
5373 // destructor can be invoked for a const, volatile or const
5374 // volatile object. A destructor shall not be declared const,
5375 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00005376 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005377 if (!D.isInvalidType())
5378 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
5379 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00005380 << SourceRange(D.getIdentifierLoc())
5381 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5382
John McCalld931b082010-08-26 03:08:43 +00005383 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005384 }
Chris Lattner65401802009-04-25 08:28:21 +00005385 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005386 // Destructors don't have return types, but the parser will
5387 // happily parse something like:
5388 //
5389 // class X {
5390 // float ~X();
5391 // };
5392 //
5393 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005394 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
5395 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5396 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00005397 }
Mike Stump1eb44332009-09-09 15:08:12 +00005398
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005399 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005400 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00005401 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005402 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5403 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005404 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005405 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5406 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005407 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005408 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5409 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00005410 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005411 }
5412
Douglas Gregorc938c162011-01-26 05:01:58 +00005413 // C++0x [class.dtor]p2:
5414 // A destructor shall not be declared with a ref-qualifier.
5415 if (FTI.hasRefQualifier()) {
5416 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
5417 << FTI.RefQualifierIsLValueRef
5418 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5419 D.setInvalidType();
5420 }
5421
Douglas Gregor42a552f2008-11-05 20:51:48 +00005422 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005423 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005424 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
5425
5426 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00005427 FTI.freeArgs();
5428 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005429 }
5430
Mike Stump1eb44332009-09-09 15:08:12 +00005431 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00005432 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005433 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00005434 D.setInvalidType();
5435 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00005436
5437 // Rebuild the function type "R" without any type qualifiers or
5438 // parameters (in case any of the errors above fired) and with
5439 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00005440 // types.
John McCalle23cf432010-12-14 08:05:40 +00005441 if (!D.isInvalidType())
5442 return R;
5443
Douglas Gregord92ec472010-07-01 05:10:53 +00005444 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005445 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5446 EPI.Variadic = false;
5447 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005448 EPI.RefQualifier = RQ_None;
John McCalle23cf432010-12-14 08:05:40 +00005449 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005450}
5451
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005452/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
5453/// well-formednes of the conversion function declarator @p D with
5454/// type @p R. If there are any errors in the declarator, this routine
5455/// will emit diagnostics and return true. Otherwise, it will return
5456/// false. Either way, the type @p R will be updated to reflect a
5457/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00005458void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00005459 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005460 // C++ [class.conv.fct]p1:
5461 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00005462 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00005463 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00005464 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00005465 if (!D.isInvalidType())
5466 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
5467 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5468 << SourceRange(D.getIdentifierLoc());
5469 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005470 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005471 }
John McCalla3f81372010-04-13 00:04:31 +00005472
5473 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
5474
Chris Lattner6e475012009-04-25 08:35:12 +00005475 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005476 // Conversion functions don't have return types, but the parser will
5477 // happily parse something like:
5478 //
5479 // class X {
5480 // float operator bool();
5481 // };
5482 //
5483 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005484 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
5485 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5486 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00005487 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005488 }
5489
John McCalla3f81372010-04-13 00:04:31 +00005490 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5491
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005492 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00005493 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005494 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
5495
5496 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005497 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00005498 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00005499 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005500 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00005501 D.setInvalidType();
5502 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005503
John McCalla3f81372010-04-13 00:04:31 +00005504 // Diagnose "&operator bool()" and other such nonsense. This
5505 // is actually a gcc extension which we don't support.
5506 if (Proto->getResultType() != ConvType) {
5507 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
5508 << Proto->getResultType();
5509 D.setInvalidType();
5510 ConvType = Proto->getResultType();
5511 }
5512
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005513 // C++ [class.conv.fct]p4:
5514 // The conversion-type-id shall not represent a function type nor
5515 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005516 if (ConvType->isArrayType()) {
5517 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
5518 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005519 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005520 } else if (ConvType->isFunctionType()) {
5521 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
5522 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005523 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005524 }
5525
5526 // Rebuild the function type "R" without any parameters (in case any
5527 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00005528 // return type.
John McCalle23cf432010-12-14 08:05:40 +00005529 if (D.isInvalidType())
5530 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005531
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005532 // C++0x explicit conversion operators.
Richard Smithebaf0e62011-10-18 20:49:44 +00005533 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump1eb44332009-09-09 15:08:12 +00005534 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smithebaf0e62011-10-18 20:49:44 +00005535 getLangOptions().CPlusPlus0x ?
5536 diag::warn_cxx98_compat_explicit_conversion_functions :
5537 diag::ext_explicit_conversion_functions)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005538 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005539}
5540
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005541/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
5542/// the declaration of the given C++ conversion function. This routine
5543/// is responsible for recording the conversion function in the C++
5544/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00005545Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005546 assert(Conversion && "Expected to receive a conversion function declaration");
5547
Douglas Gregor9d350972008-12-12 08:25:50 +00005548 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005549
5550 // Make sure we aren't redeclaring the conversion function.
5551 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005552
5553 // C++ [class.conv.fct]p1:
5554 // [...] A conversion function is never used to convert a
5555 // (possibly cv-qualified) object to the (possibly cv-qualified)
5556 // same object type (or a reference to it), to a (possibly
5557 // cv-qualified) base class of that type (or a reference to it),
5558 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00005559 // FIXME: Suppress this warning if the conversion function ends up being a
5560 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00005561 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005562 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00005563 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005564 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005565 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
5566 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00005567 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005568 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005569 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
5570 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00005571 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005572 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005573 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00005574 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005575 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005576 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00005577 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005578 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005579 }
5580
Douglas Gregore80622f2010-09-29 04:25:11 +00005581 if (FunctionTemplateDecl *ConversionTemplate
5582 = Conversion->getDescribedFunctionTemplate())
5583 return ConversionTemplate;
5584
John McCalld226f652010-08-21 09:40:31 +00005585 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005586}
5587
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005588//===----------------------------------------------------------------------===//
5589// Namespace Handling
5590//===----------------------------------------------------------------------===//
5591
John McCallea318642010-08-26 09:15:37 +00005592
5593
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005594/// ActOnStartNamespaceDef - This is called at the start of a namespace
5595/// definition.
John McCalld226f652010-08-21 09:40:31 +00005596Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00005597 SourceLocation InlineLoc,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005598 SourceLocation NamespaceLoc,
John McCallea318642010-08-26 09:15:37 +00005599 SourceLocation IdentLoc,
5600 IdentifierInfo *II,
5601 SourceLocation LBrace,
5602 AttributeList *AttrList) {
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005603 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
5604 // For anonymous namespace, take the location of the left brace.
5605 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005606 bool IsInline = InlineLoc.isValid();
Douglas Gregor67310742012-01-10 22:14:10 +00005607 bool IsInvalid = false;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005608 bool IsStd = false;
5609 bool AddToKnown = false;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005610 Scope *DeclRegionScope = NamespcScope->getParent();
5611
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005612 NamespaceDecl *PrevNS = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005613 if (II) {
5614 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00005615 // The identifier in an original-namespace-definition shall not
5616 // have been previously defined in the declarative region in
5617 // which the original-namespace-definition appears. The
5618 // identifier in an original-namespace-definition is the name of
5619 // the namespace. Subsequently in that declarative region, it is
5620 // treated as an original-namespace-name.
5621 //
5622 // Since namespace names are unique in their scope, and we don't
Douglas Gregor010157f2011-05-06 23:28:47 +00005623 // look through using directives, just look for any ordinary names.
5624
5625 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005626 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
5627 Decl::IDNS_Namespace;
Douglas Gregor010157f2011-05-06 23:28:47 +00005628 NamedDecl *PrevDecl = 0;
5629 for (DeclContext::lookup_result R
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005630 = CurContext->getRedeclContext()->lookup(II);
Douglas Gregor010157f2011-05-06 23:28:47 +00005631 R.first != R.second; ++R.first) {
5632 if ((*R.first)->getIdentifierNamespace() & IDNS) {
5633 PrevDecl = *R.first;
5634 break;
5635 }
5636 }
5637
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005638 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
5639
5640 if (PrevNS) {
Douglas Gregor44b43212008-12-11 16:49:14 +00005641 // This is an extended namespace definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005642 if (IsInline != PrevNS->isInline()) {
Sebastian Redl4e4d5702010-08-31 00:36:36 +00005643 // inline-ness must match
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005644 if (PrevNS->isInline()) {
Douglas Gregorb7ec9062011-05-20 15:48:31 +00005645 // The user probably just forgot the 'inline', so suggest that it
5646 // be added back.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005647 Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
Douglas Gregorb7ec9062011-05-20 15:48:31 +00005648 << FixItHint::CreateInsertion(NamespaceLoc, "inline ");
5649 } else {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005650 Diag(Loc, diag::err_inline_namespace_mismatch)
5651 << IsInline;
Douglas Gregorb7ec9062011-05-20 15:48:31 +00005652 }
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005653 Diag(PrevNS->getLocation(), diag::note_previous_definition);
5654
5655 IsInline = PrevNS->isInline();
5656 }
Douglas Gregor44b43212008-12-11 16:49:14 +00005657 } else if (PrevDecl) {
5658 // This is an invalid name redefinition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005659 Diag(Loc, diag::err_redefinition_different_kind)
5660 << II;
Douglas Gregor44b43212008-12-11 16:49:14 +00005661 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00005662 IsInvalid = true;
Douglas Gregor44b43212008-12-11 16:49:14 +00005663 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005664 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00005665 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00005666 // This is the first "real" definition of the namespace "std", so update
5667 // our cache of the "std" namespace to point at this definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005668 PrevNS = getStdNamespace();
5669 IsStd = true;
5670 AddToKnown = !IsInline;
5671 } else {
5672 // We've seen this namespace for the first time.
5673 AddToKnown = !IsInline;
Mike Stump1eb44332009-09-09 15:08:12 +00005674 }
Douglas Gregor44b43212008-12-11 16:49:14 +00005675 } else {
John McCall9aeed322009-10-01 00:25:31 +00005676 // Anonymous namespaces.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005677
5678 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl7a126a42010-08-31 00:36:30 +00005679 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00005680 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005681 PrevNS = TU->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00005682 } else {
5683 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005684 PrevNS = ND->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00005685 }
5686
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005687 if (PrevNS && IsInline != PrevNS->isInline()) {
5688 // inline-ness must match
5689 Diag(Loc, diag::err_inline_namespace_mismatch)
5690 << IsInline;
5691 Diag(PrevNS->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00005692
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005693 // Recover by ignoring the new namespace's inline status.
5694 IsInline = PrevNS->isInline();
5695 }
5696 }
5697
5698 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
5699 StartLoc, Loc, II, PrevNS);
Douglas Gregor67310742012-01-10 22:14:10 +00005700 if (IsInvalid)
5701 Namespc->setInvalidDecl();
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005702
5703 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00005704
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005705 // FIXME: Should we be merging attributes?
5706 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00005707 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005708
5709 if (IsStd)
5710 StdNamespace = Namespc;
5711 if (AddToKnown)
5712 KnownNamespaces[Namespc] = false;
5713
5714 if (II) {
5715 PushOnScopeChains(Namespc, DeclRegionScope);
5716 } else {
5717 // Link the anonymous namespace into its parent.
5718 DeclContext *Parent = CurContext->getRedeclContext();
5719 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
5720 TU->setAnonymousNamespace(Namespc);
5721 } else {
5722 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall5fdd7642009-12-16 02:06:49 +00005723 }
John McCall9aeed322009-10-01 00:25:31 +00005724
Douglas Gregora4181472010-03-24 00:46:35 +00005725 CurContext->addDecl(Namespc);
5726
John McCall9aeed322009-10-01 00:25:31 +00005727 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
5728 // behaves as if it were replaced by
5729 // namespace unique { /* empty body */ }
5730 // using namespace unique;
5731 // namespace unique { namespace-body }
5732 // where all occurrences of 'unique' in a translation unit are
5733 // replaced by the same identifier and this identifier differs
5734 // from all other identifiers in the entire program.
5735
5736 // We just create the namespace with an empty name and then add an
5737 // implicit using declaration, just like the standard suggests.
5738 //
5739 // CodeGen enforces the "universally unique" aspect by giving all
5740 // declarations semantically contained within an anonymous
5741 // namespace internal linkage.
5742
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005743 if (!PrevNS) {
John McCall5fdd7642009-12-16 02:06:49 +00005744 UsingDirectiveDecl* UD
5745 = UsingDirectiveDecl::Create(Context, CurContext,
5746 /* 'using' */ LBrace,
5747 /* 'namespace' */ SourceLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00005748 /* qualifier */ NestedNameSpecifierLoc(),
John McCall5fdd7642009-12-16 02:06:49 +00005749 /* identifier */ SourceLocation(),
5750 Namespc,
5751 /* Ancestor */ CurContext);
5752 UD->setImplicit();
5753 CurContext->addDecl(UD);
5754 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005755 }
5756
5757 // Although we could have an invalid decl (i.e. the namespace name is a
5758 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00005759 // FIXME: We should be able to push Namespc here, so that the each DeclContext
5760 // for the namespace has the declarations that showed up in that particular
5761 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00005762 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00005763 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005764}
5765
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005766/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
5767/// is a namespace alias, returns the namespace it points to.
5768static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
5769 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
5770 return AD->getNamespace();
5771 return dyn_cast_or_null<NamespaceDecl>(D);
5772}
5773
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005774/// ActOnFinishNamespaceDef - This callback is called after a namespace is
5775/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00005776void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005777 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
5778 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005779 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005780 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00005781 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00005782 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005783}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005784
John McCall384aff82010-08-25 07:42:41 +00005785CXXRecordDecl *Sema::getStdBadAlloc() const {
5786 return cast_or_null<CXXRecordDecl>(
5787 StdBadAlloc.get(Context.getExternalSource()));
5788}
5789
5790NamespaceDecl *Sema::getStdNamespace() const {
5791 return cast_or_null<NamespaceDecl>(
5792 StdNamespace.get(Context.getExternalSource()));
5793}
5794
Douglas Gregor66992202010-06-29 17:53:46 +00005795/// \brief Retrieve the special "std" namespace, which may require us to
5796/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00005797NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00005798 if (!StdNamespace) {
5799 // The "std" namespace has not yet been defined, so build one implicitly.
5800 StdNamespace = NamespaceDecl::Create(Context,
5801 Context.getTranslationUnitDecl(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005802 /*Inline=*/false,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005803 SourceLocation(), SourceLocation(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005804 &PP.getIdentifierTable().get("std"),
5805 /*PrevDecl=*/0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00005806 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00005807 }
5808
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00005809 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00005810}
5811
Sebastian Redl395e04d2012-01-17 22:49:33 +00005812bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
5813 assert(getLangOptions().CPlusPlus &&
5814 "Looking for std::initializer_list outside of C++.");
5815
5816 // We're looking for implicit instantiations of
5817 // template <typename E> class std::initializer_list.
5818
5819 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
5820 return false;
5821
Sebastian Redl84760e32012-01-17 22:49:58 +00005822 ClassTemplateDecl *Template = 0;
5823 const TemplateArgument *Arguments = 0;
Sebastian Redl395e04d2012-01-17 22:49:33 +00005824
Sebastian Redl84760e32012-01-17 22:49:58 +00005825 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl395e04d2012-01-17 22:49:33 +00005826
Sebastian Redl84760e32012-01-17 22:49:58 +00005827 ClassTemplateSpecializationDecl *Specialization =
5828 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
5829 if (!Specialization)
5830 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00005831
Sebastian Redl84760e32012-01-17 22:49:58 +00005832 Template = Specialization->getSpecializedTemplate();
5833 Arguments = Specialization->getTemplateArgs().data();
5834 } else if (const TemplateSpecializationType *TST =
5835 Ty->getAs<TemplateSpecializationType>()) {
5836 Template = dyn_cast_or_null<ClassTemplateDecl>(
5837 TST->getTemplateName().getAsTemplateDecl());
5838 Arguments = TST->getArgs();
5839 }
5840 if (!Template)
5841 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00005842
5843 if (!StdInitializerList) {
5844 // Haven't recognized std::initializer_list yet, maybe this is it.
5845 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
5846 if (TemplateClass->getIdentifier() !=
5847 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redlb832f6d2012-01-23 22:09:39 +00005848 !getStdNamespace()->InEnclosingNamespaceSetOf(
5849 TemplateClass->getDeclContext()))
Sebastian Redl395e04d2012-01-17 22:49:33 +00005850 return false;
5851 // This is a template called std::initializer_list, but is it the right
5852 // template?
5853 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00005854 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl395e04d2012-01-17 22:49:33 +00005855 return false;
5856 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
5857 return false;
5858
5859 // It's the right template.
5860 StdInitializerList = Template;
5861 }
5862
5863 if (Template != StdInitializerList)
5864 return false;
5865
5866 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl84760e32012-01-17 22:49:58 +00005867 if (Element)
5868 *Element = Arguments[0].getAsType();
Sebastian Redl395e04d2012-01-17 22:49:33 +00005869 return true;
5870}
5871
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00005872static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
5873 NamespaceDecl *Std = S.getStdNamespace();
5874 if (!Std) {
5875 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
5876 return 0;
5877 }
5878
5879 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
5880 Loc, Sema::LookupOrdinaryName);
5881 if (!S.LookupQualifiedName(Result, Std)) {
5882 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
5883 return 0;
5884 }
5885 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
5886 if (!Template) {
5887 Result.suppressDiagnostics();
5888 // We found something weird. Complain about the first thing we found.
5889 NamedDecl *Found = *Result.begin();
5890 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
5891 return 0;
5892 }
5893
5894 // We found some template called std::initializer_list. Now verify that it's
5895 // correct.
5896 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00005897 if (Params->getMinRequiredArguments() != 1 ||
5898 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00005899 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
5900 return 0;
5901 }
5902
5903 return Template;
5904}
5905
5906QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
5907 if (!StdInitializerList) {
5908 StdInitializerList = LookupStdInitializerList(*this, Loc);
5909 if (!StdInitializerList)
5910 return QualType();
5911 }
5912
5913 TemplateArgumentListInfo Args(Loc, Loc);
5914 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
5915 Context.getTrivialTypeSourceInfo(Element,
5916 Loc)));
5917 return Context.getCanonicalType(
5918 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
5919}
5920
Sebastian Redl98d36062012-01-17 22:50:14 +00005921bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
5922 // C++ [dcl.init.list]p2:
5923 // A constructor is an initializer-list constructor if its first parameter
5924 // is of type std::initializer_list<E> or reference to possibly cv-qualified
5925 // std::initializer_list<E> for some type E, and either there are no other
5926 // parameters or else all other parameters have default arguments.
5927 if (Ctor->getNumParams() < 1 ||
5928 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
5929 return false;
5930
5931 QualType ArgType = Ctor->getParamDecl(0)->getType();
5932 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
5933 ArgType = RT->getPointeeType().getUnqualifiedType();
5934
5935 return isStdInitializerList(ArgType, 0);
5936}
5937
Douglas Gregor9172aa62011-03-26 22:25:30 +00005938/// \brief Determine whether a using statement is in a context where it will be
5939/// apply in all contexts.
5940static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
5941 switch (CurContext->getDeclKind()) {
5942 case Decl::TranslationUnit:
5943 return true;
5944 case Decl::LinkageSpec:
5945 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
5946 default:
5947 return false;
5948 }
5949}
5950
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005951namespace {
5952
5953// Callback to only accept typo corrections that are namespaces.
5954class NamespaceValidatorCCC : public CorrectionCandidateCallback {
5955 public:
5956 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
5957 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
5958 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
5959 }
5960 return false;
5961 }
5962};
5963
5964}
5965
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005966static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
5967 CXXScopeSpec &SS,
5968 SourceLocation IdentLoc,
5969 IdentifierInfo *Ident) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005970 NamespaceValidatorCCC Validator;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005971 R.clear();
5972 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005973 R.getLookupKind(), Sc, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00005974 Validator)) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005975 std::string CorrectedStr(Corrected.getAsString(S.getLangOptions()));
5976 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOptions()));
5977 if (DeclContext *DC = S.computeDeclContext(SS, false))
5978 S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
5979 << Ident << DC << CorrectedQuotedStr << SS.getRange()
5980 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
5981 else
5982 S.Diag(IdentLoc, diag::err_using_directive_suggest)
5983 << Ident << CorrectedQuotedStr
5984 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005985
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005986 S.Diag(Corrected.getCorrectionDecl()->getLocation(),
5987 diag::note_namespace_defined_here) << CorrectedQuotedStr;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005988
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005989 Ident = Corrected.getCorrectionAsIdentifierInfo();
5990 R.addDecl(Corrected.getCorrectionDecl());
5991 return true;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005992 }
5993 return false;
5994}
5995
John McCalld226f652010-08-21 09:40:31 +00005996Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005997 SourceLocation UsingLoc,
5998 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00005999 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006000 SourceLocation IdentLoc,
6001 IdentifierInfo *NamespcName,
6002 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00006003 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6004 assert(NamespcName && "Invalid NamespcName.");
6005 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00006006
6007 // This can only happen along a recovery path.
6008 while (S->getFlags() & Scope::TemplateParamScope)
6009 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006010 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00006011
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006012 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00006013 NestedNameSpecifier *Qualifier = 0;
6014 if (SS.isSet())
6015 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
6016
Douglas Gregoreb11cd02009-01-14 22:20:51 +00006017 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00006018 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
6019 LookupParsedName(R, S, &SS);
6020 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00006021 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00006022
Douglas Gregor66992202010-06-29 17:53:46 +00006023 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006024 R.clear();
Douglas Gregor66992202010-06-29 17:53:46 +00006025 // Allow "using namespace std;" or "using namespace ::std;" even if
6026 // "std" hasn't been defined yet, for GCC compatibility.
6027 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
6028 NamespcName->isStr("std")) {
6029 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006030 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00006031 R.resolveKind();
6032 }
6033 // Otherwise, attempt typo correction.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006034 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00006035 }
6036
John McCallf36e02d2009-10-09 21:13:30 +00006037 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006038 NamedDecl *Named = R.getFoundDecl();
6039 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
6040 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006041 // C++ [namespace.udir]p1:
6042 // A using-directive specifies that the names in the nominated
6043 // namespace can be used in the scope in which the
6044 // using-directive appears after the using-directive. During
6045 // unqualified name lookup (3.4.1), the names appear as if they
6046 // were declared in the nearest enclosing namespace which
6047 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00006048 // namespace. [Note: in this context, "contains" means "contains
6049 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006050
6051 // Find enclosing context containing both using-directive and
6052 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006053 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006054 DeclContext *CommonAncestor = cast<DeclContext>(NS);
6055 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
6056 CommonAncestor = CommonAncestor->getParent();
6057
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006058 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregordb992412011-02-25 16:33:46 +00006059 SS.getWithLocInContext(Context),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006060 IdentLoc, Named, CommonAncestor);
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006061
Douglas Gregor9172aa62011-03-26 22:25:30 +00006062 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Chandler Carruth40278532011-07-25 16:49:02 +00006063 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006064 Diag(IdentLoc, diag::warn_using_directive_in_header);
6065 }
6066
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006067 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006068 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00006069 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00006070 }
6071
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006072 // FIXME: We ignore attributes for now.
John McCalld226f652010-08-21 09:40:31 +00006073 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006074}
6075
6076void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
6077 // If scope has associated entity, then using directive is at namespace
6078 // or translation unit scope. We add UsingDirectiveDecls, into
6079 // it's lookup structure.
6080 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006081 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006082 else
6083 // Otherwise it is block-sope. using-directives will affect lookup
6084 // only to the end of scope.
John McCalld226f652010-08-21 09:40:31 +00006085 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006086}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006087
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006088
John McCalld226f652010-08-21 09:40:31 +00006089Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00006090 AccessSpecifier AS,
6091 bool HasUsingKeyword,
6092 SourceLocation UsingLoc,
6093 CXXScopeSpec &SS,
6094 UnqualifiedId &Name,
6095 AttributeList *AttrList,
6096 bool IsTypeName,
6097 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006098 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00006099
Douglas Gregor12c118a2009-11-04 16:30:06 +00006100 switch (Name.getKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00006101 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006102 case UnqualifiedId::IK_Identifier:
6103 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00006104 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006105 case UnqualifiedId::IK_ConversionFunctionId:
6106 break;
6107
6108 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00006109 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall604e7f12009-12-08 07:46:18 +00006110 // C++0x inherited constructors.
Richard Smithebaf0e62011-10-18 20:49:44 +00006111 Diag(Name.getSourceRange().getBegin(),
6112 getLangOptions().CPlusPlus0x ?
6113 diag::warn_cxx98_compat_using_decl_constructor :
6114 diag::err_using_decl_constructor)
6115 << SS.getRange();
6116
John McCall604e7f12009-12-08 07:46:18 +00006117 if (getLangOptions().CPlusPlus0x) break;
6118
John McCalld226f652010-08-21 09:40:31 +00006119 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006120
6121 case UnqualifiedId::IK_DestructorName:
6122 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
6123 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00006124 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006125
6126 case UnqualifiedId::IK_TemplateId:
6127 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
6128 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00006129 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006130 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006131
6132 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
6133 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00006134 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00006135 return 0;
John McCall604e7f12009-12-08 07:46:18 +00006136
John McCall60fa3cf2009-12-11 02:10:03 +00006137 // Warn about using declarations.
6138 // TODO: store that the declaration was written without 'using' and
6139 // talk about access decls instead of using decls in the
6140 // diagnostics.
6141 if (!HasUsingKeyword) {
6142 UsingLoc = Name.getSourceRange().getBegin();
6143
6144 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00006145 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00006146 }
6147
Douglas Gregor56c04582010-12-16 00:46:58 +00006148 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
6149 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
6150 return 0;
6151
John McCall9488ea12009-11-17 05:59:44 +00006152 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006153 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006154 /* IsInstantiation */ false,
6155 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00006156 if (UD)
6157 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00006158
John McCalld226f652010-08-21 09:40:31 +00006159 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00006160}
6161
Douglas Gregor09acc982010-07-07 23:08:52 +00006162/// \brief Determine whether a using declaration considers the given
6163/// declarations as "equivalent", e.g., if they are redeclarations of
6164/// the same entity or are both typedefs of the same type.
6165static bool
6166IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
6167 bool &SuppressRedeclaration) {
6168 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
6169 SuppressRedeclaration = false;
6170 return true;
6171 }
6172
Richard Smith162e1c12011-04-15 14:24:37 +00006173 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
6174 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor09acc982010-07-07 23:08:52 +00006175 SuppressRedeclaration = true;
6176 return Context.hasSameType(TD1->getUnderlyingType(),
6177 TD2->getUnderlyingType());
6178 }
6179
6180 return false;
6181}
6182
6183
John McCall9f54ad42009-12-10 09:41:52 +00006184/// Determines whether to create a using shadow decl for a particular
6185/// decl, given the set of decls existing prior to this using lookup.
6186bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
6187 const LookupResult &Previous) {
6188 // Diagnose finding a decl which is not from a base class of the
6189 // current class. We do this now because there are cases where this
6190 // function will silently decide not to build a shadow decl, which
6191 // will pre-empt further diagnostics.
6192 //
6193 // We don't need to do this in C++0x because we do the check once on
6194 // the qualifier.
6195 //
6196 // FIXME: diagnose the following if we care enough:
6197 // struct A { int foo; };
6198 // struct B : A { using A::foo; };
6199 // template <class T> struct C : A {};
6200 // template <class T> struct D : C<T> { using B::foo; } // <---
6201 // This is invalid (during instantiation) in C++03 because B::foo
6202 // resolves to the using decl in B, which is not a base class of D<T>.
6203 // We can't diagnose it immediately because C<T> is an unknown
6204 // specialization. The UsingShadowDecl in D<T> then points directly
6205 // to A::foo, which will look well-formed when we instantiate.
6206 // The right solution is to not collapse the shadow-decl chain.
6207 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
6208 DeclContext *OrigDC = Orig->getDeclContext();
6209
6210 // Handle enums and anonymous structs.
6211 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
6212 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
6213 while (OrigRec->isAnonymousStructOrUnion())
6214 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
6215
6216 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
6217 if (OrigDC == CurContext) {
6218 Diag(Using->getLocation(),
6219 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006220 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006221 Diag(Orig->getLocation(), diag::note_using_decl_target);
6222 return true;
6223 }
6224
Douglas Gregordc355712011-02-25 00:36:19 +00006225 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall9f54ad42009-12-10 09:41:52 +00006226 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006227 << Using->getQualifier()
John McCall9f54ad42009-12-10 09:41:52 +00006228 << cast<CXXRecordDecl>(CurContext)
Douglas Gregordc355712011-02-25 00:36:19 +00006229 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006230 Diag(Orig->getLocation(), diag::note_using_decl_target);
6231 return true;
6232 }
6233 }
6234
6235 if (Previous.empty()) return false;
6236
6237 NamedDecl *Target = Orig;
6238 if (isa<UsingShadowDecl>(Target))
6239 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6240
John McCalld7533ec2009-12-11 02:33:26 +00006241 // If the target happens to be one of the previous declarations, we
6242 // don't have a conflict.
6243 //
6244 // FIXME: but we might be increasing its access, in which case we
6245 // should redeclare it.
6246 NamedDecl *NonTag = 0, *Tag = 0;
6247 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6248 I != E; ++I) {
6249 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00006250 bool Result;
6251 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
6252 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00006253
6254 (isa<TagDecl>(D) ? Tag : NonTag) = D;
6255 }
6256
John McCall9f54ad42009-12-10 09:41:52 +00006257 if (Target->isFunctionOrFunctionTemplate()) {
6258 FunctionDecl *FD;
6259 if (isa<FunctionTemplateDecl>(Target))
6260 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
6261 else
6262 FD = cast<FunctionDecl>(Target);
6263
6264 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00006265 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00006266 case Ovl_Overload:
6267 return false;
6268
6269 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00006270 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006271 break;
6272
6273 // We found a decl with the exact signature.
6274 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00006275 // If we're in a record, we want to hide the target, so we
6276 // return true (without a diagnostic) to tell the caller not to
6277 // build a shadow decl.
6278 if (CurContext->isRecord())
6279 return true;
6280
6281 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00006282 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006283 break;
6284 }
6285
6286 Diag(Target->getLocation(), diag::note_using_decl_target);
6287 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
6288 return true;
6289 }
6290
6291 // Target is not a function.
6292
John McCall9f54ad42009-12-10 09:41:52 +00006293 if (isa<TagDecl>(Target)) {
6294 // No conflict between a tag and a non-tag.
6295 if (!Tag) return false;
6296
John McCall41ce66f2009-12-10 19:51:03 +00006297 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006298 Diag(Target->getLocation(), diag::note_using_decl_target);
6299 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
6300 return true;
6301 }
6302
6303 // No conflict between a tag and a non-tag.
6304 if (!NonTag) return false;
6305
John McCall41ce66f2009-12-10 19:51:03 +00006306 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006307 Diag(Target->getLocation(), diag::note_using_decl_target);
6308 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
6309 return true;
6310}
6311
John McCall9488ea12009-11-17 05:59:44 +00006312/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00006313UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00006314 UsingDecl *UD,
6315 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00006316
6317 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00006318 NamedDecl *Target = Orig;
6319 if (isa<UsingShadowDecl>(Target)) {
6320 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6321 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00006322 }
6323
6324 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00006325 = UsingShadowDecl::Create(Context, CurContext,
6326 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00006327 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00006328
6329 Shadow->setAccess(UD->getAccess());
6330 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
6331 Shadow->setInvalidDecl();
6332
John McCall9488ea12009-11-17 05:59:44 +00006333 if (S)
John McCall604e7f12009-12-08 07:46:18 +00006334 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00006335 else
John McCall604e7f12009-12-08 07:46:18 +00006336 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00006337
John McCall604e7f12009-12-08 07:46:18 +00006338
John McCall9f54ad42009-12-10 09:41:52 +00006339 return Shadow;
6340}
John McCall604e7f12009-12-08 07:46:18 +00006341
John McCall9f54ad42009-12-10 09:41:52 +00006342/// Hides a using shadow declaration. This is required by the current
6343/// using-decl implementation when a resolvable using declaration in a
6344/// class is followed by a declaration which would hide or override
6345/// one or more of the using decl's targets; for example:
6346///
6347/// struct Base { void foo(int); };
6348/// struct Derived : Base {
6349/// using Base::foo;
6350/// void foo(int);
6351/// };
6352///
6353/// The governing language is C++03 [namespace.udecl]p12:
6354///
6355/// When a using-declaration brings names from a base class into a
6356/// derived class scope, member functions in the derived class
6357/// override and/or hide member functions with the same name and
6358/// parameter types in a base class (rather than conflicting).
6359///
6360/// There are two ways to implement this:
6361/// (1) optimistically create shadow decls when they're not hidden
6362/// by existing declarations, or
6363/// (2) don't create any shadow decls (or at least don't make them
6364/// visible) until we've fully parsed/instantiated the class.
6365/// The problem with (1) is that we might have to retroactively remove
6366/// a shadow decl, which requires several O(n) operations because the
6367/// decl structures are (very reasonably) not designed for removal.
6368/// (2) avoids this but is very fiddly and phase-dependent.
6369void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00006370 if (Shadow->getDeclName().getNameKind() ==
6371 DeclarationName::CXXConversionFunctionName)
6372 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
6373
John McCall9f54ad42009-12-10 09:41:52 +00006374 // Remove it from the DeclContext...
6375 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006376
John McCall9f54ad42009-12-10 09:41:52 +00006377 // ...and the scope, if applicable...
6378 if (S) {
John McCalld226f652010-08-21 09:40:31 +00006379 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00006380 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006381 }
6382
John McCall9f54ad42009-12-10 09:41:52 +00006383 // ...and the using decl.
6384 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
6385
6386 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00006387 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00006388}
6389
John McCall7ba107a2009-11-18 02:36:19 +00006390/// Builds a using declaration.
6391///
6392/// \param IsInstantiation - Whether this call arises from an
6393/// instantiation of an unresolved using declaration. We treat
6394/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00006395NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
6396 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006397 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006398 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00006399 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006400 bool IsInstantiation,
6401 bool IsTypeName,
6402 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00006403 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006404 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00006405 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00006406
Anders Carlsson550b14b2009-08-28 05:49:21 +00006407 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00006408
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006409 if (SS.isEmpty()) {
6410 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00006411 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006412 }
Mike Stump1eb44332009-09-09 15:08:12 +00006413
John McCall9f54ad42009-12-10 09:41:52 +00006414 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006415 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00006416 ForRedeclaration);
6417 Previous.setHideTags(false);
6418 if (S) {
6419 LookupName(Previous, S);
6420
6421 // It is really dumb that we have to do this.
6422 LookupResult::Filter F = Previous.makeFilter();
6423 while (F.hasNext()) {
6424 NamedDecl *D = F.next();
6425 if (!isDeclInScope(D, CurContext, S))
6426 F.erase();
6427 }
6428 F.done();
6429 } else {
6430 assert(IsInstantiation && "no scope in non-instantiation");
6431 assert(CurContext->isRecord() && "scope not record in instantiation");
6432 LookupQualifiedName(Previous, CurContext);
6433 }
6434
John McCall9f54ad42009-12-10 09:41:52 +00006435 // Check for invalid redeclarations.
6436 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
6437 return 0;
6438
6439 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00006440 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
6441 return 0;
6442
John McCallaf8e6ed2009-11-12 03:15:40 +00006443 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00006444 NamedDecl *D;
Douglas Gregordc355712011-02-25 00:36:19 +00006445 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallaf8e6ed2009-11-12 03:15:40 +00006446 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00006447 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00006448 // FIXME: not all declaration name kinds are legal here
6449 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
6450 UsingLoc, TypenameLoc,
Douglas Gregordc355712011-02-25 00:36:19 +00006451 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006452 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00006453 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00006454 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
6455 QualifierLoc, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00006456 }
John McCalled976492009-12-04 22:46:56 +00006457 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00006458 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
6459 NameInfo, IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00006460 }
John McCalled976492009-12-04 22:46:56 +00006461 D->setAccess(AS);
6462 CurContext->addDecl(D);
6463
6464 if (!LookupContext) return D;
6465 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00006466
John McCall77bb1aa2010-05-01 00:40:08 +00006467 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00006468 UD->setInvalidDecl();
6469 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006470 }
6471
Sebastian Redlf677ea32011-02-05 19:23:19 +00006472 // Constructor inheriting using decls get special treatment.
6473 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Sebastian Redlcaa35e42011-03-12 13:44:32 +00006474 if (CheckInheritedConstructorUsingDecl(UD))
6475 UD->setInvalidDecl();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006476 return UD;
6477 }
6478
6479 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00006480
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006481 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00006482
John McCall604e7f12009-12-08 07:46:18 +00006483 // Unlike most lookups, we don't always want to hide tag
6484 // declarations: tag names are visible through the using declaration
6485 // even if hidden by ordinary names, *except* in a dependent context
6486 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00006487 if (!IsInstantiation)
6488 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00006489
John McCalla24dc2e2009-11-17 02:14:36 +00006490 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00006491
John McCallf36e02d2009-10-09 21:13:30 +00006492 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00006493 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006494 << NameInfo.getName() << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00006495 UD->setInvalidDecl();
6496 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006497 }
6498
John McCalled976492009-12-04 22:46:56 +00006499 if (R.isAmbiguous()) {
6500 UD->setInvalidDecl();
6501 return UD;
6502 }
Mike Stump1eb44332009-09-09 15:08:12 +00006503
John McCall7ba107a2009-11-18 02:36:19 +00006504 if (IsTypeName) {
6505 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00006506 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00006507 Diag(IdentLoc, diag::err_using_typename_non_type);
6508 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
6509 Diag((*I)->getUnderlyingDecl()->getLocation(),
6510 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006511 UD->setInvalidDecl();
6512 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00006513 }
6514 } else {
6515 // If we asked for a non-typename and we got a type, error out,
6516 // but only if this is an instantiation of an unresolved using
6517 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00006518 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00006519 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
6520 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006521 UD->setInvalidDecl();
6522 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00006523 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006524 }
6525
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006526 // C++0x N2914 [namespace.udecl]p6:
6527 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00006528 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006529 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
6530 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00006531 UD->setInvalidDecl();
6532 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006533 }
Mike Stump1eb44332009-09-09 15:08:12 +00006534
John McCall9f54ad42009-12-10 09:41:52 +00006535 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
6536 if (!CheckUsingShadowDecl(UD, *I, Previous))
6537 BuildUsingShadowDecl(S, UD, *I);
6538 }
John McCall9488ea12009-11-17 05:59:44 +00006539
6540 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006541}
6542
Sebastian Redlf677ea32011-02-05 19:23:19 +00006543/// Additional checks for a using declaration referring to a constructor name.
6544bool Sema::CheckInheritedConstructorUsingDecl(UsingDecl *UD) {
6545 if (UD->isTypeName()) {
6546 // FIXME: Cannot specify typename when specifying constructor
6547 return true;
6548 }
6549
Douglas Gregordc355712011-02-25 00:36:19 +00006550 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006551 assert(SourceType &&
6552 "Using decl naming constructor doesn't have type in scope spec.");
6553 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
6554
6555 // Check whether the named type is a direct base class.
6556 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
6557 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
6558 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
6559 BaseIt != BaseE; ++BaseIt) {
6560 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
6561 if (CanonicalSourceType == BaseType)
6562 break;
6563 }
6564
6565 if (BaseIt == BaseE) {
6566 // Did not find SourceType in the bases.
6567 Diag(UD->getUsingLocation(),
6568 diag::err_using_decl_constructor_not_in_direct_base)
6569 << UD->getNameInfo().getSourceRange()
6570 << QualType(SourceType, 0) << TargetClass;
6571 return true;
6572 }
6573
6574 BaseIt->setInheritConstructors();
6575
6576 return false;
6577}
6578
John McCall9f54ad42009-12-10 09:41:52 +00006579/// Checks that the given using declaration is not an invalid
6580/// redeclaration. Note that this is checking only for the using decl
6581/// itself, not for any ill-formedness among the UsingShadowDecls.
6582bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
6583 bool isTypeName,
6584 const CXXScopeSpec &SS,
6585 SourceLocation NameLoc,
6586 const LookupResult &Prev) {
6587 // C++03 [namespace.udecl]p8:
6588 // C++0x [namespace.udecl]p10:
6589 // A using-declaration is a declaration and can therefore be used
6590 // repeatedly where (and only where) multiple declarations are
6591 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00006592 //
John McCall8a726212010-11-29 18:01:58 +00006593 // That's in non-member contexts.
6594 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00006595 return false;
6596
6597 NestedNameSpecifier *Qual
6598 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
6599
6600 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
6601 NamedDecl *D = *I;
6602
6603 bool DTypename;
6604 NestedNameSpecifier *DQual;
6605 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
6606 DTypename = UD->isTypeName();
Douglas Gregordc355712011-02-25 00:36:19 +00006607 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006608 } else if (UnresolvedUsingValueDecl *UD
6609 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
6610 DTypename = false;
Douglas Gregordc355712011-02-25 00:36:19 +00006611 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006612 } else if (UnresolvedUsingTypenameDecl *UD
6613 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
6614 DTypename = true;
Douglas Gregordc355712011-02-25 00:36:19 +00006615 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006616 } else continue;
6617
6618 // using decls differ if one says 'typename' and the other doesn't.
6619 // FIXME: non-dependent using decls?
6620 if (isTypeName != DTypename) continue;
6621
6622 // using decls differ if they name different scopes (but note that
6623 // template instantiation can cause this check to trigger when it
6624 // didn't before instantiation).
6625 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
6626 Context.getCanonicalNestedNameSpecifier(DQual))
6627 continue;
6628
6629 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00006630 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00006631 return true;
6632 }
6633
6634 return false;
6635}
6636
John McCall604e7f12009-12-08 07:46:18 +00006637
John McCalled976492009-12-04 22:46:56 +00006638/// Checks that the given nested-name qualifier used in a using decl
6639/// in the current context is appropriately related to the current
6640/// scope. If an error is found, diagnoses it and returns true.
6641bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
6642 const CXXScopeSpec &SS,
6643 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00006644 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00006645
John McCall604e7f12009-12-08 07:46:18 +00006646 if (!CurContext->isRecord()) {
6647 // C++03 [namespace.udecl]p3:
6648 // C++0x [namespace.udecl]p8:
6649 // A using-declaration for a class member shall be a member-declaration.
6650
6651 // If we weren't able to compute a valid scope, it must be a
6652 // dependent class scope.
6653 if (!NamedContext || NamedContext->isRecord()) {
6654 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
6655 << SS.getRange();
6656 return true;
6657 }
6658
6659 // Otherwise, everything is known to be fine.
6660 return false;
6661 }
6662
6663 // The current scope is a record.
6664
6665 // If the named context is dependent, we can't decide much.
6666 if (!NamedContext) {
6667 // FIXME: in C++0x, we can diagnose if we can prove that the
6668 // nested-name-specifier does not refer to a base class, which is
6669 // still possible in some cases.
6670
6671 // Otherwise we have to conservatively report that things might be
6672 // okay.
6673 return false;
6674 }
6675
6676 if (!NamedContext->isRecord()) {
6677 // Ideally this would point at the last name in the specifier,
6678 // but we don't have that level of source info.
6679 Diag(SS.getRange().getBegin(),
6680 diag::err_using_decl_nested_name_specifier_is_not_class)
6681 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
6682 return true;
6683 }
6684
Douglas Gregor6fb07292010-12-21 07:41:49 +00006685 if (!NamedContext->isDependentContext() &&
6686 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
6687 return true;
6688
John McCall604e7f12009-12-08 07:46:18 +00006689 if (getLangOptions().CPlusPlus0x) {
6690 // C++0x [namespace.udecl]p3:
6691 // In a using-declaration used as a member-declaration, the
6692 // nested-name-specifier shall name a base class of the class
6693 // being defined.
6694
6695 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
6696 cast<CXXRecordDecl>(NamedContext))) {
6697 if (CurContext == NamedContext) {
6698 Diag(NameLoc,
6699 diag::err_using_decl_nested_name_specifier_is_current_class)
6700 << SS.getRange();
6701 return true;
6702 }
6703
6704 Diag(SS.getRange().getBegin(),
6705 diag::err_using_decl_nested_name_specifier_is_not_base_class)
6706 << (NestedNameSpecifier*) SS.getScopeRep()
6707 << cast<CXXRecordDecl>(CurContext)
6708 << SS.getRange();
6709 return true;
6710 }
6711
6712 return false;
6713 }
6714
6715 // C++03 [namespace.udecl]p4:
6716 // A using-declaration used as a member-declaration shall refer
6717 // to a member of a base class of the class being defined [etc.].
6718
6719 // Salient point: SS doesn't have to name a base class as long as
6720 // lookup only finds members from base classes. Therefore we can
6721 // diagnose here only if we can prove that that can't happen,
6722 // i.e. if the class hierarchies provably don't intersect.
6723
6724 // TODO: it would be nice if "definitely valid" results were cached
6725 // in the UsingDecl and UsingShadowDecl so that these checks didn't
6726 // need to be repeated.
6727
6728 struct UserData {
6729 llvm::DenseSet<const CXXRecordDecl*> Bases;
6730
6731 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
6732 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6733 Data->Bases.insert(Base);
6734 return true;
6735 }
6736
6737 bool hasDependentBases(const CXXRecordDecl *Class) {
6738 return !Class->forallBases(collect, this);
6739 }
6740
6741 /// Returns true if the base is dependent or is one of the
6742 /// accumulated base classes.
6743 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
6744 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6745 return !Data->Bases.count(Base);
6746 }
6747
6748 bool mightShareBases(const CXXRecordDecl *Class) {
6749 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
6750 }
6751 };
6752
6753 UserData Data;
6754
6755 // Returns false if we find a dependent base.
6756 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
6757 return false;
6758
6759 // Returns false if the class has a dependent base or if it or one
6760 // of its bases is present in the base set of the current context.
6761 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
6762 return false;
6763
6764 Diag(SS.getRange().getBegin(),
6765 diag::err_using_decl_nested_name_specifier_is_not_base_class)
6766 << (NestedNameSpecifier*) SS.getScopeRep()
6767 << cast<CXXRecordDecl>(CurContext)
6768 << SS.getRange();
6769
6770 return true;
John McCalled976492009-12-04 22:46:56 +00006771}
6772
Richard Smith162e1c12011-04-15 14:24:37 +00006773Decl *Sema::ActOnAliasDeclaration(Scope *S,
6774 AccessSpecifier AS,
Richard Smith3e4c6c42011-05-05 21:57:07 +00006775 MultiTemplateParamsArg TemplateParamLists,
Richard Smith162e1c12011-04-15 14:24:37 +00006776 SourceLocation UsingLoc,
6777 UnqualifiedId &Name,
6778 TypeResult Type) {
Richard Smith3e4c6c42011-05-05 21:57:07 +00006779 // Skip up to the relevant declaration scope.
6780 while (S->getFlags() & Scope::TemplateParamScope)
6781 S = S->getParent();
Richard Smith162e1c12011-04-15 14:24:37 +00006782 assert((S->getFlags() & Scope::DeclScope) &&
6783 "got alias-declaration outside of declaration scope");
6784
6785 if (Type.isInvalid())
6786 return 0;
6787
6788 bool Invalid = false;
6789 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
6790 TypeSourceInfo *TInfo = 0;
Nick Lewyckyb79bf1d2011-05-02 01:07:19 +00006791 GetTypeFromParser(Type.get(), &TInfo);
Richard Smith162e1c12011-04-15 14:24:37 +00006792
6793 if (DiagnoseClassNameShadow(CurContext, NameInfo))
6794 return 0;
6795
6796 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3e4c6c42011-05-05 21:57:07 +00006797 UPPC_DeclarationType)) {
Richard Smith162e1c12011-04-15 14:24:37 +00006798 Invalid = true;
Richard Smith3e4c6c42011-05-05 21:57:07 +00006799 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
6800 TInfo->getTypeLoc().getBeginLoc());
6801 }
Richard Smith162e1c12011-04-15 14:24:37 +00006802
6803 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
6804 LookupName(Previous, S);
6805
6806 // Warn about shadowing the name of a template parameter.
6807 if (Previous.isSingleResult() &&
6808 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorcb8f9512011-10-20 17:58:49 +00006809 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smith162e1c12011-04-15 14:24:37 +00006810 Previous.clear();
6811 }
6812
6813 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
6814 "name in alias declaration must be an identifier");
6815 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
6816 Name.StartLocation,
6817 Name.Identifier, TInfo);
6818
6819 NewTD->setAccess(AS);
6820
6821 if (Invalid)
6822 NewTD->setInvalidDecl();
6823
Richard Smith3e4c6c42011-05-05 21:57:07 +00006824 CheckTypedefForVariablyModifiedType(S, NewTD);
6825 Invalid |= NewTD->isInvalidDecl();
6826
Richard Smith162e1c12011-04-15 14:24:37 +00006827 bool Redeclaration = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00006828
6829 NamedDecl *NewND;
6830 if (TemplateParamLists.size()) {
6831 TypeAliasTemplateDecl *OldDecl = 0;
6832 TemplateParameterList *OldTemplateParams = 0;
6833
6834 if (TemplateParamLists.size() != 1) {
6835 Diag(UsingLoc, diag::err_alias_template_extra_headers)
6836 << SourceRange(TemplateParamLists.get()[1]->getTemplateLoc(),
6837 TemplateParamLists.get()[TemplateParamLists.size()-1]->getRAngleLoc());
6838 }
6839 TemplateParameterList *TemplateParams = TemplateParamLists.get()[0];
6840
6841 // Only consider previous declarations in the same scope.
6842 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
6843 /*ExplicitInstantiationOrSpecialization*/false);
6844 if (!Previous.empty()) {
6845 Redeclaration = true;
6846
6847 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
6848 if (!OldDecl && !Invalid) {
6849 Diag(UsingLoc, diag::err_redefinition_different_kind)
6850 << Name.Identifier;
6851
6852 NamedDecl *OldD = Previous.getRepresentativeDecl();
6853 if (OldD->getLocation().isValid())
6854 Diag(OldD->getLocation(), diag::note_previous_definition);
6855
6856 Invalid = true;
6857 }
6858
6859 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
6860 if (TemplateParameterListsAreEqual(TemplateParams,
6861 OldDecl->getTemplateParameters(),
6862 /*Complain=*/true,
6863 TPL_TemplateMatch))
6864 OldTemplateParams = OldDecl->getTemplateParameters();
6865 else
6866 Invalid = true;
6867
6868 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
6869 if (!Invalid &&
6870 !Context.hasSameType(OldTD->getUnderlyingType(),
6871 NewTD->getUnderlyingType())) {
6872 // FIXME: The C++0x standard does not clearly say this is ill-formed,
6873 // but we can't reasonably accept it.
6874 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
6875 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
6876 if (OldTD->getLocation().isValid())
6877 Diag(OldTD->getLocation(), diag::note_previous_definition);
6878 Invalid = true;
6879 }
6880 }
6881 }
6882
6883 // Merge any previous default template arguments into our parameters,
6884 // and check the parameter list.
6885 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
6886 TPC_TypeAliasTemplate))
6887 return 0;
6888
6889 TypeAliasTemplateDecl *NewDecl =
6890 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
6891 Name.Identifier, TemplateParams,
6892 NewTD);
6893
6894 NewDecl->setAccess(AS);
6895
6896 if (Invalid)
6897 NewDecl->setInvalidDecl();
6898 else if (OldDecl)
6899 NewDecl->setPreviousDeclaration(OldDecl);
6900
6901 NewND = NewDecl;
6902 } else {
6903 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
6904 NewND = NewTD;
6905 }
Richard Smith162e1c12011-04-15 14:24:37 +00006906
6907 if (!Redeclaration)
Richard Smith3e4c6c42011-05-05 21:57:07 +00006908 PushOnScopeChains(NewND, S);
Richard Smith162e1c12011-04-15 14:24:37 +00006909
Richard Smith3e4c6c42011-05-05 21:57:07 +00006910 return NewND;
Richard Smith162e1c12011-04-15 14:24:37 +00006911}
6912
John McCalld226f652010-08-21 09:40:31 +00006913Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00006914 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006915 SourceLocation AliasLoc,
6916 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006917 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00006918 SourceLocation IdentLoc,
6919 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00006920
Anders Carlsson81c85c42009-03-28 23:53:49 +00006921 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00006922 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
6923 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00006924
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006925 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00006926 NamedDecl *PrevDecl
6927 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
6928 ForRedeclaration);
6929 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
6930 PrevDecl = 0;
6931
6932 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00006933 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00006934 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00006935 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00006936 // FIXME: At some point, we'll want to create the (redundant)
6937 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00006938 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00006939 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00006940 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00006941 }
Mike Stump1eb44332009-09-09 15:08:12 +00006942
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006943 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
6944 diag::err_redefinition_different_kind;
6945 Diag(AliasLoc, DiagID) << Alias;
6946 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00006947 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006948 }
6949
John McCalla24dc2e2009-11-17 02:14:36 +00006950 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00006951 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00006952
John McCallf36e02d2009-10-09 21:13:30 +00006953 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006954 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00006955 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00006956 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00006957 }
Anders Carlsson5721c682009-03-28 06:42:02 +00006958 }
Mike Stump1eb44332009-09-09 15:08:12 +00006959
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00006960 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00006961 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00006962 Alias, SS.getWithLocInContext(Context),
John McCallf36e02d2009-10-09 21:13:30 +00006963 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00006964
John McCall3dbd3d52010-02-16 06:53:13 +00006965 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00006966 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00006967}
6968
Douglas Gregor39957dc2010-05-01 15:04:51 +00006969namespace {
6970 /// \brief Scoped object used to handle the state changes required in Sema
6971 /// to implicitly define the body of a C++ member function;
6972 class ImplicitlyDefinedFunctionScope {
6973 Sema &S;
John McCalleee1d542011-02-14 07:13:47 +00006974 Sema::ContextRAII SavedContext;
Douglas Gregor39957dc2010-05-01 15:04:51 +00006975
6976 public:
6977 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
John McCalleee1d542011-02-14 07:13:47 +00006978 : S(S), SavedContext(S, Method)
Douglas Gregor39957dc2010-05-01 15:04:51 +00006979 {
Douglas Gregor39957dc2010-05-01 15:04:51 +00006980 S.PushFunctionScope();
6981 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
6982 }
6983
6984 ~ImplicitlyDefinedFunctionScope() {
6985 S.PopExpressionEvaluationContext();
Eli Friedmanec9ea722012-01-05 03:35:19 +00006986 S.PopFunctionScopeInfo();
Douglas Gregor39957dc2010-05-01 15:04:51 +00006987 }
6988 };
6989}
6990
Sean Hunt001cad92011-05-10 00:49:42 +00006991Sema::ImplicitExceptionSpecification
6992Sema::ComputeDefaultedDefaultCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006993 // C++ [except.spec]p14:
6994 // An implicitly declared special member function (Clause 12) shall have an
6995 // exception-specification. [...]
6996 ImplicitExceptionSpecification ExceptSpec(Context);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00006997 if (ClassDecl->isInvalidDecl())
6998 return ExceptSpec;
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006999
Sebastian Redl60618fa2011-03-12 11:50:43 +00007000 // Direct base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007001 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7002 BEnd = ClassDecl->bases_end();
7003 B != BEnd; ++B) {
7004 if (B->isVirtual()) // Handled below.
7005 continue;
7006
Douglas Gregor18274032010-07-03 00:47:00 +00007007 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7008 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007009 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7010 // If this is a deleted function, add it anyway. This might be conformant
7011 // with the standard. This might not. I'm not sure. It might not matter.
7012 if (Constructor)
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007013 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007014 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007015 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007016
7017 // Virtual base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007018 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7019 BEnd = ClassDecl->vbases_end();
7020 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00007021 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7022 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007023 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7024 // If this is a deleted function, add it anyway. This might be conformant
7025 // with the standard. This might not. I'm not sure. It might not matter.
7026 if (Constructor)
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007027 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007028 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007029 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007030
7031 // Field constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007032 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7033 FEnd = ClassDecl->field_end();
7034 F != FEnd; ++F) {
Richard Smith7a614d82011-06-11 17:19:42 +00007035 if (F->hasInClassInitializer()) {
7036 if (Expr *E = F->getInClassInitializer())
7037 ExceptSpec.CalledExpr(E);
7038 else if (!F->isInvalidDecl())
7039 ExceptSpec.SetDelayed();
7040 } else if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00007041 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Sean Huntb320e0c2011-06-10 03:50:41 +00007042 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7043 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7044 // If this is a deleted function, add it anyway. This might be conformant
7045 // with the standard. This might not. I'm not sure. It might not matter.
7046 // In particular, the problem is that this function never gets called. It
7047 // might just be ill-formed because this function attempts to refer to
7048 // a deleted function here.
7049 if (Constructor)
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007050 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007051 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007052 }
John McCalle23cf432010-12-14 08:05:40 +00007053
Sean Hunt001cad92011-05-10 00:49:42 +00007054 return ExceptSpec;
7055}
7056
7057CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
7058 CXXRecordDecl *ClassDecl) {
7059 // C++ [class.ctor]p5:
7060 // A default constructor for a class X is a constructor of class X
7061 // that can be called without an argument. If there is no
7062 // user-declared constructor for class X, a default constructor is
7063 // implicitly declared. An implicitly-declared default constructor
7064 // is an inline public member of its class.
7065 assert(!ClassDecl->hasUserDeclaredConstructor() &&
7066 "Should not build implicit default constructor!");
7067
7068 ImplicitExceptionSpecification Spec =
7069 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
7070 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Sebastian Redl8b5b4092011-03-06 10:52:04 +00007071
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007072 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00007073 CanQualType ClassType
7074 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007075 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007076 DeclarationName Name
7077 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007078 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith61802452011-12-22 02:22:31 +00007079 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
7080 Context, ClassDecl, ClassLoc, NameInfo,
7081 Context.getFunctionType(Context.VoidTy, 0, 0, EPI), /*TInfo=*/0,
7082 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
7083 /*isConstexpr=*/ClassDecl->defaultedDefaultConstructorIsConstexpr() &&
7084 getLangOptions().CPlusPlus0x);
Douglas Gregor32df23e2010-07-01 22:02:46 +00007085 DefaultCon->setAccess(AS_public);
Sean Hunt1e238652011-05-12 03:51:51 +00007086 DefaultCon->setDefaulted();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007087 DefaultCon->setImplicit();
Sean Hunt023df372011-05-09 18:22:59 +00007088 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
Douglas Gregor18274032010-07-03 00:47:00 +00007089
7090 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00007091 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
7092
Douglas Gregor23c94db2010-07-02 17:43:08 +00007093 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00007094 PushOnScopeChains(DefaultCon, S, false);
7095 ClassDecl->addDecl(DefaultCon);
Sean Hunt71a682f2011-05-18 03:41:58 +00007096
Sean Hunte16da072011-10-10 06:18:57 +00007097 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Sean Hunt71a682f2011-05-18 03:41:58 +00007098 DefaultCon->setDeletedAsWritten();
Douglas Gregor18274032010-07-03 00:47:00 +00007099
Douglas Gregor32df23e2010-07-01 22:02:46 +00007100 return DefaultCon;
7101}
7102
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007103void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
7104 CXXConstructorDecl *Constructor) {
Sean Hunt1e238652011-05-12 03:51:51 +00007105 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00007106 !Constructor->doesThisDeclarationHaveABody() &&
7107 !Constructor->isDeleted()) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00007108 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00007109
Anders Carlssonf6513ed2010-04-23 16:04:08 +00007110 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00007111 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00007112
Douglas Gregor39957dc2010-05-01 15:04:51 +00007113 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007114 DiagnosticErrorTrap Trap(Diags);
Sean Huntcbb67482011-01-08 20:30:50 +00007115 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007116 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00007117 Diag(CurrentLocation, diag::note_member_synthesized_at)
Sean Huntf961ea52011-05-10 19:08:14 +00007118 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00007119 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007120 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00007121 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007122
7123 SourceLocation Loc = Constructor->getLocation();
7124 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
7125
7126 Constructor->setUsed();
7127 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007128
7129 if (ASTMutationListener *L = getASTMutationListener()) {
7130 L->CompletedImplicitDefinition(Constructor);
7131 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007132}
7133
Richard Smith7a614d82011-06-11 17:19:42 +00007134/// Get any existing defaulted default constructor for the given class. Do not
7135/// implicitly define one if it does not exist.
7136static CXXConstructorDecl *getDefaultedDefaultConstructorUnsafe(Sema &Self,
7137 CXXRecordDecl *D) {
7138 ASTContext &Context = Self.Context;
7139 QualType ClassType = Context.getTypeDeclType(D);
7140 DeclarationName ConstructorName
7141 = Context.DeclarationNames.getCXXConstructorName(
7142 Context.getCanonicalType(ClassType.getUnqualifiedType()));
7143
7144 DeclContext::lookup_const_iterator Con, ConEnd;
7145 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
7146 Con != ConEnd; ++Con) {
7147 // A function template cannot be defaulted.
7148 if (isa<FunctionTemplateDecl>(*Con))
7149 continue;
7150
7151 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
7152 if (Constructor->isDefaultConstructor())
7153 return Constructor->isDefaulted() ? Constructor : 0;
7154 }
7155 return 0;
7156}
7157
7158void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
7159 if (!D) return;
7160 AdjustDeclIfTemplate(D);
7161
7162 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D);
7163 CXXConstructorDecl *CtorDecl
7164 = getDefaultedDefaultConstructorUnsafe(*this, ClassDecl);
7165
7166 if (!CtorDecl) return;
7167
7168 // Compute the exception specification for the default constructor.
7169 const FunctionProtoType *CtorTy =
7170 CtorDecl->getType()->castAs<FunctionProtoType>();
7171 if (CtorTy->getExceptionSpecType() == EST_Delayed) {
7172 ImplicitExceptionSpecification Spec =
7173 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
7174 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
7175 assert(EPI.ExceptionSpecType != EST_Delayed);
7176
7177 CtorDecl->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
7178 }
7179
7180 // If the default constructor is explicitly defaulted, checking the exception
7181 // specification is deferred until now.
7182 if (!CtorDecl->isInvalidDecl() && CtorDecl->isExplicitlyDefaulted() &&
7183 !ClassDecl->isDependentType())
7184 CheckExplicitlyDefaultedDefaultConstructor(CtorDecl);
7185}
7186
Sebastian Redlf677ea32011-02-05 19:23:19 +00007187void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
7188 // We start with an initial pass over the base classes to collect those that
7189 // inherit constructors from. If there are none, we can forgo all further
7190 // processing.
Chris Lattner5f9e2722011-07-23 10:55:15 +00007191 typedef SmallVector<const RecordType *, 4> BasesVector;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007192 BasesVector BasesToInheritFrom;
7193 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
7194 BaseE = ClassDecl->bases_end();
7195 BaseIt != BaseE; ++BaseIt) {
7196 if (BaseIt->getInheritConstructors()) {
7197 QualType Base = BaseIt->getType();
7198 if (Base->isDependentType()) {
7199 // If we inherit constructors from anything that is dependent, just
7200 // abort processing altogether. We'll get another chance for the
7201 // instantiations.
7202 return;
7203 }
7204 BasesToInheritFrom.push_back(Base->castAs<RecordType>());
7205 }
7206 }
7207 if (BasesToInheritFrom.empty())
7208 return;
7209
7210 // Now collect the constructors that we already have in the current class.
7211 // Those take precedence over inherited constructors.
7212 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
7213 // unless there is a user-declared constructor with the same signature in
7214 // the class where the using-declaration appears.
7215 llvm::SmallSet<const Type *, 8> ExistingConstructors;
7216 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
7217 CtorE = ClassDecl->ctor_end();
7218 CtorIt != CtorE; ++CtorIt) {
7219 ExistingConstructors.insert(
7220 Context.getCanonicalType(CtorIt->getType()).getTypePtr());
7221 }
7222
7223 Scope *S = getScopeForContext(ClassDecl);
7224 DeclarationName CreatedCtorName =
7225 Context.DeclarationNames.getCXXConstructorName(
7226 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
7227
7228 // Now comes the true work.
7229 // First, we keep a map from constructor types to the base that introduced
7230 // them. Needed for finding conflicting constructors. We also keep the
7231 // actually inserted declarations in there, for pretty diagnostics.
7232 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
7233 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
7234 ConstructorToSourceMap InheritedConstructors;
7235 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
7236 BaseE = BasesToInheritFrom.end();
7237 BaseIt != BaseE; ++BaseIt) {
7238 const RecordType *Base = *BaseIt;
7239 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
7240 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
7241 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
7242 CtorE = BaseDecl->ctor_end();
7243 CtorIt != CtorE; ++CtorIt) {
7244 // Find the using declaration for inheriting this base's constructors.
7245 DeclarationName Name =
7246 Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
7247 UsingDecl *UD = dyn_cast_or_null<UsingDecl>(
7248 LookupSingleName(S, Name,SourceLocation(), LookupUsingDeclName));
7249 SourceLocation UsingLoc = UD ? UD->getLocation() :
7250 ClassDecl->getLocation();
7251
7252 // C++0x [class.inhctor]p1: The candidate set of inherited constructors
7253 // from the class X named in the using-declaration consists of actual
7254 // constructors and notional constructors that result from the
7255 // transformation of defaulted parameters as follows:
7256 // - all non-template default constructors of X, and
7257 // - for each non-template constructor of X that has at least one
7258 // parameter with a default argument, the set of constructors that
7259 // results from omitting any ellipsis parameter specification and
7260 // successively omitting parameters with a default argument from the
7261 // end of the parameter-type-list.
7262 CXXConstructorDecl *BaseCtor = *CtorIt;
7263 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
7264 const FunctionProtoType *BaseCtorType =
7265 BaseCtor->getType()->getAs<FunctionProtoType>();
7266
7267 for (unsigned params = BaseCtor->getMinRequiredArguments(),
7268 maxParams = BaseCtor->getNumParams();
7269 params <= maxParams; ++params) {
7270 // Skip default constructors. They're never inherited.
7271 if (params == 0)
7272 continue;
7273 // Skip copy and move constructors for the same reason.
7274 if (CanBeCopyOrMove && params == 1)
7275 continue;
7276
7277 // Build up a function type for this particular constructor.
7278 // FIXME: The working paper does not consider that the exception spec
7279 // for the inheriting constructor might be larger than that of the
Richard Smith7a614d82011-06-11 17:19:42 +00007280 // source. This code doesn't yet, either. When it does, this code will
7281 // need to be delayed until after exception specifications and in-class
7282 // member initializers are attached.
Sebastian Redlf677ea32011-02-05 19:23:19 +00007283 const Type *NewCtorType;
7284 if (params == maxParams)
7285 NewCtorType = BaseCtorType;
7286 else {
Chris Lattner5f9e2722011-07-23 10:55:15 +00007287 SmallVector<QualType, 16> Args;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007288 for (unsigned i = 0; i < params; ++i) {
7289 Args.push_back(BaseCtorType->getArgType(i));
7290 }
7291 FunctionProtoType::ExtProtoInfo ExtInfo =
7292 BaseCtorType->getExtProtoInfo();
7293 ExtInfo.Variadic = false;
7294 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
7295 Args.data(), params, ExtInfo)
7296 .getTypePtr();
7297 }
7298 const Type *CanonicalNewCtorType =
7299 Context.getCanonicalType(NewCtorType);
7300
7301 // Now that we have the type, first check if the class already has a
7302 // constructor with this signature.
7303 if (ExistingConstructors.count(CanonicalNewCtorType))
7304 continue;
7305
7306 // Then we check if we have already declared an inherited constructor
7307 // with this signature.
7308 std::pair<ConstructorToSourceMap::iterator, bool> result =
7309 InheritedConstructors.insert(std::make_pair(
7310 CanonicalNewCtorType,
7311 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
7312 if (!result.second) {
7313 // Already in the map. If it came from a different class, that's an
7314 // error. Not if it's from the same.
7315 CanQualType PreviousBase = result.first->second.first;
7316 if (CanonicalBase != PreviousBase) {
7317 const CXXConstructorDecl *PrevCtor = result.first->second.second;
7318 const CXXConstructorDecl *PrevBaseCtor =
7319 PrevCtor->getInheritedConstructor();
7320 assert(PrevBaseCtor && "Conflicting constructor was not inherited");
7321
7322 Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
7323 Diag(BaseCtor->getLocation(),
7324 diag::note_using_decl_constructor_conflict_current_ctor);
7325 Diag(PrevBaseCtor->getLocation(),
7326 diag::note_using_decl_constructor_conflict_previous_ctor);
7327 Diag(PrevCtor->getLocation(),
7328 diag::note_using_decl_constructor_conflict_previous_using);
7329 }
7330 continue;
7331 }
7332
7333 // OK, we're there, now add the constructor.
7334 // C++0x [class.inhctor]p8: [...] that would be performed by a
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007335 // user-written inline constructor [...]
Sebastian Redlf677ea32011-02-05 19:23:19 +00007336 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
7337 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007338 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
7339 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007340 /*ImplicitlyDeclared=*/true,
7341 // FIXME: Due to a defect in the standard, we treat inherited
7342 // constructors as constexpr even if that makes them ill-formed.
7343 /*Constexpr=*/BaseCtor->isConstexpr());
Sebastian Redlf677ea32011-02-05 19:23:19 +00007344 NewCtor->setAccess(BaseCtor->getAccess());
7345
7346 // Build up the parameter decls and add them.
Chris Lattner5f9e2722011-07-23 10:55:15 +00007347 SmallVector<ParmVarDecl *, 16> ParamDecls;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007348 for (unsigned i = 0; i < params; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007349 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
7350 UsingLoc, UsingLoc,
Sebastian Redlf677ea32011-02-05 19:23:19 +00007351 /*IdentifierInfo=*/0,
7352 BaseCtorType->getArgType(i),
7353 /*TInfo=*/0, SC_None,
7354 SC_None, /*DefaultArg=*/0));
7355 }
David Blaikie4278c652011-09-21 18:16:56 +00007356 NewCtor->setParams(ParamDecls);
Sebastian Redlf677ea32011-02-05 19:23:19 +00007357 NewCtor->setInheritedConstructor(BaseCtor);
7358
7359 PushOnScopeChains(NewCtor, S, false);
7360 ClassDecl->addDecl(NewCtor);
7361 result.first->second.second = NewCtor;
7362 }
7363 }
7364 }
7365}
7366
Sean Huntcb45a0f2011-05-12 22:46:25 +00007367Sema::ImplicitExceptionSpecification
7368Sema::ComputeDefaultedDtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007369 // C++ [except.spec]p14:
7370 // An implicitly declared special member function (Clause 12) shall have
7371 // an exception-specification.
7372 ImplicitExceptionSpecification ExceptSpec(Context);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007373 if (ClassDecl->isInvalidDecl())
7374 return ExceptSpec;
7375
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007376 // Direct base-class destructors.
7377 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7378 BEnd = ClassDecl->bases_end();
7379 B != BEnd; ++B) {
7380 if (B->isVirtual()) // Handled below.
7381 continue;
7382
7383 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
7384 ExceptSpec.CalledDecl(
Sebastian Redl0ee33912011-05-19 05:13:44 +00007385 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007386 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00007387
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007388 // Virtual base-class destructors.
7389 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7390 BEnd = ClassDecl->vbases_end();
7391 B != BEnd; ++B) {
7392 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
7393 ExceptSpec.CalledDecl(
Sebastian Redl0ee33912011-05-19 05:13:44 +00007394 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007395 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00007396
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007397 // Field destructors.
7398 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7399 FEnd = ClassDecl->field_end();
7400 F != FEnd; ++F) {
7401 if (const RecordType *RecordTy
7402 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
7403 ExceptSpec.CalledDecl(
Sebastian Redl0ee33912011-05-19 05:13:44 +00007404 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007405 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007406
Sean Huntcb45a0f2011-05-12 22:46:25 +00007407 return ExceptSpec;
7408}
7409
7410CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
7411 // C++ [class.dtor]p2:
7412 // If a class has no user-declared destructor, a destructor is
7413 // declared implicitly. An implicitly-declared destructor is an
7414 // inline public member of its class.
7415
7416 ImplicitExceptionSpecification Spec =
Sebastian Redl0ee33912011-05-19 05:13:44 +00007417 ComputeDefaultedDtorExceptionSpec(ClassDecl);
Sean Huntcb45a0f2011-05-12 22:46:25 +00007418 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
7419
Douglas Gregor4923aa22010-07-02 20:37:36 +00007420 // Create the actual destructor declaration.
John McCalle23cf432010-12-14 08:05:40 +00007421 QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Sebastian Redl60618fa2011-03-12 11:50:43 +00007422
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007423 CanQualType ClassType
7424 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007425 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007426 DeclarationName Name
7427 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007428 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007429 CXXDestructorDecl *Destructor
Sebastian Redl60618fa2011-03-12 11:50:43 +00007430 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, Ty, 0,
7431 /*isInline=*/true,
7432 /*isImplicitlyDeclared=*/true);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007433 Destructor->setAccess(AS_public);
Sean Huntcb45a0f2011-05-12 22:46:25 +00007434 Destructor->setDefaulted();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007435 Destructor->setImplicit();
7436 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor4923aa22010-07-02 20:37:36 +00007437
7438 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00007439 ++ASTContext::NumImplicitDestructorsDeclared;
7440
7441 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00007442 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00007443 PushOnScopeChains(Destructor, S, false);
7444 ClassDecl->addDecl(Destructor);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007445
7446 // This could be uniqued if it ever proves significant.
7447 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
Sean Huntcb45a0f2011-05-12 22:46:25 +00007448
7449 if (ShouldDeleteDestructor(Destructor))
7450 Destructor->setDeletedAsWritten();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007451
7452 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor4923aa22010-07-02 20:37:36 +00007453
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007454 return Destructor;
7455}
7456
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007457void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00007458 CXXDestructorDecl *Destructor) {
Sean Huntcd10dec2011-05-23 23:14:04 +00007459 assert((Destructor->isDefaulted() &&
7460 !Destructor->doesThisDeclarationHaveABody()) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007461 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00007462 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007463 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007464
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007465 if (Destructor->isInvalidDecl())
7466 return;
7467
Douglas Gregor39957dc2010-05-01 15:04:51 +00007468 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007469
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007470 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00007471 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
7472 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00007473
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007474 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00007475 Diag(CurrentLocation, diag::note_member_synthesized_at)
7476 << CXXDestructor << Context.getTagDeclType(ClassDecl);
7477
7478 Destructor->setInvalidDecl();
7479 return;
7480 }
7481
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007482 SourceLocation Loc = Destructor->getLocation();
7483 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
Douglas Gregor690b2db2011-09-22 20:32:43 +00007484 Destructor->setImplicitlyDefined(true);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007485 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007486 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007487
7488 if (ASTMutationListener *L = getASTMutationListener()) {
7489 L->CompletedImplicitDefinition(Destructor);
7490 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007491}
7492
Sebastian Redl0ee33912011-05-19 05:13:44 +00007493void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *classDecl,
7494 CXXDestructorDecl *destructor) {
7495 // C++11 [class.dtor]p3:
7496 // A declaration of a destructor that does not have an exception-
7497 // specification is implicitly considered to have the same exception-
7498 // specification as an implicit declaration.
7499 const FunctionProtoType *dtorType = destructor->getType()->
7500 getAs<FunctionProtoType>();
7501 if (dtorType->hasExceptionSpec())
7502 return;
7503
7504 ImplicitExceptionSpecification exceptSpec =
7505 ComputeDefaultedDtorExceptionSpec(classDecl);
7506
Chandler Carruth3f224b22011-09-20 04:55:26 +00007507 // Replace the destructor's type, building off the existing one. Fortunately,
7508 // the only thing of interest in the destructor type is its extended info.
7509 // The return and arguments are fixed.
7510 FunctionProtoType::ExtProtoInfo epi = dtorType->getExtProtoInfo();
Sebastian Redl0ee33912011-05-19 05:13:44 +00007511 epi.ExceptionSpecType = exceptSpec.getExceptionSpecType();
7512 epi.NumExceptions = exceptSpec.size();
7513 epi.Exceptions = exceptSpec.data();
7514 QualType ty = Context.getFunctionType(Context.VoidTy, 0, 0, epi);
7515
7516 destructor->setType(ty);
7517
7518 // FIXME: If the destructor has a body that could throw, and the newly created
7519 // spec doesn't allow exceptions, we should emit a warning, because this
7520 // change in behavior can break conforming C++03 programs at runtime.
7521 // However, we don't have a body yet, so it needs to be done somewhere else.
7522}
7523
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007524/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregor06a9f362010-05-01 20:49:11 +00007525/// \c To.
7526///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007527/// This routine is used to copy/move the members of a class with an
7528/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregor06a9f362010-05-01 20:49:11 +00007529/// copied are arrays, this routine builds for loops to copy them.
7530///
7531/// \param S The Sema object used for type-checking.
7532///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007533/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007534///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007535/// \param T The type of the expressions being copied/moved. Both expressions
7536/// must have this type.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007537///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007538/// \param To The expression we are copying/moving to.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007539///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007540/// \param From The expression we are copying/moving from.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007541///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007542/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor6cdc1612010-05-04 15:20:55 +00007543/// Otherwise, it's a non-static member subobject.
7544///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007545/// \param Copying Whether we're copying or moving.
7546///
Douglas Gregor06a9f362010-05-01 20:49:11 +00007547/// \param Depth Internal parameter recording the depth of the recursion.
7548///
7549/// \returns A statement or a loop that copies the expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00007550static StmtResult
Douglas Gregor06a9f362010-05-01 20:49:11 +00007551BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCall9ae2f072010-08-23 23:25:46 +00007552 Expr *To, Expr *From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007553 bool CopyingBaseSubobject, bool Copying,
7554 unsigned Depth = 0) {
7555 // C++0x [class.copy]p28:
Douglas Gregor06a9f362010-05-01 20:49:11 +00007556 // Each subobject is assigned in the manner appropriate to its type:
7557 //
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007558 // - if the subobject is of class type, as if by a call to operator= with
7559 // the subobject as the object expression and the corresponding
7560 // subobject of x as a single function argument (as if by explicit
7561 // qualification; that is, ignoring any possible virtual overriding
7562 // functions in more derived classes);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007563 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
7564 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7565
7566 // Look for operator=.
7567 DeclarationName Name
7568 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
7569 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
7570 S.LookupQualifiedName(OpLookup, ClassDecl, false);
7571
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007572 // Filter out any result that isn't a copy/move-assignment operator.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007573 LookupResult::Filter F = OpLookup.makeFilter();
7574 while (F.hasNext()) {
7575 NamedDecl *D = F.next();
7576 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007577 if (Copying ? Method->isCopyAssignmentOperator() :
7578 Method->isMoveAssignmentOperator())
Douglas Gregor06a9f362010-05-01 20:49:11 +00007579 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007580
Douglas Gregor06a9f362010-05-01 20:49:11 +00007581 F.erase();
John McCallb0207482010-03-16 06:11:48 +00007582 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007583 F.done();
7584
Douglas Gregor6cdc1612010-05-04 15:20:55 +00007585 // Suppress the protected check (C++ [class.protected]) for each of the
7586 // assignment operators we found. This strange dance is required when
7587 // we're assigning via a base classes's copy-assignment operator. To
7588 // ensure that we're getting the right base class subobject (without
7589 // ambiguities), we need to cast "this" to that subobject type; to
7590 // ensure that we don't go through the virtual call mechanism, we need
7591 // to qualify the operator= name with the base class (see below). However,
7592 // this means that if the base class has a protected copy assignment
7593 // operator, the protected member access check will fail. So, we
7594 // rewrite "protected" access to "public" access in this case, since we
7595 // know by construction that we're calling from a derived class.
7596 if (CopyingBaseSubobject) {
7597 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
7598 L != LEnd; ++L) {
7599 if (L.getAccess() == AS_protected)
7600 L.setAccess(AS_public);
7601 }
7602 }
7603
Douglas Gregor06a9f362010-05-01 20:49:11 +00007604 // Create the nested-name-specifier that will be used to qualify the
7605 // reference to operator=; this is required to suppress the virtual
7606 // call mechanism.
7607 CXXScopeSpec SS;
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00007608 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Douglas Gregorc34348a2011-02-24 17:54:50 +00007609 SS.MakeTrivial(S.Context,
7610 NestedNameSpecifier::Create(S.Context, 0, false,
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00007611 CanonicalT),
Douglas Gregorc34348a2011-02-24 17:54:50 +00007612 Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007613
7614 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00007615 ExprResult OpEqualRef
John McCall9ae2f072010-08-23 23:25:46 +00007616 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00007617 /*TemplateKWLoc=*/SourceLocation(),
7618 /*FirstQualifierInScope=*/0,
7619 OpLookup,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007620 /*TemplateArgs=*/0,
7621 /*SuppressQualifierCheck=*/true);
7622 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007623 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007624
7625 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00007626
John McCall60d7b3a2010-08-24 06:29:42 +00007627 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00007628 OpEqualRef.takeAs<Expr>(),
7629 Loc, &From, 1, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007630 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007631 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007632
7633 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007634 }
John McCallb0207482010-03-16 06:11:48 +00007635
Douglas Gregor06a9f362010-05-01 20:49:11 +00007636 // - if the subobject is of scalar type, the built-in assignment
7637 // operator is used.
7638 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
7639 if (!ArrayTy) {
John McCall2de56d12010-08-25 11:45:40 +00007640 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007641 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007642 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007643
7644 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007645 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007646
7647 // - if the subobject is an array, each element is assigned, in the
7648 // manner appropriate to the element type;
7649
7650 // Construct a loop over the array bounds, e.g.,
7651 //
7652 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
7653 //
7654 // that will copy each of the array elements.
7655 QualType SizeType = S.Context.getSizeType();
7656
7657 // Create the iteration variable.
7658 IdentifierInfo *IterationVarName = 0;
7659 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00007660 SmallString<8> Str;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007661 llvm::raw_svector_ostream OS(Str);
7662 OS << "__i" << Depth;
7663 IterationVarName = &S.Context.Idents.get(OS.str());
7664 }
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007665 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007666 IterationVarName, SizeType,
7667 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00007668 SC_None, SC_None);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007669
7670 // Initialize the iteration variable to zero.
7671 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00007672 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00007673
7674 // Create a reference to the iteration variable; we'll use this several
7675 // times throughout.
7676 Expr *IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00007677 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007678 assert(IterationVarRef && "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00007679 Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take();
7680 assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!");
7681
Douglas Gregor06a9f362010-05-01 20:49:11 +00007682 // Create the DeclStmt that holds the iteration variable.
7683 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
7684
7685 // Create the comparison against the array bound.
Jay Foad9f71a8f2010-12-07 08:25:34 +00007686 llvm::APInt Upper
7687 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCall9ae2f072010-08-23 23:25:46 +00007688 Expr *Comparison
Eli Friedman8c382062012-01-23 02:35:22 +00007689 = new (S.Context) BinaryOperator(IterationVarRefRVal,
John McCallf89e55a2010-11-18 06:31:45 +00007690 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
7691 BO_NE, S.Context.BoolTy,
7692 VK_RValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007693
7694 // Create the pre-increment of the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00007695 Expr *Increment
John McCallf89e55a2010-11-18 06:31:45 +00007696 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
7697 VK_LValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007698
7699 // Subscript the "from" and "to" expressions with the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00007700 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00007701 IterationVarRefRVal,
7702 Loc));
John McCall9ae2f072010-08-23 23:25:46 +00007703 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00007704 IterationVarRefRVal,
7705 Loc));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007706 if (!Copying) // Cast to rvalue
7707 From = CastForMoving(S, From);
7708
7709 // Build the copy/move for an individual element of the array.
John McCallf89e55a2010-11-18 06:31:45 +00007710 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
7711 To, From, CopyingBaseSubobject,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007712 Copying, Depth + 1);
Douglas Gregorff331c12010-07-25 18:17:45 +00007713 if (Copy.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007714 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007715
7716 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00007717 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007718 S.MakeFullExpr(Comparison),
John McCalld226f652010-08-21 09:40:31 +00007719 0, S.MakeFullExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00007720 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007721}
7722
Sean Hunt30de05c2011-05-14 05:23:20 +00007723std::pair<Sema::ImplicitExceptionSpecification, bool>
7724Sema::ComputeDefaultedCopyAssignmentExceptionSpecAndConst(
7725 CXXRecordDecl *ClassDecl) {
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007726 if (ClassDecl->isInvalidDecl())
7727 return std::make_pair(ImplicitExceptionSpecification(Context), false);
7728
Douglas Gregord3c35902010-07-01 16:36:15 +00007729 // C++ [class.copy]p10:
7730 // If the class definition does not explicitly declare a copy
7731 // assignment operator, one is declared implicitly.
7732 // The implicitly-defined copy assignment operator for a class X
7733 // will have the form
7734 //
7735 // X& X::operator=(const X&)
7736 //
7737 // if
7738 bool HasConstCopyAssignment = true;
7739
7740 // -- each direct base class B of X has a copy assignment operator
7741 // whose parameter is of type const B&, const volatile B& or B,
7742 // and
7743 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7744 BaseEnd = ClassDecl->bases_end();
7745 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00007746 // We'll handle this below
7747 if (LangOpts.CPlusPlus0x && Base->isVirtual())
7748 continue;
7749
Douglas Gregord3c35902010-07-01 16:36:15 +00007750 assert(!Base->getType()->isDependentType() &&
7751 "Cannot generate implicit members for class with dependent bases.");
Sean Hunt661c67a2011-06-21 23:42:56 +00007752 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
7753 LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
7754 &HasConstCopyAssignment);
7755 }
7756
Richard Smithebaf0e62011-10-18 20:49:44 +00007757 // In C++11, the above citation has "or virtual" added
Sean Hunt661c67a2011-06-21 23:42:56 +00007758 if (LangOpts.CPlusPlus0x) {
7759 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7760 BaseEnd = ClassDecl->vbases_end();
7761 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
7762 assert(!Base->getType()->isDependentType() &&
7763 "Cannot generate implicit members for class with dependent bases.");
7764 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
7765 LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
7766 &HasConstCopyAssignment);
7767 }
Douglas Gregord3c35902010-07-01 16:36:15 +00007768 }
7769
7770 // -- for all the nonstatic data members of X that are of a class
7771 // type M (or array thereof), each such class type has a copy
7772 // assignment operator whose parameter is of type const M&,
7773 // const volatile M& or M.
7774 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7775 FieldEnd = ClassDecl->field_end();
7776 HasConstCopyAssignment && Field != FieldEnd;
7777 ++Field) {
7778 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00007779 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7780 LookupCopyingAssignment(FieldClassDecl, Qualifiers::Const, false, 0,
7781 &HasConstCopyAssignment);
Douglas Gregord3c35902010-07-01 16:36:15 +00007782 }
7783 }
7784
7785 // Otherwise, the implicitly declared copy assignment operator will
7786 // have the form
7787 //
7788 // X& X::operator=(X&)
Douglas Gregord3c35902010-07-01 16:36:15 +00007789
Douglas Gregorb87786f2010-07-01 17:48:08 +00007790 // C++ [except.spec]p14:
7791 // An implicitly declared special member function (Clause 12) shall have an
7792 // exception-specification. [...]
Sean Hunt661c67a2011-06-21 23:42:56 +00007793
7794 // It is unspecified whether or not an implicit copy assignment operator
7795 // attempts to deduplicate calls to assignment operators of virtual bases are
7796 // made. As such, this exception specification is effectively unspecified.
7797 // Based on a similar decision made for constness in C++0x, we're erring on
7798 // the side of assuming such calls to be made regardless of whether they
7799 // actually happen.
Douglas Gregorb87786f2010-07-01 17:48:08 +00007800 ImplicitExceptionSpecification ExceptSpec(Context);
Sean Hunt661c67a2011-06-21 23:42:56 +00007801 unsigned ArgQuals = HasConstCopyAssignment ? Qualifiers::Const : 0;
Douglas Gregorb87786f2010-07-01 17:48:08 +00007802 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7803 BaseEnd = ClassDecl->bases_end();
7804 Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00007805 if (Base->isVirtual())
7806 continue;
7807
Douglas Gregora376d102010-07-02 21:50:04 +00007808 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00007809 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00007810 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7811 ArgQuals, false, 0))
Douglas Gregorb87786f2010-07-01 17:48:08 +00007812 ExceptSpec.CalledDecl(CopyAssign);
7813 }
Sean Hunt661c67a2011-06-21 23:42:56 +00007814
7815 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7816 BaseEnd = ClassDecl->vbases_end();
7817 Base != BaseEnd; ++Base) {
7818 CXXRecordDecl *BaseClassDecl
7819 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7820 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7821 ArgQuals, false, 0))
7822 ExceptSpec.CalledDecl(CopyAssign);
7823 }
7824
Douglas Gregorb87786f2010-07-01 17:48:08 +00007825 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7826 FieldEnd = ClassDecl->field_end();
7827 Field != FieldEnd;
7828 ++Field) {
7829 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00007830 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7831 if (CXXMethodDecl *CopyAssign =
7832 LookupCopyingAssignment(FieldClassDecl, ArgQuals, false, 0))
7833 ExceptSpec.CalledDecl(CopyAssign);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007834 }
Douglas Gregorb87786f2010-07-01 17:48:08 +00007835 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007836
Sean Hunt30de05c2011-05-14 05:23:20 +00007837 return std::make_pair(ExceptSpec, HasConstCopyAssignment);
7838}
7839
7840CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
7841 // Note: The following rules are largely analoguous to the copy
7842 // constructor rules. Note that virtual bases are not taken into account
7843 // for determining the argument type of the operator. Note also that
7844 // operators taking an object instead of a reference are allowed.
7845
7846 ImplicitExceptionSpecification Spec(Context);
7847 bool Const;
7848 llvm::tie(Spec, Const) =
7849 ComputeDefaultedCopyAssignmentExceptionSpecAndConst(ClassDecl);
7850
7851 QualType ArgType = Context.getTypeDeclType(ClassDecl);
7852 QualType RetType = Context.getLValueReferenceType(ArgType);
7853 if (Const)
7854 ArgType = ArgType.withConst();
7855 ArgType = Context.getLValueReferenceType(ArgType);
7856
Douglas Gregord3c35902010-07-01 16:36:15 +00007857 // An implicitly-declared copy assignment operator is an inline public
7858 // member of its class.
Sean Hunt30de05c2011-05-14 05:23:20 +00007859 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Douglas Gregord3c35902010-07-01 16:36:15 +00007860 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007861 SourceLocation ClassLoc = ClassDecl->getLocation();
7862 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregord3c35902010-07-01 16:36:15 +00007863 CXXMethodDecl *CopyAssignment
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007864 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
John McCalle23cf432010-12-14 08:05:40 +00007865 Context.getFunctionType(RetType, &ArgType, 1, EPI),
Douglas Gregord3c35902010-07-01 16:36:15 +00007866 /*TInfo=*/0, /*isStatic=*/false,
John McCalld931b082010-08-26 03:08:43 +00007867 /*StorageClassAsWritten=*/SC_None,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007868 /*isInline=*/true, /*isConstexpr=*/false,
Douglas Gregorf5251602011-03-08 17:10:18 +00007869 SourceLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00007870 CopyAssignment->setAccess(AS_public);
Sean Hunt7f410192011-05-14 05:23:24 +00007871 CopyAssignment->setDefaulted();
Douglas Gregord3c35902010-07-01 16:36:15 +00007872 CopyAssignment->setImplicit();
7873 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Douglas Gregord3c35902010-07-01 16:36:15 +00007874
7875 // Add the parameter to the operator.
7876 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007877 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregord3c35902010-07-01 16:36:15 +00007878 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00007879 SC_None,
7880 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00007881 CopyAssignment->setParams(FromParam);
Douglas Gregord3c35902010-07-01 16:36:15 +00007882
Douglas Gregora376d102010-07-02 21:50:04 +00007883 // Note that we have added this copy-assignment operator.
Douglas Gregora376d102010-07-02 21:50:04 +00007884 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Sean Hunt7f410192011-05-14 05:23:24 +00007885
Douglas Gregor23c94db2010-07-02 17:43:08 +00007886 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora376d102010-07-02 21:50:04 +00007887 PushOnScopeChains(CopyAssignment, S, false);
7888 ClassDecl->addDecl(CopyAssignment);
Douglas Gregord3c35902010-07-01 16:36:15 +00007889
Nico Weberafcc96a2012-01-23 03:19:29 +00007890 // C++0x [class.copy]p19:
7891 // .... If the class definition does not explicitly declare a copy
7892 // assignment operator, there is no user-declared move constructor, and
7893 // there is no user-declared move assignment operator, a copy assignment
7894 // operator is implicitly declared as defaulted.
7895 if ((ClassDecl->hasUserDeclaredMoveConstructor() &&
Nico Weber28976602012-01-23 04:01:33 +00007896 !getLangOptions().MicrosoftMode) ||
7897 ClassDecl->hasUserDeclaredMoveAssignment() ||
Sean Hunt1ccbc542011-06-22 01:05:13 +00007898 ShouldDeleteCopyAssignmentOperator(CopyAssignment))
Sean Hunt71a682f2011-05-18 03:41:58 +00007899 CopyAssignment->setDeletedAsWritten();
7900
Douglas Gregord3c35902010-07-01 16:36:15 +00007901 AddOverriddenMethods(ClassDecl, CopyAssignment);
7902 return CopyAssignment;
7903}
7904
Douglas Gregor06a9f362010-05-01 20:49:11 +00007905void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
7906 CXXMethodDecl *CopyAssignOperator) {
Sean Hunt7f410192011-05-14 05:23:24 +00007907 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00007908 CopyAssignOperator->isOverloadedOperator() &&
7909 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Sean Huntcd10dec2011-05-23 23:14:04 +00007910 !CopyAssignOperator->doesThisDeclarationHaveABody()) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00007911 "DefineImplicitCopyAssignment called for wrong function");
7912
7913 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
7914
7915 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
7916 CopyAssignOperator->setInvalidDecl();
7917 return;
7918 }
7919
7920 CopyAssignOperator->setUsed();
7921
7922 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007923 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007924
7925 // C++0x [class.copy]p30:
7926 // The implicitly-defined or explicitly-defaulted copy assignment operator
7927 // for a non-union class X performs memberwise copy assignment of its
7928 // subobjects. The direct base classes of X are assigned first, in the
7929 // order of their declaration in the base-specifier-list, and then the
7930 // immediate non-static data members of X are assigned, in the order in
7931 // which they were declared in the class definition.
7932
7933 // The statements that form the synthesized function body.
John McCallca0408f2010-08-23 06:44:23 +00007934 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007935
7936 // The parameter for the "other" object, which we are copying from.
7937 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
7938 Qualifiers OtherQuals = Other->getType().getQualifiers();
7939 QualType OtherRefType = Other->getType();
7940 if (const LValueReferenceType *OtherRef
7941 = OtherRefType->getAs<LValueReferenceType>()) {
7942 OtherRefType = OtherRef->getPointeeType();
7943 OtherQuals = OtherRefType.getQualifiers();
7944 }
7945
7946 // Our location for everything implicitly-generated.
7947 SourceLocation Loc = CopyAssignOperator->getLocation();
7948
7949 // Construct a reference to the "other" object. We'll be using this
7950 // throughout the generated ASTs.
John McCall09431682010-11-18 19:01:18 +00007951 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007952 assert(OtherRef && "Reference to parameter cannot fail!");
7953
7954 // Construct the "this" pointer. We'll be using this throughout the generated
7955 // ASTs.
7956 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
7957 assert(This && "Reference to this cannot fail!");
7958
7959 // Assign base classes.
7960 bool Invalid = false;
7961 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7962 E = ClassDecl->bases_end(); Base != E; ++Base) {
7963 // Form the assignment:
7964 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
7965 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00007966 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00007967 Invalid = true;
7968 continue;
7969 }
7970
John McCallf871d0c2010-08-07 06:22:56 +00007971 CXXCastPath BasePath;
7972 BasePath.push_back(Base);
7973
Douglas Gregor06a9f362010-05-01 20:49:11 +00007974 // Construct the "from" expression, which is an implicit cast to the
7975 // appropriately-qualified base type.
John McCall3fa5cae2010-10-26 07:05:15 +00007976 Expr *From = OtherRef;
John Wiegley429bb272011-04-08 18:41:53 +00007977 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
7978 CK_UncheckedDerivedToBase,
7979 VK_LValue, &BasePath).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007980
7981 // Dereference "this".
John McCall5baba9d2010-08-25 10:28:54 +00007982 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007983
7984 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley429bb272011-04-08 18:41:53 +00007985 To = ImpCastExprToType(To.take(),
7986 Context.getCVRQualifiedType(BaseType,
7987 CopyAssignOperator->getTypeQualifiers()),
7988 CK_UncheckedDerivedToBase,
7989 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007990
7991 // Build the copy.
John McCall60d7b3a2010-08-24 06:29:42 +00007992 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00007993 To.get(), From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007994 /*CopyingBaseSubobject=*/true,
7995 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007996 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007997 Diag(CurrentLocation, diag::note_member_synthesized_at)
7998 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7999 CopyAssignOperator->setInvalidDecl();
8000 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008001 }
8002
8003 // Success! Record the copy.
8004 Statements.push_back(Copy.takeAs<Expr>());
8005 }
8006
8007 // \brief Reference to the __builtin_memcpy function.
8008 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00008009 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00008010 Expr *CollectableMemCpyRef = 0;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008011
8012 // Assign non-static members.
8013 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8014 FieldEnd = ClassDecl->field_end();
8015 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00008016 if (Field->isUnnamedBitfield())
8017 continue;
8018
Douglas Gregor06a9f362010-05-01 20:49:11 +00008019 // Check for members of reference type; we can't copy those.
8020 if (Field->getType()->isReferenceType()) {
8021 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8022 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8023 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008024 Diag(CurrentLocation, diag::note_member_synthesized_at)
8025 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008026 Invalid = true;
8027 continue;
8028 }
8029
8030 // Check for members of const-qualified, non-class type.
8031 QualType BaseType = Context.getBaseElementType(Field->getType());
8032 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8033 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8034 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8035 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008036 Diag(CurrentLocation, diag::note_member_synthesized_at)
8037 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008038 Invalid = true;
8039 continue;
8040 }
John McCallb77115d2011-06-17 00:18:42 +00008041
8042 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00008043 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8044 continue;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008045
8046 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00008047 if (FieldType->isIncompleteArrayType()) {
8048 assert(ClassDecl->hasFlexibleArrayMember() &&
8049 "Incomplete array type is not valid");
8050 continue;
8051 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008052
8053 // Build references to the field in the object we're copying from and to.
8054 CXXScopeSpec SS; // Intentionally empty
8055 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8056 LookupMemberName);
8057 MemberLookup.addDecl(*Field);
8058 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00008059 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall09431682010-11-18 19:01:18 +00008060 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008061 SS, SourceLocation(), 0,
8062 MemberLookup, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00008063 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall09431682010-11-18 19:01:18 +00008064 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008065 SS, SourceLocation(), 0,
8066 MemberLookup, 0);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008067 assert(!From.isInvalid() && "Implicit field reference cannot fail");
8068 assert(!To.isInvalid() && "Implicit field reference cannot fail");
8069
8070 // If the field should be copied with __builtin_memcpy rather than via
8071 // explicit assignments, do so. This optimization only applies for arrays
8072 // of scalars and arrays of class type with trivial copy-assignment
8073 // operators.
Fariborz Jahanian6b167f42011-08-09 00:26:11 +00008074 if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008075 && BaseType.hasTrivialAssignment(Context, /*Copying=*/true)) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00008076 // Compute the size of the memory buffer to be copied.
8077 QualType SizeType = Context.getSizeType();
8078 llvm::APInt Size(Context.getTypeSize(SizeType),
8079 Context.getTypeSizeInChars(BaseType).getQuantity());
8080 for (const ConstantArrayType *Array
8081 = Context.getAsConstantArrayType(FieldType);
8082 Array;
8083 Array = Context.getAsConstantArrayType(Array->getElementType())) {
Jay Foad9f71a8f2010-12-07 08:25:34 +00008084 llvm::APInt ArraySize
8085 = Array->getSize().zextOrTrunc(Size.getBitWidth());
Douglas Gregor06a9f362010-05-01 20:49:11 +00008086 Size *= ArraySize;
8087 }
8088
8089 // Take the address of the field references for "from" and "to".
John McCall2de56d12010-08-25 11:45:40 +00008090 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
8091 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00008092
8093 bool NeedsCollectableMemCpy =
8094 (BaseType->isRecordType() &&
8095 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
8096
8097 if (NeedsCollectableMemCpy) {
8098 if (!CollectableMemCpyRef) {
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00008099 // Create a reference to the __builtin_objc_memmove_collectable function.
8100 LookupResult R(*this,
8101 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00008102 Loc, LookupOrdinaryName);
8103 LookupName(R, TUScope, true);
8104
8105 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
8106 if (!CollectableMemCpy) {
8107 // Something went horribly wrong earlier, and we will have
8108 // complained about it.
8109 Invalid = true;
8110 continue;
8111 }
8112
8113 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
8114 CollectableMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00008115 VK_LValue, Loc, 0).take();
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00008116 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
8117 }
8118 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008119 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00008120 else if (!BuiltinMemCpyRef) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00008121 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
8122 LookupOrdinaryName);
8123 LookupName(R, TUScope, true);
8124
8125 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
8126 if (!BuiltinMemCpy) {
8127 // Something went horribly wrong earlier, and we will have complained
8128 // about it.
8129 Invalid = true;
8130 continue;
8131 }
8132
8133 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
8134 BuiltinMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00008135 VK_LValue, Loc, 0).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008136 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
8137 }
8138
John McCallca0408f2010-08-23 06:44:23 +00008139 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008140 CallArgs.push_back(To.takeAs<Expr>());
8141 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00008142 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCall60d7b3a2010-08-24 06:29:42 +00008143 ExprResult Call = ExprError();
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00008144 if (NeedsCollectableMemCpy)
8145 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00008146 CollectableMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00008147 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00008148 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00008149 else
8150 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00008151 BuiltinMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00008152 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00008153 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00008154
Douglas Gregor06a9f362010-05-01 20:49:11 +00008155 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8156 Statements.push_back(Call.takeAs<Expr>());
8157 continue;
8158 }
8159
8160 // Build the copy of this field.
John McCall60d7b3a2010-08-24 06:29:42 +00008161 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008162 To.get(), From.get(),
8163 /*CopyingBaseSubobject=*/false,
8164 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008165 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008166 Diag(CurrentLocation, diag::note_member_synthesized_at)
8167 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8168 CopyAssignOperator->setInvalidDecl();
8169 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008170 }
8171
8172 // Success! Record the copy.
8173 Statements.push_back(Copy.takeAs<Stmt>());
8174 }
8175
8176 if (!Invalid) {
8177 // Add a "return *this;"
John McCall2de56d12010-08-25 11:45:40 +00008178 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008179
John McCall60d7b3a2010-08-24 06:29:42 +00008180 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00008181 if (Return.isInvalid())
8182 Invalid = true;
8183 else {
8184 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008185
8186 if (Trap.hasErrorOccurred()) {
8187 Diag(CurrentLocation, diag::note_member_synthesized_at)
8188 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8189 Invalid = true;
8190 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008191 }
8192 }
8193
8194 if (Invalid) {
8195 CopyAssignOperator->setInvalidDecl();
8196 return;
8197 }
8198
John McCall60d7b3a2010-08-24 06:29:42 +00008199 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
Douglas Gregor06a9f362010-05-01 20:49:11 +00008200 /*isStmtExpr=*/false);
8201 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8202 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008203
8204 if (ASTMutationListener *L = getASTMutationListener()) {
8205 L->CompletedImplicitDefinition(CopyAssignOperator);
8206 }
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008207}
8208
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008209Sema::ImplicitExceptionSpecification
8210Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXRecordDecl *ClassDecl) {
8211 ImplicitExceptionSpecification ExceptSpec(Context);
8212
8213 if (ClassDecl->isInvalidDecl())
8214 return ExceptSpec;
8215
8216 // C++0x [except.spec]p14:
8217 // An implicitly declared special member function (Clause 12) shall have an
8218 // exception-specification. [...]
8219
8220 // It is unspecified whether or not an implicit move assignment operator
8221 // attempts to deduplicate calls to assignment operators of virtual bases are
8222 // made. As such, this exception specification is effectively unspecified.
8223 // Based on a similar decision made for constness in C++0x, we're erring on
8224 // the side of assuming such calls to be made regardless of whether they
8225 // actually happen.
8226 // Note that a move constructor is not implicitly declared when there are
8227 // virtual bases, but it can still be user-declared and explicitly defaulted.
8228 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8229 BaseEnd = ClassDecl->bases_end();
8230 Base != BaseEnd; ++Base) {
8231 if (Base->isVirtual())
8232 continue;
8233
8234 CXXRecordDecl *BaseClassDecl
8235 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8236 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
8237 false, 0))
8238 ExceptSpec.CalledDecl(MoveAssign);
8239 }
8240
8241 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8242 BaseEnd = ClassDecl->vbases_end();
8243 Base != BaseEnd; ++Base) {
8244 CXXRecordDecl *BaseClassDecl
8245 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8246 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
8247 false, 0))
8248 ExceptSpec.CalledDecl(MoveAssign);
8249 }
8250
8251 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8252 FieldEnd = ClassDecl->field_end();
8253 Field != FieldEnd;
8254 ++Field) {
8255 QualType FieldType = Context.getBaseElementType((*Field)->getType());
8256 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8257 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(FieldClassDecl,
8258 false, 0))
8259 ExceptSpec.CalledDecl(MoveAssign);
8260 }
8261 }
8262
8263 return ExceptSpec;
8264}
8265
8266CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
8267 // Note: The following rules are largely analoguous to the move
8268 // constructor rules.
8269
8270 ImplicitExceptionSpecification Spec(
8271 ComputeDefaultedMoveAssignmentExceptionSpec(ClassDecl));
8272
8273 QualType ArgType = Context.getTypeDeclType(ClassDecl);
8274 QualType RetType = Context.getLValueReferenceType(ArgType);
8275 ArgType = Context.getRValueReferenceType(ArgType);
8276
8277 // An implicitly-declared move assignment operator is an inline public
8278 // member of its class.
8279 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8280 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8281 SourceLocation ClassLoc = ClassDecl->getLocation();
8282 DeclarationNameInfo NameInfo(Name, ClassLoc);
8283 CXXMethodDecl *MoveAssignment
8284 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8285 Context.getFunctionType(RetType, &ArgType, 1, EPI),
8286 /*TInfo=*/0, /*isStatic=*/false,
8287 /*StorageClassAsWritten=*/SC_None,
8288 /*isInline=*/true,
8289 /*isConstexpr=*/false,
8290 SourceLocation());
8291 MoveAssignment->setAccess(AS_public);
8292 MoveAssignment->setDefaulted();
8293 MoveAssignment->setImplicit();
8294 MoveAssignment->setTrivial(ClassDecl->hasTrivialMoveAssignment());
8295
8296 // Add the parameter to the operator.
8297 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
8298 ClassLoc, ClassLoc, /*Id=*/0,
8299 ArgType, /*TInfo=*/0,
8300 SC_None,
8301 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008302 MoveAssignment->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008303
8304 // Note that we have added this copy-assignment operator.
8305 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
8306
8307 // C++0x [class.copy]p9:
8308 // If the definition of a class X does not explicitly declare a move
8309 // assignment operator, one will be implicitly declared as defaulted if and
8310 // only if:
8311 // [...]
8312 // - the move assignment operator would not be implicitly defined as
8313 // deleted.
8314 if (ShouldDeleteMoveAssignmentOperator(MoveAssignment)) {
8315 // Cache this result so that we don't try to generate this over and over
8316 // on every lookup, leaking memory and wasting time.
8317 ClassDecl->setFailedImplicitMoveAssignment();
8318 return 0;
8319 }
8320
8321 if (Scope *S = getScopeForContext(ClassDecl))
8322 PushOnScopeChains(MoveAssignment, S, false);
8323 ClassDecl->addDecl(MoveAssignment);
8324
8325 AddOverriddenMethods(ClassDecl, MoveAssignment);
8326 return MoveAssignment;
8327}
8328
8329void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
8330 CXXMethodDecl *MoveAssignOperator) {
8331 assert((MoveAssignOperator->isDefaulted() &&
8332 MoveAssignOperator->isOverloadedOperator() &&
8333 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
8334 !MoveAssignOperator->doesThisDeclarationHaveABody()) &&
8335 "DefineImplicitMoveAssignment called for wrong function");
8336
8337 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
8338
8339 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
8340 MoveAssignOperator->setInvalidDecl();
8341 return;
8342 }
8343
8344 MoveAssignOperator->setUsed();
8345
8346 ImplicitlyDefinedFunctionScope Scope(*this, MoveAssignOperator);
8347 DiagnosticErrorTrap Trap(Diags);
8348
8349 // C++0x [class.copy]p28:
8350 // The implicitly-defined or move assignment operator for a non-union class
8351 // X performs memberwise move assignment of its subobjects. The direct base
8352 // classes of X are assigned first, in the order of their declaration in the
8353 // base-specifier-list, and then the immediate non-static data members of X
8354 // are assigned, in the order in which they were declared in the class
8355 // definition.
8356
8357 // The statements that form the synthesized function body.
8358 ASTOwningVector<Stmt*> Statements(*this);
8359
8360 // The parameter for the "other" object, which we are move from.
8361 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
8362 QualType OtherRefType = Other->getType()->
8363 getAs<RValueReferenceType>()->getPointeeType();
8364 assert(OtherRefType.getQualifiers() == 0 &&
8365 "Bad argument type of defaulted move assignment");
8366
8367 // Our location for everything implicitly-generated.
8368 SourceLocation Loc = MoveAssignOperator->getLocation();
8369
8370 // Construct a reference to the "other" object. We'll be using this
8371 // throughout the generated ASTs.
8372 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
8373 assert(OtherRef && "Reference to parameter cannot fail!");
8374 // Cast to rvalue.
8375 OtherRef = CastForMoving(*this, OtherRef);
8376
8377 // Construct the "this" pointer. We'll be using this throughout the generated
8378 // ASTs.
8379 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8380 assert(This && "Reference to this cannot fail!");
8381
8382 // Assign base classes.
8383 bool Invalid = false;
8384 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8385 E = ClassDecl->bases_end(); Base != E; ++Base) {
8386 // Form the assignment:
8387 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
8388 QualType BaseType = Base->getType().getUnqualifiedType();
8389 if (!BaseType->isRecordType()) {
8390 Invalid = true;
8391 continue;
8392 }
8393
8394 CXXCastPath BasePath;
8395 BasePath.push_back(Base);
8396
8397 // Construct the "from" expression, which is an implicit cast to the
8398 // appropriately-qualified base type.
8399 Expr *From = OtherRef;
8400 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
Douglas Gregorb2b56582011-09-06 16:26:56 +00008401 VK_XValue, &BasePath).take();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008402
8403 // Dereference "this".
8404 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8405
8406 // Implicitly cast "this" to the appropriately-qualified base type.
8407 To = ImpCastExprToType(To.take(),
8408 Context.getCVRQualifiedType(BaseType,
8409 MoveAssignOperator->getTypeQualifiers()),
8410 CK_UncheckedDerivedToBase,
8411 VK_LValue, &BasePath);
8412
8413 // Build the move.
8414 StmtResult Move = BuildSingleCopyAssign(*this, Loc, BaseType,
8415 To.get(), From,
8416 /*CopyingBaseSubobject=*/true,
8417 /*Copying=*/false);
8418 if (Move.isInvalid()) {
8419 Diag(CurrentLocation, diag::note_member_synthesized_at)
8420 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8421 MoveAssignOperator->setInvalidDecl();
8422 return;
8423 }
8424
8425 // Success! Record the move.
8426 Statements.push_back(Move.takeAs<Expr>());
8427 }
8428
8429 // \brief Reference to the __builtin_memcpy function.
8430 Expr *BuiltinMemCpyRef = 0;
8431 // \brief Reference to the __builtin_objc_memmove_collectable function.
8432 Expr *CollectableMemCpyRef = 0;
8433
8434 // Assign non-static members.
8435 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8436 FieldEnd = ClassDecl->field_end();
8437 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00008438 if (Field->isUnnamedBitfield())
8439 continue;
8440
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008441 // Check for members of reference type; we can't move those.
8442 if (Field->getType()->isReferenceType()) {
8443 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8444 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8445 Diag(Field->getLocation(), diag::note_declared_at);
8446 Diag(CurrentLocation, diag::note_member_synthesized_at)
8447 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8448 Invalid = true;
8449 continue;
8450 }
8451
8452 // Check for members of const-qualified, non-class type.
8453 QualType BaseType = Context.getBaseElementType(Field->getType());
8454 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8455 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8456 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8457 Diag(Field->getLocation(), diag::note_declared_at);
8458 Diag(CurrentLocation, diag::note_member_synthesized_at)
8459 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8460 Invalid = true;
8461 continue;
8462 }
8463
8464 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00008465 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8466 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008467
8468 QualType FieldType = Field->getType().getNonReferenceType();
8469 if (FieldType->isIncompleteArrayType()) {
8470 assert(ClassDecl->hasFlexibleArrayMember() &&
8471 "Incomplete array type is not valid");
8472 continue;
8473 }
8474
8475 // Build references to the field in the object we're copying from and to.
8476 CXXScopeSpec SS; // Intentionally empty
8477 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8478 LookupMemberName);
8479 MemberLookup.addDecl(*Field);
8480 MemberLookup.resolveKind();
8481 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
8482 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008483 SS, SourceLocation(), 0,
8484 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008485 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
8486 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008487 SS, SourceLocation(), 0,
8488 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008489 assert(!From.isInvalid() && "Implicit field reference cannot fail");
8490 assert(!To.isInvalid() && "Implicit field reference cannot fail");
8491
8492 assert(!From.get()->isLValue() && // could be xvalue or prvalue
8493 "Member reference with rvalue base must be rvalue except for reference "
8494 "members, which aren't allowed for move assignment.");
8495
8496 // If the field should be copied with __builtin_memcpy rather than via
8497 // explicit assignments, do so. This optimization only applies for arrays
8498 // of scalars and arrays of class type with trivial move-assignment
8499 // operators.
8500 if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
8501 && BaseType.hasTrivialAssignment(Context, /*Copying=*/false)) {
8502 // Compute the size of the memory buffer to be copied.
8503 QualType SizeType = Context.getSizeType();
8504 llvm::APInt Size(Context.getTypeSize(SizeType),
8505 Context.getTypeSizeInChars(BaseType).getQuantity());
8506 for (const ConstantArrayType *Array
8507 = Context.getAsConstantArrayType(FieldType);
8508 Array;
8509 Array = Context.getAsConstantArrayType(Array->getElementType())) {
8510 llvm::APInt ArraySize
8511 = Array->getSize().zextOrTrunc(Size.getBitWidth());
8512 Size *= ArraySize;
8513 }
8514
Douglas Gregor45d3d712011-09-01 02:09:07 +00008515 // Take the address of the field references for "from" and "to". We
8516 // directly construct UnaryOperators here because semantic analysis
8517 // does not permit us to take the address of an xvalue.
8518 From = new (Context) UnaryOperator(From.get(), UO_AddrOf,
8519 Context.getPointerType(From.get()->getType()),
8520 VK_RValue, OK_Ordinary, Loc);
8521 To = new (Context) UnaryOperator(To.get(), UO_AddrOf,
8522 Context.getPointerType(To.get()->getType()),
8523 VK_RValue, OK_Ordinary, Loc);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008524
8525 bool NeedsCollectableMemCpy =
8526 (BaseType->isRecordType() &&
8527 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
8528
8529 if (NeedsCollectableMemCpy) {
8530 if (!CollectableMemCpyRef) {
8531 // Create a reference to the __builtin_objc_memmove_collectable function.
8532 LookupResult R(*this,
8533 &Context.Idents.get("__builtin_objc_memmove_collectable"),
8534 Loc, LookupOrdinaryName);
8535 LookupName(R, TUScope, true);
8536
8537 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
8538 if (!CollectableMemCpy) {
8539 // Something went horribly wrong earlier, and we will have
8540 // complained about it.
8541 Invalid = true;
8542 continue;
8543 }
8544
8545 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
8546 CollectableMemCpy->getType(),
8547 VK_LValue, Loc, 0).take();
8548 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
8549 }
8550 }
8551 // Create a reference to the __builtin_memcpy builtin function.
8552 else if (!BuiltinMemCpyRef) {
8553 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
8554 LookupOrdinaryName);
8555 LookupName(R, TUScope, true);
8556
8557 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
8558 if (!BuiltinMemCpy) {
8559 // Something went horribly wrong earlier, and we will have complained
8560 // about it.
8561 Invalid = true;
8562 continue;
8563 }
8564
8565 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
8566 BuiltinMemCpy->getType(),
8567 VK_LValue, Loc, 0).take();
8568 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
8569 }
8570
8571 ASTOwningVector<Expr*> CallArgs(*this);
8572 CallArgs.push_back(To.takeAs<Expr>());
8573 CallArgs.push_back(From.takeAs<Expr>());
8574 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
8575 ExprResult Call = ExprError();
8576 if (NeedsCollectableMemCpy)
8577 Call = ActOnCallExpr(/*Scope=*/0,
8578 CollectableMemCpyRef,
8579 Loc, move_arg(CallArgs),
8580 Loc);
8581 else
8582 Call = ActOnCallExpr(/*Scope=*/0,
8583 BuiltinMemCpyRef,
8584 Loc, move_arg(CallArgs),
8585 Loc);
8586
8587 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8588 Statements.push_back(Call.takeAs<Expr>());
8589 continue;
8590 }
8591
8592 // Build the move of this field.
8593 StmtResult Move = BuildSingleCopyAssign(*this, Loc, FieldType,
8594 To.get(), From.get(),
8595 /*CopyingBaseSubobject=*/false,
8596 /*Copying=*/false);
8597 if (Move.isInvalid()) {
8598 Diag(CurrentLocation, diag::note_member_synthesized_at)
8599 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8600 MoveAssignOperator->setInvalidDecl();
8601 return;
8602 }
8603
8604 // Success! Record the copy.
8605 Statements.push_back(Move.takeAs<Stmt>());
8606 }
8607
8608 if (!Invalid) {
8609 // Add a "return *this;"
8610 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8611
8612 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
8613 if (Return.isInvalid())
8614 Invalid = true;
8615 else {
8616 Statements.push_back(Return.takeAs<Stmt>());
8617
8618 if (Trap.hasErrorOccurred()) {
8619 Diag(CurrentLocation, diag::note_member_synthesized_at)
8620 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8621 Invalid = true;
8622 }
8623 }
8624 }
8625
8626 if (Invalid) {
8627 MoveAssignOperator->setInvalidDecl();
8628 return;
8629 }
8630
8631 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
8632 /*isStmtExpr=*/false);
8633 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8634 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
8635
8636 if (ASTMutationListener *L = getASTMutationListener()) {
8637 L->CompletedImplicitDefinition(MoveAssignOperator);
8638 }
8639}
8640
Sean Hunt49634cf2011-05-13 06:10:58 +00008641std::pair<Sema::ImplicitExceptionSpecification, bool>
8642Sema::ComputeDefaultedCopyCtorExceptionSpecAndConst(CXXRecordDecl *ClassDecl) {
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008643 if (ClassDecl->isInvalidDecl())
8644 return std::make_pair(ImplicitExceptionSpecification(Context), false);
8645
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008646 // C++ [class.copy]p5:
8647 // The implicitly-declared copy constructor for a class X will
8648 // have the form
8649 //
8650 // X::X(const X&)
8651 //
8652 // if
Sean Huntc530d172011-06-10 04:44:37 +00008653 // FIXME: It ought to be possible to store this on the record.
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008654 bool HasConstCopyConstructor = true;
8655
8656 // -- each direct or virtual base class B of X has a copy
8657 // constructor whose first parameter is of type const B& or
8658 // const volatile B&, and
8659 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8660 BaseEnd = ClassDecl->bases_end();
8661 HasConstCopyConstructor && Base != BaseEnd;
8662 ++Base) {
Douglas Gregor598a8542010-07-01 18:27:03 +00008663 // Virtual bases are handled below.
8664 if (Base->isVirtual())
8665 continue;
8666
Douglas Gregor22584312010-07-02 23:41:54 +00008667 CXXRecordDecl *BaseClassDecl
Douglas Gregor598a8542010-07-01 18:27:03 +00008668 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00008669 LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
8670 &HasConstCopyConstructor);
Douglas Gregor598a8542010-07-01 18:27:03 +00008671 }
8672
8673 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8674 BaseEnd = ClassDecl->vbases_end();
8675 HasConstCopyConstructor && Base != BaseEnd;
8676 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00008677 CXXRecordDecl *BaseClassDecl
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008678 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00008679 LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
8680 &HasConstCopyConstructor);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008681 }
8682
8683 // -- for all the nonstatic data members of X that are of a
8684 // class type M (or array thereof), each such class type
8685 // has a copy constructor whose first parameter is of type
8686 // const M& or const volatile M&.
8687 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8688 FieldEnd = ClassDecl->field_end();
8689 HasConstCopyConstructor && Field != FieldEnd;
8690 ++Field) {
Douglas Gregor598a8542010-07-01 18:27:03 +00008691 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Huntc530d172011-06-10 04:44:37 +00008692 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Sean Hunt661c67a2011-06-21 23:42:56 +00008693 LookupCopyingConstructor(FieldClassDecl, Qualifiers::Const,
8694 &HasConstCopyConstructor);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008695 }
8696 }
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008697 // Otherwise, the implicitly declared copy constructor will have
8698 // the form
8699 //
8700 // X::X(X&)
Sean Hunt49634cf2011-05-13 06:10:58 +00008701
Douglas Gregor0d405db2010-07-01 20:59:04 +00008702 // C++ [except.spec]p14:
8703 // An implicitly declared special member function (Clause 12) shall have an
8704 // exception-specification. [...]
8705 ImplicitExceptionSpecification ExceptSpec(Context);
8706 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
8707 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8708 BaseEnd = ClassDecl->bases_end();
8709 Base != BaseEnd;
8710 ++Base) {
8711 // Virtual bases are handled below.
8712 if (Base->isVirtual())
8713 continue;
8714
Douglas Gregor22584312010-07-02 23:41:54 +00008715 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00008716 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00008717 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008718 LookupCopyingConstructor(BaseClassDecl, Quals))
Douglas Gregor0d405db2010-07-01 20:59:04 +00008719 ExceptSpec.CalledDecl(CopyConstructor);
8720 }
8721 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8722 BaseEnd = ClassDecl->vbases_end();
8723 Base != BaseEnd;
8724 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00008725 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00008726 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00008727 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008728 LookupCopyingConstructor(BaseClassDecl, Quals))
Douglas Gregor0d405db2010-07-01 20:59:04 +00008729 ExceptSpec.CalledDecl(CopyConstructor);
8730 }
8731 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8732 FieldEnd = ClassDecl->field_end();
8733 Field != FieldEnd;
8734 ++Field) {
8735 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Huntc530d172011-06-10 04:44:37 +00008736 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8737 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008738 LookupCopyingConstructor(FieldClassDecl, Quals))
Sean Huntc530d172011-06-10 04:44:37 +00008739 ExceptSpec.CalledDecl(CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00008740 }
8741 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008742
Sean Hunt49634cf2011-05-13 06:10:58 +00008743 return std::make_pair(ExceptSpec, HasConstCopyConstructor);
8744}
8745
8746CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
8747 CXXRecordDecl *ClassDecl) {
8748 // C++ [class.copy]p4:
8749 // If the class definition does not explicitly declare a copy
8750 // constructor, one is declared implicitly.
8751
8752 ImplicitExceptionSpecification Spec(Context);
8753 bool Const;
8754 llvm::tie(Spec, Const) =
8755 ComputeDefaultedCopyCtorExceptionSpecAndConst(ClassDecl);
8756
8757 QualType ClassType = Context.getTypeDeclType(ClassDecl);
8758 QualType ArgType = ClassType;
8759 if (Const)
8760 ArgType = ArgType.withConst();
8761 ArgType = Context.getLValueReferenceType(ArgType);
8762
8763 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8764
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008765 DeclarationName Name
8766 = Context.DeclarationNames.getCXXConstructorName(
8767 Context.getCanonicalType(ClassType));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008768 SourceLocation ClassLoc = ClassDecl->getLocation();
8769 DeclarationNameInfo NameInfo(Name, ClassLoc);
Sean Hunt49634cf2011-05-13 06:10:58 +00008770
8771 // An implicitly-declared copy constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00008772 // member of its class.
8773 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
8774 Context, ClassDecl, ClassLoc, NameInfo,
8775 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI), /*TInfo=*/0,
8776 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
8777 /*isConstexpr=*/ClassDecl->defaultedCopyConstructorIsConstexpr() &&
8778 getLangOptions().CPlusPlus0x);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008779 CopyConstructor->setAccess(AS_public);
Sean Hunt49634cf2011-05-13 06:10:58 +00008780 CopyConstructor->setDefaulted();
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008781 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
Richard Smith61802452011-12-22 02:22:31 +00008782
Douglas Gregor22584312010-07-02 23:41:54 +00008783 // Note that we have declared this constructor.
Douglas Gregor22584312010-07-02 23:41:54 +00008784 ++ASTContext::NumImplicitCopyConstructorsDeclared;
8785
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008786 // Add the parameter to the constructor.
8787 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008788 ClassLoc, ClassLoc,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008789 /*IdentifierInfo=*/0,
8790 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00008791 SC_None,
8792 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008793 CopyConstructor->setParams(FromParam);
Sean Hunt49634cf2011-05-13 06:10:58 +00008794
Douglas Gregor23c94db2010-07-02 17:43:08 +00008795 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor22584312010-07-02 23:41:54 +00008796 PushOnScopeChains(CopyConstructor, S, false);
8797 ClassDecl->addDecl(CopyConstructor);
Sean Hunt71a682f2011-05-18 03:41:58 +00008798
Nico Weberafcc96a2012-01-23 03:19:29 +00008799 // C++11 [class.copy]p8:
8800 // ... If the class definition does not explicitly declare a copy
8801 // constructor, there is no user-declared move constructor, and there is no
8802 // user-declared move assignment operator, a copy constructor is implicitly
8803 // declared as defaulted.
Sean Hunt1ccbc542011-06-22 01:05:13 +00008804 if (ClassDecl->hasUserDeclaredMoveConstructor() ||
Nico Weberafcc96a2012-01-23 03:19:29 +00008805 (ClassDecl->hasUserDeclaredMoveAssignment() &&
Nico Weber28976602012-01-23 04:01:33 +00008806 !getLangOptions().MicrosoftMode) ||
Sean Huntc32d6842011-10-11 04:55:36 +00008807 ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Sean Hunt71a682f2011-05-18 03:41:58 +00008808 CopyConstructor->setDeletedAsWritten();
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008809
8810 return CopyConstructor;
8811}
8812
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008813void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Sean Hunt49634cf2011-05-13 06:10:58 +00008814 CXXConstructorDecl *CopyConstructor) {
8815 assert((CopyConstructor->isDefaulted() &&
8816 CopyConstructor->isCopyConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00008817 !CopyConstructor->doesThisDeclarationHaveABody()) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008818 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00008819
Anders Carlsson63010a72010-04-23 16:24:12 +00008820 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008821 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008822
Douglas Gregor39957dc2010-05-01 15:04:51 +00008823 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008824 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008825
Sean Huntcbb67482011-01-08 20:30:50 +00008826 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008827 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00008828 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008829 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00008830 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008831 } else {
8832 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
8833 CopyConstructor->getLocation(),
8834 MultiStmtArg(*this, 0, 0),
8835 /*isStmtExpr=*/false)
8836 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00008837 CopyConstructor->setImplicitlyDefined(true);
Anders Carlsson8e142cc2010-04-25 00:52:09 +00008838 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008839
8840 CopyConstructor->setUsed();
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008841 if (ASTMutationListener *L = getASTMutationListener()) {
8842 L->CompletedImplicitDefinition(CopyConstructor);
8843 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008844}
8845
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008846Sema::ImplicitExceptionSpecification
8847Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
8848 // C++ [except.spec]p14:
8849 // An implicitly declared special member function (Clause 12) shall have an
8850 // exception-specification. [...]
8851 ImplicitExceptionSpecification ExceptSpec(Context);
8852 if (ClassDecl->isInvalidDecl())
8853 return ExceptSpec;
8854
8855 // Direct base-class constructors.
8856 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8857 BEnd = ClassDecl->bases_end();
8858 B != BEnd; ++B) {
8859 if (B->isVirtual()) // Handled below.
8860 continue;
8861
8862 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8863 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8864 CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl);
8865 // If this is a deleted function, add it anyway. This might be conformant
8866 // with the standard. This might not. I'm not sure. It might not matter.
8867 if (Constructor)
8868 ExceptSpec.CalledDecl(Constructor);
8869 }
8870 }
8871
8872 // Virtual base-class constructors.
8873 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8874 BEnd = ClassDecl->vbases_end();
8875 B != BEnd; ++B) {
8876 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8877 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8878 CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl);
8879 // If this is a deleted function, add it anyway. This might be conformant
8880 // with the standard. This might not. I'm not sure. It might not matter.
8881 if (Constructor)
8882 ExceptSpec.CalledDecl(Constructor);
8883 }
8884 }
8885
8886 // Field constructors.
8887 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8888 FEnd = ClassDecl->field_end();
8889 F != FEnd; ++F) {
Douglas Gregorf4853882011-11-28 20:03:15 +00008890 if (const RecordType *RecordTy
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008891 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8892 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8893 CXXConstructorDecl *Constructor = LookupMovingConstructor(FieldRecDecl);
8894 // If this is a deleted function, add it anyway. This might be conformant
8895 // with the standard. This might not. I'm not sure. It might not matter.
8896 // In particular, the problem is that this function never gets called. It
8897 // might just be ill-formed because this function attempts to refer to
8898 // a deleted function here.
8899 if (Constructor)
8900 ExceptSpec.CalledDecl(Constructor);
8901 }
8902 }
8903
8904 return ExceptSpec;
8905}
8906
8907CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
8908 CXXRecordDecl *ClassDecl) {
8909 ImplicitExceptionSpecification Spec(
8910 ComputeDefaultedMoveCtorExceptionSpec(ClassDecl));
8911
8912 QualType ClassType = Context.getTypeDeclType(ClassDecl);
8913 QualType ArgType = Context.getRValueReferenceType(ClassType);
8914
8915 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8916
8917 DeclarationName Name
8918 = Context.DeclarationNames.getCXXConstructorName(
8919 Context.getCanonicalType(ClassType));
8920 SourceLocation ClassLoc = ClassDecl->getLocation();
8921 DeclarationNameInfo NameInfo(Name, ClassLoc);
8922
8923 // C++0x [class.copy]p11:
8924 // An implicitly-declared copy/move constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00008925 // member of its class.
8926 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
8927 Context, ClassDecl, ClassLoc, NameInfo,
8928 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI), /*TInfo=*/0,
8929 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
8930 /*isConstexpr=*/ClassDecl->defaultedMoveConstructorIsConstexpr() &&
8931 getLangOptions().CPlusPlus0x);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008932 MoveConstructor->setAccess(AS_public);
8933 MoveConstructor->setDefaulted();
8934 MoveConstructor->setTrivial(ClassDecl->hasTrivialMoveConstructor());
Richard Smith61802452011-12-22 02:22:31 +00008935
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008936 // Add the parameter to the constructor.
8937 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
8938 ClassLoc, ClassLoc,
8939 /*IdentifierInfo=*/0,
8940 ArgType, /*TInfo=*/0,
8941 SC_None,
8942 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008943 MoveConstructor->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008944
8945 // C++0x [class.copy]p9:
8946 // If the definition of a class X does not explicitly declare a move
8947 // constructor, one will be implicitly declared as defaulted if and only if:
8948 // [...]
8949 // - the move constructor would not be implicitly defined as deleted.
Sean Hunt769bb2d2011-10-11 06:43:29 +00008950 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008951 // Cache this result so that we don't try to generate this over and over
8952 // on every lookup, leaking memory and wasting time.
8953 ClassDecl->setFailedImplicitMoveConstructor();
8954 return 0;
8955 }
8956
8957 // Note that we have declared this constructor.
8958 ++ASTContext::NumImplicitMoveConstructorsDeclared;
8959
8960 if (Scope *S = getScopeForContext(ClassDecl))
8961 PushOnScopeChains(MoveConstructor, S, false);
8962 ClassDecl->addDecl(MoveConstructor);
8963
8964 return MoveConstructor;
8965}
8966
8967void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
8968 CXXConstructorDecl *MoveConstructor) {
8969 assert((MoveConstructor->isDefaulted() &&
8970 MoveConstructor->isMoveConstructor() &&
8971 !MoveConstructor->doesThisDeclarationHaveABody()) &&
8972 "DefineImplicitMoveConstructor - call it for implicit move ctor");
8973
8974 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
8975 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
8976
8977 ImplicitlyDefinedFunctionScope Scope(*this, MoveConstructor);
8978 DiagnosticErrorTrap Trap(Diags);
8979
8980 if (SetCtorInitializers(MoveConstructor, 0, 0, /*AnyErrors=*/false) ||
8981 Trap.hasErrorOccurred()) {
8982 Diag(CurrentLocation, diag::note_member_synthesized_at)
8983 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
8984 MoveConstructor->setInvalidDecl();
8985 } else {
8986 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
8987 MoveConstructor->getLocation(),
8988 MultiStmtArg(*this, 0, 0),
8989 /*isStmtExpr=*/false)
8990 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00008991 MoveConstructor->setImplicitlyDefined(true);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008992 }
8993
8994 MoveConstructor->setUsed();
8995
8996 if (ASTMutationListener *L = getASTMutationListener()) {
8997 L->CompletedImplicitDefinition(MoveConstructor);
8998 }
8999}
9000
John McCall60d7b3a2010-08-24 06:29:42 +00009001ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00009002Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00009003 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00009004 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009005 bool HadMultipleCandidates,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009006 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009007 unsigned ConstructKind,
9008 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009009 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00009010
Douglas Gregor2f599792010-04-02 18:24:57 +00009011 // C++0x [class.copy]p34:
9012 // When certain criteria are met, an implementation is allowed to
9013 // omit the copy/move construction of a class object, even if the
9014 // copy/move constructor and/or destructor for the object have
9015 // side effects. [...]
9016 // - when a temporary class object that has not been bound to a
9017 // reference (12.2) would be copied/moved to a class object
9018 // with the same cv-unqualified type, the copy/move operation
9019 // can be omitted by constructing the temporary object
9020 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +00009021 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregor70a21de2011-01-27 23:24:55 +00009022 Constructor->isCopyOrMoveConstructor() && ExprArgs.size() >= 1) {
Douglas Gregor2f599792010-04-02 18:24:57 +00009023 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
John McCall558d2ab2010-09-15 10:14:12 +00009024 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009025 }
Mike Stump1eb44332009-09-09 15:08:12 +00009026
9027 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009028 Elidable, move(ExprArgs), HadMultipleCandidates,
9029 RequiresZeroInit, ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009030}
9031
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009032/// BuildCXXConstructExpr - Creates a complete call to a constructor,
9033/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00009034ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00009035Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
9036 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00009037 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009038 bool HadMultipleCandidates,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009039 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009040 unsigned ConstructKind,
9041 SourceRange ParenRange) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00009042 unsigned NumExprs = ExprArgs.size();
9043 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00009044
Nick Lewycky909a70d2011-03-25 01:44:32 +00009045 for (specific_attr_iterator<NonNullAttr>
9046 i = Constructor->specific_attr_begin<NonNullAttr>(),
9047 e = Constructor->specific_attr_end<NonNullAttr>(); i != e; ++i) {
9048 const NonNullAttr *NonNull = *i;
9049 CheckNonNullArguments(NonNull, ExprArgs.get(), ConstructLoc);
9050 }
9051
Eli Friedman5f2987c2012-02-02 03:46:19 +00009052 MarkFunctionReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00009053 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009054 Constructor, Elidable, Exprs, NumExprs,
9055 HadMultipleCandidates, RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009056 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
9057 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009058}
9059
Mike Stump1eb44332009-09-09 15:08:12 +00009060bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009061 CXXConstructorDecl *Constructor,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009062 MultiExprArg Exprs,
9063 bool HadMultipleCandidates) {
Chandler Carruth428edaf2010-10-25 08:47:36 +00009064 // FIXME: Provide the correct paren SourceRange when available.
John McCall60d7b3a2010-08-24 06:29:42 +00009065 ExprResult TempResult =
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00009066 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009067 move(Exprs), HadMultipleCandidates, false,
9068 CXXConstructExpr::CK_Complete, SourceRange());
Anders Carlssonfe2de492009-08-25 05:18:00 +00009069 if (TempResult.isInvalid())
9070 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00009071
Anders Carlssonda3f4e22009-08-25 05:12:04 +00009072 Expr *Temp = TempResult.takeAs<Expr>();
John McCallb4eb64d2010-10-08 02:01:28 +00009073 CheckImplicitConversions(Temp, VD->getLocation());
Eli Friedman5f2987c2012-02-02 03:46:19 +00009074 MarkFunctionReferenced(VD->getLocation(), Constructor);
John McCall4765fa02010-12-06 08:20:24 +00009075 Temp = MaybeCreateExprWithCleanups(Temp);
Douglas Gregor838db382010-02-11 01:19:42 +00009076 VD->setInit(Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00009077
Anders Carlssonfe2de492009-08-25 05:18:00 +00009078 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00009079}
9080
John McCall68c6c9a2010-02-02 09:10:11 +00009081void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009082 if (VD->isInvalidDecl()) return;
9083
John McCall68c6c9a2010-02-02 09:10:11 +00009084 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009085 if (ClassDecl->isInvalidDecl()) return;
9086 if (ClassDecl->hasTrivialDestructor()) return;
9087 if (ClassDecl->isDependentContext()) return;
John McCall626e96e2010-08-01 20:20:59 +00009088
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009089 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedman5f2987c2012-02-02 03:46:19 +00009090 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009091 CheckDestructorAccess(VD->getLocation(), Destructor,
9092 PDiag(diag::err_access_dtor_var)
9093 << VD->getDeclName()
9094 << VD->getType());
Anders Carlsson2b32dad2011-03-24 01:01:41 +00009095
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009096 if (!VD->hasGlobalStorage()) return;
9097
9098 // Emit warning for non-trivial dtor in global scope (a real global,
9099 // class-static, function-static).
9100 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
9101
9102 // TODO: this should be re-enabled for static locals by !CXAAtExit
9103 if (!VD->isStaticLocal())
9104 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00009105}
9106
Mike Stump1eb44332009-09-09 15:08:12 +00009107/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00009108/// ActOnDeclarator, when a C++ direct initializer is present.
9109/// e.g: "int x(1);"
John McCalld226f652010-08-21 09:40:31 +00009110void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl,
Chris Lattnerb28317a2009-03-28 19:18:32 +00009111 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +00009112 MultiExprArg Exprs,
Richard Smith34b41d92011-02-20 03:19:35 +00009113 SourceLocation RParenLoc,
9114 bool TypeMayContainAuto) {
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00009115 // If there is no declaration, there was an error parsing it. Just ignore
9116 // the initializer.
Chris Lattnerb28317a2009-03-28 19:18:32 +00009117 if (RealDecl == 0)
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00009118 return;
Mike Stump1eb44332009-09-09 15:08:12 +00009119
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00009120 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
9121 if (!VDecl) {
9122 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
9123 RealDecl->setInvalidDecl();
9124 return;
9125 }
9126
Eli Friedman6aeaa602012-01-05 22:34:08 +00009127 // C++0x [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for.
Richard Smith34b41d92011-02-20 03:19:35 +00009128 if (TypeMayContainAuto && VDecl->getType()->getContainedAutoType()) {
Eli Friedman6aeaa602012-01-05 22:34:08 +00009129 if (Exprs.size() == 0) {
9130 // It isn't possible to write this directly, but it is possible to
9131 // end up in this situation with "auto x(some_pack...);"
9132 Diag(LParenLoc, diag::err_auto_var_init_no_expression)
9133 << VDecl->getDeclName() << VDecl->getType()
9134 << VDecl->getSourceRange();
9135 RealDecl->setInvalidDecl();
9136 return;
9137 }
9138
Richard Smith34b41d92011-02-20 03:19:35 +00009139 if (Exprs.size() > 1) {
9140 Diag(Exprs.get()[1]->getSourceRange().getBegin(),
9141 diag::err_auto_var_init_multiple_expressions)
9142 << VDecl->getDeclName() << VDecl->getType()
9143 << VDecl->getSourceRange();
9144 RealDecl->setInvalidDecl();
9145 return;
9146 }
9147
9148 Expr *Init = Exprs.get()[0];
Richard Smitha085da82011-03-17 16:11:59 +00009149 TypeSourceInfo *DeducedType = 0;
Sebastian Redlb832f6d2012-01-23 22:09:39 +00009150 if (DeduceAutoType(VDecl->getTypeSourceInfo(), Init, DeducedType) ==
9151 DAR_Failed)
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00009152 DiagnoseAutoDeductionFailure(VDecl, Init);
Richard Smitha085da82011-03-17 16:11:59 +00009153 if (!DeducedType) {
Richard Smith34b41d92011-02-20 03:19:35 +00009154 RealDecl->setInvalidDecl();
9155 return;
9156 }
Richard Smitha085da82011-03-17 16:11:59 +00009157 VDecl->setTypeSourceInfo(DeducedType);
9158 VDecl->setType(DeducedType->getType());
Richard Smith34b41d92011-02-20 03:19:35 +00009159
John McCallf85e1932011-06-15 23:02:42 +00009160 // In ARC, infer lifetime.
9161 if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
9162 VDecl->setInvalidDecl();
9163
Richard Smith34b41d92011-02-20 03:19:35 +00009164 // If this is a redeclaration, check that the type we just deduced matches
9165 // the previously declared type.
Douglas Gregoref96ee02012-01-14 16:38:05 +00009166 if (VarDecl *Old = VDecl->getPreviousDecl())
Richard Smith34b41d92011-02-20 03:19:35 +00009167 MergeVarDeclTypes(VDecl, Old);
9168 }
9169
Douglas Gregor83ddad32009-08-26 21:14:46 +00009170 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00009171 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00009172 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
9173 //
9174 // Clients that want to distinguish between the two forms, can check for
9175 // direct initializer using VarDecl::hasCXXDirectInitializer().
9176 // A major benefit is that clients that don't particularly care about which
9177 // exactly form was it (like the CodeGen) can handle both cases without
9178 // special case code.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00009179
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00009180 // C++ 8.5p11:
9181 // The form of initialization (using parentheses or '=') is generally
9182 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00009183 // class type.
9184
Douglas Gregor4dffad62010-02-11 22:55:30 +00009185 if (!VDecl->getType()->isDependentType() &&
Douglas Gregord24c3062011-10-10 16:05:18 +00009186 !VDecl->getType()->isIncompleteArrayType() &&
Douglas Gregor4dffad62010-02-11 22:55:30 +00009187 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor615c5d42009-03-24 16:43:20 +00009188 diag::err_typecheck_decl_incomplete_type)) {
9189 VDecl->setInvalidDecl();
9190 return;
9191 }
9192
Douglas Gregor90f93822009-12-22 22:17:25 +00009193 // The variable can not have an abstract class type.
9194 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
9195 diag::err_abstract_type_in_decl,
9196 AbstractVariableType))
9197 VDecl->setInvalidDecl();
9198
Sebastian Redl31310a22010-02-01 20:16:42 +00009199 const VarDecl *Def;
9200 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregor90f93822009-12-22 22:17:25 +00009201 Diag(VDecl->getLocation(), diag::err_redefinition)
9202 << VDecl->getDeclName();
9203 Diag(Def->getLocation(), diag::note_previous_definition);
9204 VDecl->setInvalidDecl();
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00009205 return;
9206 }
Douglas Gregor4dffad62010-02-11 22:55:30 +00009207
Douglas Gregor3a91abf2010-08-24 05:27:49 +00009208 // C++ [class.static.data]p4
9209 // If a static data member is of const integral or const
9210 // enumeration type, its declaration in the class definition can
9211 // specify a constant-initializer which shall be an integral
9212 // constant expression (5.19). In that case, the member can appear
9213 // in integral constant expressions. The member shall still be
9214 // defined in a namespace scope if it is used in the program and the
9215 // namespace scope definition shall not contain an initializer.
9216 //
9217 // We already performed a redefinition check above, but for static
9218 // data members we also need to check whether there was an in-class
9219 // declaration with an initializer.
9220 const VarDecl* PrevInit = 0;
9221 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
9222 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
9223 Diag(PrevInit->getLocation(), diag::note_previous_definition);
9224 return;
9225 }
9226
Eli Friedman7badd242012-02-09 20:13:14 +00009227 if (VDecl->hasLocalStorage())
9228 getCurFunction()->setHasBranchProtectedScope();
9229
Douglas Gregora31040f2010-12-16 01:31:22 +00009230 bool IsDependent = false;
9231 for (unsigned I = 0, N = Exprs.size(); I != N; ++I) {
9232 if (DiagnoseUnexpandedParameterPack(Exprs.get()[I], UPPC_Expression)) {
9233 VDecl->setInvalidDecl();
9234 return;
9235 }
9236
9237 if (Exprs.get()[I]->isTypeDependent())
9238 IsDependent = true;
9239 }
9240
Douglas Gregor4dffad62010-02-11 22:55:30 +00009241 // If either the declaration has a dependent type or if any of the
9242 // expressions is type-dependent, we represent the initialization
9243 // via a ParenListExpr for later use during template instantiation.
Douglas Gregora31040f2010-12-16 01:31:22 +00009244 if (VDecl->getType()->isDependentType() || IsDependent) {
Douglas Gregor4dffad62010-02-11 22:55:30 +00009245 // Let clients know that initialization was done with a direct initializer.
9246 VDecl->setCXXDirectInitializer(true);
9247
9248 // Store the initialization expressions as a ParenListExpr.
9249 unsigned NumExprs = Exprs.size();
Manuel Klimek0d9106f2011-06-22 20:02:16 +00009250 VDecl->setInit(new (Context) ParenListExpr(
9251 Context, LParenLoc, (Expr **)Exprs.release(), NumExprs, RParenLoc,
9252 VDecl->getType().getNonReferenceType()));
Douglas Gregor4dffad62010-02-11 22:55:30 +00009253 return;
9254 }
Douglas Gregor90f93822009-12-22 22:17:25 +00009255
9256 // Capture the variable that is being initialized and the style of
9257 // initialization.
9258 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
9259
9260 // FIXME: Poor source location information.
9261 InitializationKind Kind
9262 = InitializationKind::CreateDirect(VDecl->getLocation(),
9263 LParenLoc, RParenLoc);
9264
Douglas Gregord24c3062011-10-10 16:05:18 +00009265 QualType T = VDecl->getType();
Douglas Gregor90f93822009-12-22 22:17:25 +00009266 InitializationSequence InitSeq(*this, Entity, Kind,
John McCall9ae2f072010-08-23 23:25:46 +00009267 Exprs.get(), Exprs.size());
Douglas Gregord24c3062011-10-10 16:05:18 +00009268 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs), &T);
Douglas Gregor90f93822009-12-22 22:17:25 +00009269 if (Result.isInvalid()) {
9270 VDecl->setInvalidDecl();
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00009271 return;
Douglas Gregord24c3062011-10-10 16:05:18 +00009272 } else if (T != VDecl->getType()) {
9273 VDecl->setType(T);
9274 Result.get()->setType(T);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00009275 }
John McCallb4eb64d2010-10-08 02:01:28 +00009276
Douglas Gregord24c3062011-10-10 16:05:18 +00009277
Richard Smithc6d990a2011-09-29 19:11:37 +00009278 Expr *Init = Result.get();
9279 CheckImplicitConversions(Init, LParenLoc);
Richard Smithc6d990a2011-09-29 19:11:37 +00009280
9281 Init = MaybeCreateExprWithCleanups(Init);
9282 VDecl->setInit(Init);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00009283 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00009284
John McCall2998d6b2011-01-19 11:48:09 +00009285 CheckCompleteVariableDeclaration(VDecl);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00009286}
Douglas Gregor27c8dc02008-10-29 00:13:59 +00009287
Douglas Gregor39da0b82009-09-09 23:08:42 +00009288/// \brief Given a constructor and the set of arguments provided for the
9289/// constructor, convert the arguments and add any required default arguments
9290/// to form a proper call to this constructor.
9291///
9292/// \returns true if an error occurred, false otherwise.
9293bool
9294Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
9295 MultiExprArg ArgsPtr,
9296 SourceLocation Loc,
John McCallca0408f2010-08-23 06:44:23 +00009297 ASTOwningVector<Expr*> &ConvertedArgs) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00009298 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
9299 unsigned NumArgs = ArgsPtr.size();
9300 Expr **Args = (Expr **)ArgsPtr.get();
9301
9302 const FunctionProtoType *Proto
9303 = Constructor->getType()->getAs<FunctionProtoType>();
9304 assert(Proto && "Constructor without a prototype?");
9305 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00009306
9307 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009308 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00009309 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009310 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00009311 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009312
9313 VariadicCallType CallType =
9314 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner5f9e2722011-07-23 10:55:15 +00009315 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009316 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
9317 Proto, 0, Args, NumArgs, AllArgs,
9318 CallType);
9319 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
9320 ConvertedArgs.push_back(AllArgs[i]);
9321 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00009322}
9323
Anders Carlsson20d45d22009-12-12 00:32:00 +00009324static inline bool
9325CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
9326 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00009327 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +00009328 if (isa<NamespaceDecl>(DC)) {
9329 return SemaRef.Diag(FnDecl->getLocation(),
9330 diag::err_operator_new_delete_declared_in_namespace)
9331 << FnDecl->getDeclName();
9332 }
9333
9334 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +00009335 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00009336 return SemaRef.Diag(FnDecl->getLocation(),
9337 diag::err_operator_new_delete_declared_static)
9338 << FnDecl->getDeclName();
9339 }
9340
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00009341 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00009342}
9343
Anders Carlsson156c78e2009-12-13 17:53:43 +00009344static inline bool
9345CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
9346 CanQualType ExpectedResultType,
9347 CanQualType ExpectedFirstParamType,
9348 unsigned DependentParamTypeDiag,
9349 unsigned InvalidParamTypeDiag) {
9350 QualType ResultType =
9351 FnDecl->getType()->getAs<FunctionType>()->getResultType();
9352
9353 // Check that the result type is not dependent.
9354 if (ResultType->isDependentType())
9355 return SemaRef.Diag(FnDecl->getLocation(),
9356 diag::err_operator_new_delete_dependent_result_type)
9357 << FnDecl->getDeclName() << ExpectedResultType;
9358
9359 // Check that the result type is what we expect.
9360 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
9361 return SemaRef.Diag(FnDecl->getLocation(),
9362 diag::err_operator_new_delete_invalid_result_type)
9363 << FnDecl->getDeclName() << ExpectedResultType;
9364
9365 // A function template must have at least 2 parameters.
9366 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
9367 return SemaRef.Diag(FnDecl->getLocation(),
9368 diag::err_operator_new_delete_template_too_few_parameters)
9369 << FnDecl->getDeclName();
9370
9371 // The function decl must have at least 1 parameter.
9372 if (FnDecl->getNumParams() == 0)
9373 return SemaRef.Diag(FnDecl->getLocation(),
9374 diag::err_operator_new_delete_too_few_parameters)
9375 << FnDecl->getDeclName();
9376
9377 // Check the the first parameter type is not dependent.
9378 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
9379 if (FirstParamType->isDependentType())
9380 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
9381 << FnDecl->getDeclName() << ExpectedFirstParamType;
9382
9383 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +00009384 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +00009385 ExpectedFirstParamType)
9386 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
9387 << FnDecl->getDeclName() << ExpectedFirstParamType;
9388
9389 return false;
9390}
9391
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009392static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +00009393CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00009394 // C++ [basic.stc.dynamic.allocation]p1:
9395 // A program is ill-formed if an allocation function is declared in a
9396 // namespace scope other than global scope or declared static in global
9397 // scope.
9398 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9399 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +00009400
9401 CanQualType SizeTy =
9402 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
9403
9404 // C++ [basic.stc.dynamic.allocation]p1:
9405 // The return type shall be void*. The first parameter shall have type
9406 // std::size_t.
9407 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
9408 SizeTy,
9409 diag::err_operator_new_dependent_param_type,
9410 diag::err_operator_new_param_type))
9411 return true;
9412
9413 // C++ [basic.stc.dynamic.allocation]p1:
9414 // The first parameter shall not have an associated default argument.
9415 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +00009416 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +00009417 diag::err_operator_new_default_arg)
9418 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
9419
9420 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +00009421}
9422
9423static bool
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009424CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
9425 // C++ [basic.stc.dynamic.deallocation]p1:
9426 // A program is ill-formed if deallocation functions are declared in a
9427 // namespace scope other than global scope or declared static in global
9428 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +00009429 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9430 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009431
9432 // C++ [basic.stc.dynamic.deallocation]p2:
9433 // Each deallocation function shall return void and its first parameter
9434 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +00009435 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
9436 SemaRef.Context.VoidPtrTy,
9437 diag::err_operator_delete_dependent_param_type,
9438 diag::err_operator_delete_param_type))
9439 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009440
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009441 return false;
9442}
9443
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009444/// CheckOverloadedOperatorDeclaration - Check whether the declaration
9445/// of this overloaded operator is well-formed. If so, returns false;
9446/// otherwise, emits appropriate diagnostics and returns true.
9447bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009448 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009449 "Expected an overloaded operator declaration");
9450
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009451 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
9452
Mike Stump1eb44332009-09-09 15:08:12 +00009453 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009454 // The allocation and deallocation functions, operator new,
9455 // operator new[], operator delete and operator delete[], are
9456 // described completely in 3.7.3. The attributes and restrictions
9457 // found in the rest of this subclause do not apply to them unless
9458 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +00009459 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009460 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00009461
Anders Carlssona3ccda52009-12-12 00:26:23 +00009462 if (Op == OO_New || Op == OO_Array_New)
9463 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009464
9465 // C++ [over.oper]p6:
9466 // An operator function shall either be a non-static member
9467 // function or be a non-member function and have at least one
9468 // parameter whose type is a class, a reference to a class, an
9469 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009470 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
9471 if (MethodDecl->isStatic())
9472 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009473 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009474 } else {
9475 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009476 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
9477 ParamEnd = FnDecl->param_end();
9478 Param != ParamEnd; ++Param) {
9479 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00009480 if (ParamType->isDependentType() || ParamType->isRecordType() ||
9481 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009482 ClassOrEnumParam = true;
9483 break;
9484 }
9485 }
9486
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009487 if (!ClassOrEnumParam)
9488 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009489 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009490 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009491 }
9492
9493 // C++ [over.oper]p8:
9494 // An operator function cannot have default arguments (8.3.6),
9495 // except where explicitly stated below.
9496 //
Mike Stump1eb44332009-09-09 15:08:12 +00009497 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009498 // (C++ [over.call]p1).
9499 if (Op != OO_Call) {
9500 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
9501 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +00009502 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00009503 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00009504 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +00009505 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009506 }
9507 }
9508
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009509 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
9510 { false, false, false }
9511#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
9512 , { Unary, Binary, MemberOnly }
9513#include "clang/Basic/OperatorKinds.def"
9514 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009515
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009516 bool CanBeUnaryOperator = OperatorUses[Op][0];
9517 bool CanBeBinaryOperator = OperatorUses[Op][1];
9518 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009519
9520 // C++ [over.oper]p8:
9521 // [...] Operator functions cannot have more or fewer parameters
9522 // than the number required for the corresponding operator, as
9523 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00009524 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009525 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009526 if (Op != OO_Call &&
9527 ((NumParams == 1 && !CanBeUnaryOperator) ||
9528 (NumParams == 2 && !CanBeBinaryOperator) ||
9529 (NumParams < 1) || (NumParams > 2))) {
9530 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00009531 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009532 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00009533 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009534 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00009535 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009536 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00009537 assert(CanBeBinaryOperator &&
9538 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00009539 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009540 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009541
Chris Lattner416e46f2008-11-21 07:57:12 +00009542 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009543 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009544 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00009545
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009546 // Overloaded operators other than operator() cannot be variadic.
9547 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00009548 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009549 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009550 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009551 }
9552
9553 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009554 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
9555 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009556 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009557 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009558 }
9559
9560 // C++ [over.inc]p1:
9561 // The user-defined function called operator++ implements the
9562 // prefix and postfix ++ operator. If this function is a member
9563 // function with no parameters, or a non-member function with one
9564 // parameter of class or enumeration type, it defines the prefix
9565 // increment operator ++ for objects of that type. If the function
9566 // is a member function with one parameter (which shall be of type
9567 // int) or a non-member function with two parameters (the second
9568 // of which shall be of type int), it defines the postfix
9569 // increment operator ++ for objects of that type.
9570 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
9571 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
9572 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00009573 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009574 ParamIsInt = BT->getKind() == BuiltinType::Int;
9575
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00009576 if (!ParamIsInt)
9577 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00009578 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00009579 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009580 }
9581
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009582 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009583}
Chris Lattner5a003a42008-12-17 07:09:26 +00009584
Sean Hunta6c058d2010-01-13 09:01:02 +00009585/// CheckLiteralOperatorDeclaration - Check whether the declaration
9586/// of this literal operator function is well-formed. If so, returns
9587/// false; otherwise, emits appropriate diagnostics and returns true.
9588bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
9589 DeclContext *DC = FnDecl->getDeclContext();
9590 Decl::Kind Kind = DC->getDeclKind();
9591 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
9592 Kind != Decl::LinkageSpec) {
9593 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
9594 << FnDecl->getDeclName();
9595 return true;
9596 }
9597
9598 bool Valid = false;
9599
Sean Hunt216c2782010-04-07 23:11:06 +00009600 // template <char...> type operator "" name() is the only valid template
9601 // signature, and the only valid signature with no parameters.
9602 if (FnDecl->param_size() == 0) {
9603 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
9604 // Must have only one template parameter
9605 TemplateParameterList *Params = TpDecl->getTemplateParameters();
9606 if (Params->size() == 1) {
9607 NonTypeTemplateParmDecl *PmDecl =
9608 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +00009609
Sean Hunt216c2782010-04-07 23:11:06 +00009610 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +00009611 if (PmDecl && PmDecl->isTemplateParameterPack() &&
9612 Context.hasSameType(PmDecl->getType(), Context.CharTy))
9613 Valid = true;
9614 }
9615 }
9616 } else {
Sean Hunta6c058d2010-01-13 09:01:02 +00009617 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +00009618 FunctionDecl::param_iterator Param = FnDecl->param_begin();
9619
Sean Hunta6c058d2010-01-13 09:01:02 +00009620 QualType T = (*Param)->getType();
9621
Sean Hunt30019c02010-04-07 22:57:35 +00009622 // unsigned long long int, long double, and any character type are allowed
9623 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +00009624 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
9625 Context.hasSameType(T, Context.LongDoubleTy) ||
9626 Context.hasSameType(T, Context.CharTy) ||
9627 Context.hasSameType(T, Context.WCharTy) ||
9628 Context.hasSameType(T, Context.Char16Ty) ||
9629 Context.hasSameType(T, Context.Char32Ty)) {
9630 if (++Param == FnDecl->param_end())
9631 Valid = true;
9632 goto FinishedParams;
9633 }
9634
Sean Hunt30019c02010-04-07 22:57:35 +00009635 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +00009636 const PointerType *PT = T->getAs<PointerType>();
9637 if (!PT)
9638 goto FinishedParams;
9639 T = PT->getPointeeType();
9640 if (!T.isConstQualified())
9641 goto FinishedParams;
9642 T = T.getUnqualifiedType();
9643
9644 // Move on to the second parameter;
9645 ++Param;
9646
9647 // If there is no second parameter, the first must be a const char *
9648 if (Param == FnDecl->param_end()) {
9649 if (Context.hasSameType(T, Context.CharTy))
9650 Valid = true;
9651 goto FinishedParams;
9652 }
9653
9654 // const char *, const wchar_t*, const char16_t*, and const char32_t*
9655 // are allowed as the first parameter to a two-parameter function
9656 if (!(Context.hasSameType(T, Context.CharTy) ||
9657 Context.hasSameType(T, Context.WCharTy) ||
9658 Context.hasSameType(T, Context.Char16Ty) ||
9659 Context.hasSameType(T, Context.Char32Ty)))
9660 goto FinishedParams;
9661
9662 // The second and final parameter must be an std::size_t
9663 T = (*Param)->getType().getUnqualifiedType();
9664 if (Context.hasSameType(T, Context.getSizeType()) &&
9665 ++Param == FnDecl->param_end())
9666 Valid = true;
9667 }
9668
9669 // FIXME: This diagnostic is absolutely terrible.
9670FinishedParams:
9671 if (!Valid) {
9672 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
9673 << FnDecl->getDeclName();
9674 return true;
9675 }
9676
Douglas Gregor1155c422011-08-30 22:40:35 +00009677 StringRef LiteralName
9678 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
9679 if (LiteralName[0] != '_') {
9680 // C++0x [usrlit.suffix]p1:
9681 // Literal suffix identifiers that do not start with an underscore are
9682 // reserved for future standardization.
9683 bool IsHexFloat = true;
9684 if (LiteralName.size() > 1 &&
9685 (LiteralName[0] == 'P' || LiteralName[0] == 'p')) {
9686 for (unsigned I = 1, N = LiteralName.size(); I < N; ++I) {
9687 if (!isdigit(LiteralName[I])) {
9688 IsHexFloat = false;
9689 break;
9690 }
9691 }
9692 }
9693
9694 if (IsHexFloat)
9695 Diag(FnDecl->getLocation(), diag::warn_user_literal_hexfloat)
9696 << LiteralName;
9697 else
9698 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
9699 }
9700
Sean Hunta6c058d2010-01-13 09:01:02 +00009701 return false;
9702}
9703
Douglas Gregor074149e2009-01-05 19:45:36 +00009704/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
9705/// linkage specification, including the language and (if present)
9706/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
9707/// the location of the language string literal, which is provided
9708/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
9709/// the '{' brace. Otherwise, this linkage specification does not
9710/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +00009711Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
9712 SourceLocation LangLoc,
Chris Lattner5f9e2722011-07-23 10:55:15 +00009713 StringRef Lang,
Chris Lattner7d642712010-11-09 20:15:55 +00009714 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00009715 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +00009716 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00009717 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +00009718 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00009719 Language = LinkageSpecDecl::lang_cxx;
9720 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00009721 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +00009722 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +00009723 }
Mike Stump1eb44332009-09-09 15:08:12 +00009724
Chris Lattnercc98eac2008-12-17 07:13:27 +00009725 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +00009726
Douglas Gregor074149e2009-01-05 19:45:36 +00009727 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009728 ExternLoc, LangLoc, Language);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009729 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00009730 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +00009731 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +00009732}
9733
Abramo Bagnara35f9a192010-07-30 16:47:02 +00009734/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +00009735/// the C++ linkage specification LinkageSpec. If RBraceLoc is
9736/// valid, it's the position of the closing '}' brace in a linkage
9737/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +00009738Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +00009739 Decl *LinkageSpec,
9740 SourceLocation RBraceLoc) {
9741 if (LinkageSpec) {
9742 if (RBraceLoc.isValid()) {
9743 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
9744 LSDecl->setRBraceLoc(RBraceLoc);
9745 }
Douglas Gregor074149e2009-01-05 19:45:36 +00009746 PopDeclContext();
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +00009747 }
Douglas Gregor074149e2009-01-05 19:45:36 +00009748 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00009749}
9750
Douglas Gregord308e622009-05-18 20:51:54 +00009751/// \brief Perform semantic analysis for the variable declaration that
9752/// occurs within a C++ catch clause, returning the newly-created
9753/// variable.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009754VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +00009755 TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009756 SourceLocation StartLoc,
9757 SourceLocation Loc,
9758 IdentifierInfo *Name) {
Douglas Gregord308e622009-05-18 20:51:54 +00009759 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +00009760 QualType ExDeclType = TInfo->getType();
9761
Sebastian Redl4b07b292008-12-22 19:15:10 +00009762 // Arrays and functions decay.
9763 if (ExDeclType->isArrayType())
9764 ExDeclType = Context.getArrayDecayedType(ExDeclType);
9765 else if (ExDeclType->isFunctionType())
9766 ExDeclType = Context.getPointerType(ExDeclType);
9767
9768 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
9769 // The exception-declaration shall not denote a pointer or reference to an
9770 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009771 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +00009772 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +00009773 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009774 Invalid = true;
9775 }
Douglas Gregord308e622009-05-18 20:51:54 +00009776
Sebastian Redl4b07b292008-12-22 19:15:10 +00009777 QualType BaseType = ExDeclType;
9778 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00009779 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +00009780 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009781 BaseType = Ptr->getPointeeType();
9782 Mode = 1;
Douglas Gregorecd7b042012-01-24 19:01:26 +00009783 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +00009784 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009785 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00009786 BaseType = Ref->getPointeeType();
9787 Mode = 2;
Douglas Gregorecd7b042012-01-24 19:01:26 +00009788 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009789 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009790 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregorecd7b042012-01-24 19:01:26 +00009791 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +00009792 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009793
Mike Stump1eb44332009-09-09 15:08:12 +00009794 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +00009795 RequireNonAbstractType(Loc, ExDeclType,
9796 diag::err_abstract_type_in_decl,
9797 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00009798 Invalid = true;
9799
John McCall5a180392010-07-24 00:37:23 +00009800 // Only the non-fragile NeXT runtime currently supports C++ catches
9801 // of ObjC types, and no runtime supports catching ObjC types by value.
9802 if (!Invalid && getLangOptions().ObjC1) {
9803 QualType T = ExDeclType;
9804 if (const ReferenceType *RT = T->getAs<ReferenceType>())
9805 T = RT->getPointeeType();
9806
9807 if (T->isObjCObjectType()) {
9808 Diag(Loc, diag::err_objc_object_catch);
9809 Invalid = true;
9810 } else if (T->isObjCObjectPointerType()) {
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +00009811 if (!getLangOptions().ObjCNonFragileABI)
9812 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall5a180392010-07-24 00:37:23 +00009813 }
9814 }
9815
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009816 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
9817 ExDeclType, TInfo, SC_None, SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +00009818 ExDecl->setExceptionVariable(true);
9819
Douglas Gregor9aab9c42011-12-10 01:22:52 +00009820 // In ARC, infer 'retaining' for variables of retainable type.
9821 if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
9822 Invalid = true;
9823
Douglas Gregorc41b8782011-07-06 18:14:43 +00009824 if (!Invalid && !ExDeclType->isDependentType()) {
John McCalle996ffd2011-02-16 08:02:54 +00009825 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
Douglas Gregor6d182892010-03-05 23:38:39 +00009826 // C++ [except.handle]p16:
9827 // The object declared in an exception-declaration or, if the
9828 // exception-declaration does not specify a name, a temporary (12.2) is
9829 // copy-initialized (8.5) from the exception object. [...]
9830 // The object is destroyed when the handler exits, after the destruction
9831 // of any automatic objects initialized within the handler.
9832 //
9833 // We just pretend to initialize the object with itself, then make sure
9834 // it can be destroyed later.
John McCalle996ffd2011-02-16 08:02:54 +00009835 QualType initType = ExDeclType;
9836
9837 InitializedEntity entity =
9838 InitializedEntity::InitializeVariable(ExDecl);
9839 InitializationKind initKind =
9840 InitializationKind::CreateCopy(Loc, SourceLocation());
9841
9842 Expr *opaqueValue =
9843 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
9844 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
9845 ExprResult result = sequence.Perform(*this, entity, initKind,
9846 MultiExprArg(&opaqueValue, 1));
9847 if (result.isInvalid())
Douglas Gregor6d182892010-03-05 23:38:39 +00009848 Invalid = true;
John McCalle996ffd2011-02-16 08:02:54 +00009849 else {
9850 // If the constructor used was non-trivial, set this as the
9851 // "initializer".
9852 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
9853 if (!construct->getConstructor()->isTrivial()) {
9854 Expr *init = MaybeCreateExprWithCleanups(construct);
9855 ExDecl->setInit(init);
9856 }
9857
9858 // And make sure it's destructable.
9859 FinalizeVarWithDestructor(ExDecl, recordType);
9860 }
Douglas Gregor6d182892010-03-05 23:38:39 +00009861 }
9862 }
9863
Douglas Gregord308e622009-05-18 20:51:54 +00009864 if (Invalid)
9865 ExDecl->setInvalidDecl();
9866
9867 return ExDecl;
9868}
9869
9870/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
9871/// handler.
John McCalld226f652010-08-21 09:40:31 +00009872Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +00009873 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +00009874 bool Invalid = D.isInvalidType();
9875
9876 // Check for unexpanded parameter packs.
9877 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
9878 UPPC_ExceptionType)) {
9879 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
9880 D.getIdentifierLoc());
9881 Invalid = true;
9882 }
9883
Sebastian Redl4b07b292008-12-22 19:15:10 +00009884 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +00009885 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +00009886 LookupOrdinaryName,
9887 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009888 // The scope should be freshly made just for us. There is just no way
9889 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +00009890 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +00009891 if (PrevDecl->isTemplateParameter()) {
9892 // Maybe we will complain about the shadowed template parameter.
9893 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregorcb8f9512011-10-20 17:58:49 +00009894 PrevDecl = 0;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009895 }
9896 }
9897
Chris Lattnereaaebc72009-04-25 08:06:05 +00009898 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009899 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
9900 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00009901 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009902 }
9903
Douglas Gregor83cb9422010-09-09 17:09:21 +00009904 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009905 D.getSourceRange().getBegin(),
9906 D.getIdentifierLoc(),
9907 D.getIdentifier());
Chris Lattnereaaebc72009-04-25 08:06:05 +00009908 if (Invalid)
9909 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00009910
Sebastian Redl4b07b292008-12-22 19:15:10 +00009911 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00009912 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00009913 PushOnScopeChains(ExDecl, S);
9914 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009915 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00009916
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00009917 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +00009918 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009919}
Anders Carlssonfb311762009-03-14 00:25:26 +00009920
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009921Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +00009922 Expr *AssertExpr,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009923 Expr *AssertMessageExpr_,
9924 SourceLocation RParenLoc) {
John McCall9ae2f072010-08-23 23:25:46 +00009925 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
Anders Carlssonfb311762009-03-14 00:25:26 +00009926
Anders Carlssonc3082412009-03-14 00:33:21 +00009927 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
Richard Smith282e7e62012-02-04 09:53:13 +00009928 // In a static_assert-declaration, the constant-expression shall be a
9929 // constant expression that can be contextually converted to bool.
9930 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
9931 if (Converted.isInvalid())
9932 return 0;
9933
Richard Smithdaaefc52011-12-14 23:32:26 +00009934 llvm::APSInt Cond;
Richard Smith282e7e62012-02-04 09:53:13 +00009935 if (VerifyIntegerConstantExpression(Converted.get(), &Cond,
9936 PDiag(diag::err_static_assert_expression_is_not_constant),
9937 /*AllowFold=*/false).isInvalid())
John McCalld226f652010-08-21 09:40:31 +00009938 return 0;
Anders Carlssonfb311762009-03-14 00:25:26 +00009939
Richard Smithdaaefc52011-12-14 23:32:26 +00009940 if (!Cond)
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009941 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Benjamin Kramer8d042582009-12-11 13:33:18 +00009942 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlssonc3082412009-03-14 00:33:21 +00009943 }
Mike Stump1eb44332009-09-09 15:08:12 +00009944
Douglas Gregor399ad972010-12-15 23:55:21 +00009945 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
9946 return 0;
9947
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009948 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
9949 AssertExpr, AssertMessage, RParenLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00009950
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009951 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +00009952 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +00009953}
Sebastian Redl50de12f2009-03-24 22:27:57 +00009954
Douglas Gregor1d869352010-04-07 16:53:43 +00009955/// \brief Perform semantic analysis of the given friend type declaration.
9956///
9957/// \returns A friend declaration that.
Abramo Bagnara0216df82011-10-29 20:52:52 +00009958FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation Loc,
9959 SourceLocation FriendLoc,
Douglas Gregor1d869352010-04-07 16:53:43 +00009960 TypeSourceInfo *TSInfo) {
9961 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
9962
9963 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00009964 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +00009965
Richard Smith6b130222011-10-18 21:39:00 +00009966 // C++03 [class.friend]p2:
9967 // An elaborated-type-specifier shall be used in a friend declaration
9968 // for a class.*
9969 //
9970 // * The class-key of the elaborated-type-specifier is required.
9971 if (!ActiveTemplateInstantiations.empty()) {
9972 // Do not complain about the form of friend template types during
9973 // template instantiation; we will already have complained when the
9974 // template was declared.
9975 } else if (!T->isElaboratedTypeSpecifier()) {
9976 // If we evaluated the type to a record type, suggest putting
9977 // a tag in front.
9978 if (const RecordType *RT = T->getAs<RecordType>()) {
9979 RecordDecl *RD = RT->getDecl();
9980
9981 std::string InsertionText = std::string(" ") + RD->getKindName();
9982
9983 Diag(TypeRange.getBegin(),
9984 getLangOptions().CPlusPlus0x ?
9985 diag::warn_cxx98_compat_unelaborated_friend_type :
9986 diag::ext_unelaborated_friend_type)
9987 << (unsigned) RD->getTagKind()
9988 << T
9989 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
9990 InsertionText);
9991 } else {
9992 Diag(FriendLoc,
9993 getLangOptions().CPlusPlus0x ?
9994 diag::warn_cxx98_compat_nonclass_type_friend :
9995 diag::ext_nonclass_type_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +00009996 << T
Douglas Gregor1d869352010-04-07 16:53:43 +00009997 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregor1d869352010-04-07 16:53:43 +00009998 }
Richard Smith6b130222011-10-18 21:39:00 +00009999 } else if (T->getAs<EnumType>()) {
10000 Diag(FriendLoc,
10001 getLangOptions().CPlusPlus0x ?
10002 diag::warn_cxx98_compat_enum_friend :
10003 diag::ext_enum_friend)
10004 << T
10005 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregor1d869352010-04-07 16:53:43 +000010006 }
10007
Douglas Gregor06245bf2010-04-07 17:57:12 +000010008 // C++0x [class.friend]p3:
10009 // If the type specifier in a friend declaration designates a (possibly
10010 // cv-qualified) class type, that class is declared as a friend; otherwise,
10011 // the friend declaration is ignored.
10012
10013 // FIXME: C++0x has some syntactic restrictions on friend type declarations
10014 // in [class.friend]p3 that we do not implement.
Douglas Gregor1d869352010-04-07 16:53:43 +000010015
Abramo Bagnara0216df82011-10-29 20:52:52 +000010016 return FriendDecl::Create(Context, CurContext, Loc, TSInfo, FriendLoc);
Douglas Gregor1d869352010-04-07 16:53:43 +000010017}
10018
John McCall9a34edb2010-10-19 01:40:49 +000010019/// Handle a friend tag declaration where the scope specifier was
10020/// templated.
10021Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
10022 unsigned TagSpec, SourceLocation TagLoc,
10023 CXXScopeSpec &SS,
10024 IdentifierInfo *Name, SourceLocation NameLoc,
10025 AttributeList *Attr,
10026 MultiTemplateParamsArg TempParamLists) {
10027 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
10028
10029 bool isExplicitSpecialization = false;
John McCall9a34edb2010-10-19 01:40:49 +000010030 bool Invalid = false;
10031
10032 if (TemplateParameterList *TemplateParams
Douglas Gregorc8406492011-05-10 18:27:06 +000010033 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
John McCall9a34edb2010-10-19 01:40:49 +000010034 TempParamLists.get(),
10035 TempParamLists.size(),
10036 /*friend*/ true,
10037 isExplicitSpecialization,
10038 Invalid)) {
John McCall9a34edb2010-10-19 01:40:49 +000010039 if (TemplateParams->size() > 0) {
10040 // This is a declaration of a class template.
10041 if (Invalid)
10042 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +000010043
Eric Christopher4110e132011-07-21 05:34:24 +000010044 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
10045 SS, Name, NameLoc, Attr,
10046 TemplateParams, AS_public,
Douglas Gregore7612302011-09-09 19:05:14 +000010047 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher4110e132011-07-21 05:34:24 +000010048 TempParamLists.size() - 1,
Abramo Bagnarac57c17d2011-03-10 13:28:31 +000010049 (TemplateParameterList**) TempParamLists.release()).take();
John McCall9a34edb2010-10-19 01:40:49 +000010050 } else {
10051 // The "template<>" header is extraneous.
10052 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
10053 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
10054 isExplicitSpecialization = true;
10055 }
10056 }
10057
10058 if (Invalid) return 0;
10059
John McCall9a34edb2010-10-19 01:40:49 +000010060 bool isAllExplicitSpecializations = true;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +000010061 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
John McCall9a34edb2010-10-19 01:40:49 +000010062 if (TempParamLists.get()[I]->size()) {
10063 isAllExplicitSpecializations = false;
10064 break;
10065 }
10066 }
10067
10068 // FIXME: don't ignore attributes.
10069
10070 // If it's explicit specializations all the way down, just forget
10071 // about the template header and build an appropriate non-templated
10072 // friend. TODO: for source fidelity, remember the headers.
10073 if (isAllExplicitSpecializations) {
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010074 if (SS.isEmpty()) {
10075 bool Owned = false;
10076 bool IsDependent = false;
10077 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
10078 Attr, AS_public,
10079 /*ModulePrivateLoc=*/SourceLocation(),
10080 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smithbdad7a22012-01-10 01:33:14 +000010081 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010082 /*ScopedEnumUsesClassTag=*/false,
10083 /*UnderlyingType=*/TypeResult());
10084 }
10085
Douglas Gregor2494dd02011-03-01 01:34:45 +000010086 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall9a34edb2010-10-19 01:40:49 +000010087 ElaboratedTypeKeyword Keyword
10088 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010089 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +000010090 *Name, NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010091 if (T.isNull())
10092 return 0;
10093
10094 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10095 if (isa<DependentNameType>(T)) {
10096 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara38a42912012-02-06 19:09:27 +000010097 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010098 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010099 TL.setNameLoc(NameLoc);
10100 } else {
10101 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara38a42912012-02-06 19:09:27 +000010102 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +000010103 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010104 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
10105 }
10106
10107 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
10108 TSI, FriendLoc);
10109 Friend->setAccess(AS_public);
10110 CurContext->addDecl(Friend);
10111 return Friend;
10112 }
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010113
10114 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
10115
10116
John McCall9a34edb2010-10-19 01:40:49 +000010117
10118 // Handle the case of a templated-scope friend class. e.g.
10119 // template <class T> class A<T>::B;
10120 // FIXME: we don't support these right now.
10121 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
10122 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
10123 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10124 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara38a42912012-02-06 19:09:27 +000010125 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010126 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCall9a34edb2010-10-19 01:40:49 +000010127 TL.setNameLoc(NameLoc);
10128
10129 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
10130 TSI, FriendLoc);
10131 Friend->setAccess(AS_public);
10132 Friend->setUnsupportedFriend(true);
10133 CurContext->addDecl(Friend);
10134 return Friend;
10135}
10136
10137
John McCalldd4a3b02009-09-16 22:47:08 +000010138/// Handle a friend type declaration. This works in tandem with
10139/// ActOnTag.
10140///
10141/// Notes on friend class templates:
10142///
10143/// We generally treat friend class declarations as if they were
10144/// declaring a class. So, for example, the elaborated type specifier
10145/// in a friend declaration is required to obey the restrictions of a
10146/// class-head (i.e. no typedefs in the scope chain), template
10147/// parameters are required to match up with simple template-ids, &c.
10148/// However, unlike when declaring a template specialization, it's
10149/// okay to refer to a template specialization without an empty
10150/// template parameter declaration, e.g.
10151/// friend class A<T>::B<unsigned>;
10152/// We permit this as a special case; if there are any template
10153/// parameters present at all, require proper matching, i.e.
10154/// template <> template <class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +000010155Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +000010156 MultiTemplateParamsArg TempParams) {
John McCall02cace72009-08-28 07:59:38 +000010157 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall67d1a672009-08-06 02:15:43 +000010158
10159 assert(DS.isFriendSpecified());
10160 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10161
John McCalldd4a3b02009-09-16 22:47:08 +000010162 // Try to convert the decl specifier to a type. This works for
10163 // friend templates because ActOnTag never produces a ClassTemplateDecl
10164 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +000010165 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +000010166 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
10167 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +000010168 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +000010169 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010170
Douglas Gregor6ccab972010-12-16 01:14:37 +000010171 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
10172 return 0;
10173
John McCalldd4a3b02009-09-16 22:47:08 +000010174 // This is definitely an error in C++98. It's probably meant to
10175 // be forbidden in C++0x, too, but the specification is just
10176 // poorly written.
10177 //
10178 // The problem is with declarations like the following:
10179 // template <T> friend A<T>::foo;
10180 // where deciding whether a class C is a friend or not now hinges
10181 // on whether there exists an instantiation of A that causes
10182 // 'foo' to equal C. There are restrictions on class-heads
10183 // (which we declare (by fiat) elaborated friend declarations to
10184 // be) that makes this tractable.
10185 //
10186 // FIXME: handle "template <> friend class A<T>;", which
10187 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +000010188 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +000010189 Diag(Loc, diag::err_tagless_friend_type_template)
10190 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +000010191 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +000010192 }
Douglas Gregor1d869352010-04-07 16:53:43 +000010193
John McCall02cace72009-08-28 07:59:38 +000010194 // C++98 [class.friend]p1: A friend of a class is a function
10195 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +000010196 // This is fixed in DR77, which just barely didn't make the C++03
10197 // deadline. It's also a very silly restriction that seriously
10198 // affects inner classes and which nobody else seems to implement;
10199 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +000010200 //
10201 // But note that we could warn about it: it's always useless to
10202 // friend one of your own members (it's not, however, worthless to
10203 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +000010204
John McCalldd4a3b02009-09-16 22:47:08 +000010205 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +000010206 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +000010207 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +000010208 NumTempParamLists,
John McCallbe04b6d2010-10-16 07:23:36 +000010209 TempParams.release(),
John McCall32f2fb52010-03-25 18:04:51 +000010210 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +000010211 DS.getFriendSpecLoc());
10212 else
Abramo Bagnara0216df82011-10-29 20:52:52 +000010213 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregor1d869352010-04-07 16:53:43 +000010214
10215 if (!D)
John McCalld226f652010-08-21 09:40:31 +000010216 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +000010217
John McCalldd4a3b02009-09-16 22:47:08 +000010218 D->setAccess(AS_public);
10219 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +000010220
John McCalld226f652010-08-21 09:40:31 +000010221 return D;
John McCall02cace72009-08-28 07:59:38 +000010222}
10223
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010224Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
John McCall337ec3d2010-10-12 23:13:28 +000010225 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +000010226 const DeclSpec &DS = D.getDeclSpec();
10227
10228 assert(DS.isFriendSpecified());
10229 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10230
10231 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +000010232 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall67d1a672009-08-06 02:15:43 +000010233
10234 // C++ [class.friend]p1
10235 // A friend of a class is a function or class....
10236 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +000010237 // It *doesn't* see through dependent types, which is correct
10238 // according to [temp.arg.type]p3:
10239 // If a declaration acquires a function type through a
10240 // type dependent on a template-parameter and this causes
10241 // a declaration that does not use the syntactic form of a
10242 // function declarator to have a function type, the program
10243 // is ill-formed.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010244 if (!TInfo->getType()->isFunctionType()) {
John McCall67d1a672009-08-06 02:15:43 +000010245 Diag(Loc, diag::err_unexpected_friend);
10246
10247 // It might be worthwhile to try to recover by creating an
10248 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +000010249 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010250 }
10251
10252 // C++ [namespace.memdef]p3
10253 // - If a friend declaration in a non-local class first declares a
10254 // class or function, the friend class or function is a member
10255 // of the innermost enclosing namespace.
10256 // - The name of the friend is not found by simple name lookup
10257 // until a matching declaration is provided in that namespace
10258 // scope (either before or after the class declaration granting
10259 // friendship).
10260 // - If a friend function is called, its name may be found by the
10261 // name lookup that considers functions from namespaces and
10262 // classes associated with the types of the function arguments.
10263 // - When looking for a prior declaration of a class or a function
10264 // declared as a friend, scopes outside the innermost enclosing
10265 // namespace scope are not considered.
10266
John McCall337ec3d2010-10-12 23:13:28 +000010267 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +000010268 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
10269 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +000010270 assert(Name);
10271
Douglas Gregor6ccab972010-12-16 01:14:37 +000010272 // Check for unexpanded parameter packs.
10273 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
10274 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
10275 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
10276 return 0;
10277
John McCall67d1a672009-08-06 02:15:43 +000010278 // The context we found the declaration in, or in which we should
10279 // create the declaration.
10280 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +000010281 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +000010282 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +000010283 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +000010284
John McCall337ec3d2010-10-12 23:13:28 +000010285 // FIXME: there are different rules in local classes
John McCall67d1a672009-08-06 02:15:43 +000010286
John McCall337ec3d2010-10-12 23:13:28 +000010287 // There are four cases here.
10288 // - There's no scope specifier, in which case we just go to the
John McCall29ae6e52010-10-13 05:45:15 +000010289 // appropriate scope and look for a function or function template
John McCall337ec3d2010-10-12 23:13:28 +000010290 // there as appropriate.
10291 // Recover from invalid scope qualifiers as if they just weren't there.
10292 if (SS.isInvalid() || !SS.isSet()) {
John McCall29ae6e52010-10-13 05:45:15 +000010293 // C++0x [namespace.memdef]p3:
10294 // If the name in a friend declaration is neither qualified nor
10295 // a template-id and the declaration is a function or an
10296 // elaborated-type-specifier, the lookup to determine whether
10297 // the entity has been previously declared shall not consider
10298 // any scopes outside the innermost enclosing namespace.
10299 // C++0x [class.friend]p11:
10300 // If a friend declaration appears in a local class and the name
10301 // specified is an unqualified name, a prior declaration is
10302 // looked up without considering scopes that are outside the
10303 // innermost enclosing non-class scope. For a friend function
10304 // declaration, if there is no prior declaration, the program is
10305 // ill-formed.
10306 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCall8a407372010-10-14 22:22:28 +000010307 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +000010308
John McCall29ae6e52010-10-13 05:45:15 +000010309 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +000010310 DC = CurContext;
10311 while (true) {
10312 // Skip class contexts. If someone can cite chapter and verse
10313 // for this behavior, that would be nice --- it's what GCC and
10314 // EDG do, and it seems like a reasonable intent, but the spec
10315 // really only says that checks for unqualified existing
10316 // declarations should stop at the nearest enclosing namespace,
10317 // not that they should only consider the nearest enclosing
10318 // namespace.
Douglas Gregor182ddf02009-09-28 00:08:27 +000010319 while (DC->isRecord())
10320 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +000010321
John McCall68263142009-11-18 22:49:29 +000010322 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +000010323
10324 // TODO: decide what we think about using declarations.
John McCall29ae6e52010-10-13 05:45:15 +000010325 if (isLocal || !Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +000010326 break;
John McCall29ae6e52010-10-13 05:45:15 +000010327
John McCall8a407372010-10-14 22:22:28 +000010328 if (isTemplateId) {
10329 if (isa<TranslationUnitDecl>(DC)) break;
10330 } else {
10331 if (DC->isFileContext()) break;
10332 }
John McCall67d1a672009-08-06 02:15:43 +000010333 DC = DC->getParent();
10334 }
10335
10336 // C++ [class.friend]p1: A friend of a class is a function or
10337 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000010338 // C++11 changes this for both friend types and functions.
John McCall7f27d922009-08-06 20:49:32 +000010339 // Most C++ 98 compilers do seem to give an error here, so
10340 // we do, too.
Richard Smithebaf0e62011-10-18 20:49:44 +000010341 if (!Previous.empty() && DC->Equals(CurContext))
10342 Diag(DS.getFriendSpecLoc(),
10343 getLangOptions().CPlusPlus0x ?
10344 diag::warn_cxx98_compat_friend_is_member :
10345 diag::err_friend_is_member);
John McCall337ec3d2010-10-12 23:13:28 +000010346
John McCall380aaa42010-10-13 06:22:15 +000010347 DCScope = getScopeForDeclContext(S, DC);
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000010348
Douglas Gregor883af832011-10-10 01:11:59 +000010349 // C++ [class.friend]p6:
10350 // A function can be defined in a friend declaration of a class if and
10351 // only if the class is a non-local class (9.8), the function name is
10352 // unqualified, and the function has namespace scope.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010353 if (isLocal && D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010354 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
10355 }
10356
John McCall337ec3d2010-10-12 23:13:28 +000010357 // - There's a non-dependent scope specifier, in which case we
10358 // compute it and do a previous lookup there for a function
10359 // or function template.
10360 } else if (!SS.getScopeRep()->isDependent()) {
10361 DC = computeDeclContext(SS);
10362 if (!DC) return 0;
10363
10364 if (RequireCompleteDeclContext(SS, DC)) return 0;
10365
10366 LookupQualifiedName(Previous, DC);
10367
10368 // Ignore things found implicitly in the wrong scope.
10369 // TODO: better diagnostics for this case. Suggesting the right
10370 // qualified scope would be nice...
10371 LookupResult::Filter F = Previous.makeFilter();
10372 while (F.hasNext()) {
10373 NamedDecl *D = F.next();
10374 if (!DC->InEnclosingNamespaceSetOf(
10375 D->getDeclContext()->getRedeclContext()))
10376 F.erase();
10377 }
10378 F.done();
10379
10380 if (Previous.empty()) {
10381 D.setInvalidType();
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010382 Diag(Loc, diag::err_qualified_friend_not_found)
10383 << Name << TInfo->getType();
John McCall337ec3d2010-10-12 23:13:28 +000010384 return 0;
10385 }
10386
10387 // C++ [class.friend]p1: A friend of a class is a function or
10388 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000010389 if (DC->Equals(CurContext))
10390 Diag(DS.getFriendSpecLoc(),
10391 getLangOptions().CPlusPlus0x ?
10392 diag::warn_cxx98_compat_friend_is_member :
10393 diag::err_friend_is_member);
Douglas Gregor883af832011-10-10 01:11:59 +000010394
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010395 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010396 // C++ [class.friend]p6:
10397 // A function can be defined in a friend declaration of a class if and
10398 // only if the class is a non-local class (9.8), the function name is
10399 // unqualified, and the function has namespace scope.
10400 SemaDiagnosticBuilder DB
10401 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
10402
10403 DB << SS.getScopeRep();
10404 if (DC->isFileContext())
10405 DB << FixItHint::CreateRemoval(SS.getRange());
10406 SS.clear();
10407 }
John McCall337ec3d2010-10-12 23:13:28 +000010408
10409 // - There's a scope specifier that does not match any template
10410 // parameter lists, in which case we use some arbitrary context,
10411 // create a method or method template, and wait for instantiation.
10412 // - There's a scope specifier that does match some template
10413 // parameter lists, which we don't handle right now.
10414 } else {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010415 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010416 // C++ [class.friend]p6:
10417 // A function can be defined in a friend declaration of a class if and
10418 // only if the class is a non-local class (9.8), the function name is
10419 // unqualified, and the function has namespace scope.
10420 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
10421 << SS.getScopeRep();
10422 }
10423
John McCall337ec3d2010-10-12 23:13:28 +000010424 DC = CurContext;
10425 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +000010426 }
Douglas Gregor883af832011-10-10 01:11:59 +000010427
John McCall29ae6e52010-10-13 05:45:15 +000010428 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +000010429 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +000010430 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
10431 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
10432 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +000010433 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +000010434 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
10435 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +000010436 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010437 }
John McCall67d1a672009-08-06 02:15:43 +000010438 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010439
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000010440 // FIXME: This is an egregious hack to cope with cases where the scope stack
10441 // does not contain the declaration context, i.e., in an out-of-line
10442 // definition of a class.
10443 Scope FakeDCScope(S, Scope::DeclScope, Diags);
10444 if (!DCScope) {
10445 FakeDCScope.setEntity(DC);
10446 DCScope = &FakeDCScope;
10447 }
10448
Francois Pichetaf0f4d02011-08-14 03:52:19 +000010449 bool AddToScope = true;
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010450 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
10451 move(TemplateParams), AddToScope);
John McCalld226f652010-08-21 09:40:31 +000010452 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +000010453
Douglas Gregor182ddf02009-09-28 00:08:27 +000010454 assert(ND->getDeclContext() == DC);
10455 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +000010456
John McCallab88d972009-08-31 22:39:49 +000010457 // Add the function declaration to the appropriate lookup tables,
10458 // adjusting the redeclarations list as necessary. We don't
10459 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +000010460 //
John McCallab88d972009-08-31 22:39:49 +000010461 // Also update the scope-based lookup if the target context's
10462 // lookup context is in lexical scope.
10463 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000010464 DC = DC->getRedeclContext();
Douglas Gregor182ddf02009-09-28 00:08:27 +000010465 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCallab88d972009-08-31 22:39:49 +000010466 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +000010467 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +000010468 }
John McCall02cace72009-08-28 07:59:38 +000010469
10470 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +000010471 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +000010472 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +000010473 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +000010474 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +000010475
John McCall337ec3d2010-10-12 23:13:28 +000010476 if (ND->isInvalidDecl())
10477 FrD->setInvalidDecl();
John McCall6102ca12010-10-16 06:59:13 +000010478 else {
10479 FunctionDecl *FD;
10480 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
10481 FD = FTD->getTemplatedDecl();
10482 else
10483 FD = cast<FunctionDecl>(ND);
10484
10485 // Mark templated-scope function declarations as unsupported.
10486 if (FD->getNumTemplateParameterLists())
10487 FrD->setUnsupportedFriend(true);
10488 }
John McCall337ec3d2010-10-12 23:13:28 +000010489
John McCalld226f652010-08-21 09:40:31 +000010490 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +000010491}
10492
John McCalld226f652010-08-21 09:40:31 +000010493void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
10494 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +000010495
Sebastian Redl50de12f2009-03-24 22:27:57 +000010496 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
10497 if (!Fn) {
10498 Diag(DelLoc, diag::err_deleted_non_function);
10499 return;
10500 }
Douglas Gregoref96ee02012-01-14 16:38:05 +000010501 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
Sebastian Redl50de12f2009-03-24 22:27:57 +000010502 Diag(DelLoc, diag::err_deleted_decl_not_first);
10503 Diag(Prev->getLocation(), diag::note_previous_declaration);
10504 // If the declaration wasn't the first, we delete the function anyway for
10505 // recovery.
10506 }
Sean Hunt10620eb2011-05-06 20:44:56 +000010507 Fn->setDeletedAsWritten();
Sebastian Redl50de12f2009-03-24 22:27:57 +000010508}
Sebastian Redl13e88542009-04-27 21:33:24 +000010509
Sean Hunte4246a62011-05-12 06:15:49 +000010510void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
10511 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
10512
10513 if (MD) {
Sean Hunteb88ae52011-05-23 21:07:59 +000010514 if (MD->getParent()->isDependentType()) {
10515 MD->setDefaulted();
10516 MD->setExplicitlyDefaulted();
10517 return;
10518 }
10519
Sean Hunte4246a62011-05-12 06:15:49 +000010520 CXXSpecialMember Member = getSpecialMember(MD);
10521 if (Member == CXXInvalid) {
10522 Diag(DefaultLoc, diag::err_default_special_members);
10523 return;
10524 }
10525
10526 MD->setDefaulted();
10527 MD->setExplicitlyDefaulted();
10528
Sean Huntcd10dec2011-05-23 23:14:04 +000010529 // If this definition appears within the record, do the checking when
10530 // the record is complete.
10531 const FunctionDecl *Primary = MD;
10532 if (MD->getTemplatedKind() != FunctionDecl::TK_NonTemplate)
10533 // Find the uninstantiated declaration that actually had the '= default'
10534 // on it.
10535 MD->getTemplateInstantiationPattern()->isDefined(Primary);
10536
10537 if (Primary == Primary->getCanonicalDecl())
Sean Hunte4246a62011-05-12 06:15:49 +000010538 return;
10539
10540 switch (Member) {
10541 case CXXDefaultConstructor: {
10542 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10543 CheckExplicitlyDefaultedDefaultConstructor(CD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010544 if (!CD->isInvalidDecl())
10545 DefineImplicitDefaultConstructor(DefaultLoc, CD);
10546 break;
10547 }
10548
10549 case CXXCopyConstructor: {
10550 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10551 CheckExplicitlyDefaultedCopyConstructor(CD);
10552 if (!CD->isInvalidDecl())
10553 DefineImplicitCopyConstructor(DefaultLoc, CD);
Sean Hunte4246a62011-05-12 06:15:49 +000010554 break;
10555 }
Sean Huntcb45a0f2011-05-12 22:46:25 +000010556
Sean Hunt2b188082011-05-14 05:23:28 +000010557 case CXXCopyAssignment: {
10558 CheckExplicitlyDefaultedCopyAssignment(MD);
10559 if (!MD->isInvalidDecl())
10560 DefineImplicitCopyAssignment(DefaultLoc, MD);
10561 break;
10562 }
10563
Sean Huntcb45a0f2011-05-12 22:46:25 +000010564 case CXXDestructor: {
10565 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
10566 CheckExplicitlyDefaultedDestructor(DD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010567 if (!DD->isInvalidDecl())
10568 DefineImplicitDestructor(DefaultLoc, DD);
Sean Huntcb45a0f2011-05-12 22:46:25 +000010569 break;
10570 }
10571
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010572 case CXXMoveConstructor: {
10573 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10574 CheckExplicitlyDefaultedMoveConstructor(CD);
10575 if (!CD->isInvalidDecl())
10576 DefineImplicitMoveConstructor(DefaultLoc, CD);
Sean Hunt82713172011-05-25 23:16:36 +000010577 break;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010578 }
Sean Hunt82713172011-05-25 23:16:36 +000010579
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010580 case CXXMoveAssignment: {
10581 CheckExplicitlyDefaultedMoveAssignment(MD);
10582 if (!MD->isInvalidDecl())
10583 DefineImplicitMoveAssignment(DefaultLoc, MD);
10584 break;
10585 }
10586
10587 case CXXInvalid:
David Blaikieb219cfc2011-09-23 05:06:16 +000010588 llvm_unreachable("Invalid special member.");
Sean Hunte4246a62011-05-12 06:15:49 +000010589 }
10590 } else {
10591 Diag(DefaultLoc, diag::err_default_special_members);
10592 }
10593}
10594
Sebastian Redl13e88542009-04-27 21:33:24 +000010595static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +000010596 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +000010597 Stmt *SubStmt = *CI;
10598 if (!SubStmt)
10599 continue;
10600 if (isa<ReturnStmt>(SubStmt))
10601 Self.Diag(SubStmt->getSourceRange().getBegin(),
10602 diag::err_return_in_constructor_handler);
10603 if (!isa<Expr>(SubStmt))
10604 SearchForReturnInStmt(Self, SubStmt);
10605 }
10606}
10607
10608void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
10609 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
10610 CXXCatchStmt *Handler = TryBlock->getHandler(I);
10611 SearchForReturnInStmt(*this, Handler);
10612 }
10613}
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010614
Mike Stump1eb44332009-09-09 15:08:12 +000010615bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010616 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +000010617 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
10618 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010619
Chandler Carruth73857792010-02-15 11:53:20 +000010620 if (Context.hasSameType(NewTy, OldTy) ||
10621 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010622 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000010623
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010624 // Check if the return types are covariant
10625 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +000010626
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010627 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010628 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
10629 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010630 NewClassTy = NewPT->getPointeeType();
10631 OldClassTy = OldPT->getPointeeType();
10632 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010633 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
10634 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
10635 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
10636 NewClassTy = NewRT->getPointeeType();
10637 OldClassTy = OldRT->getPointeeType();
10638 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010639 }
10640 }
Mike Stump1eb44332009-09-09 15:08:12 +000010641
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010642 // The return types aren't either both pointers or references to a class type.
10643 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +000010644 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010645 diag::err_different_return_type_for_overriding_virtual_function)
10646 << New->getDeclName() << NewTy << OldTy;
10647 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +000010648
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010649 return true;
10650 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010651
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010652 // C++ [class.virtual]p6:
10653 // If the return type of D::f differs from the return type of B::f, the
10654 // class type in the return type of D::f shall be complete at the point of
10655 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +000010656 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
10657 if (!RT->isBeingDefined() &&
10658 RequireCompleteType(New->getLocation(), NewClassTy,
10659 PDiag(diag::err_covariant_return_incomplete)
10660 << New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010661 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +000010662 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010663
Douglas Gregora4923eb2009-11-16 21:35:15 +000010664 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010665 // Check if the new class derives from the old class.
10666 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
10667 Diag(New->getLocation(),
10668 diag::err_covariant_return_not_derived)
10669 << New->getDeclName() << NewTy << OldTy;
10670 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10671 return true;
10672 }
Mike Stump1eb44332009-09-09 15:08:12 +000010673
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010674 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +000010675 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +000010676 diag::err_covariant_return_inaccessible_base,
10677 diag::err_covariant_return_ambiguous_derived_to_base_conv,
10678 // FIXME: Should this point to the return type?
10679 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCalleee1d542011-02-14 07:13:47 +000010680 // FIXME: this note won't trigger for delayed access control
10681 // diagnostics, and it's impossible to get an undelayed error
10682 // here from access control during the original parse because
10683 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010684 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10685 return true;
10686 }
10687 }
Mike Stump1eb44332009-09-09 15:08:12 +000010688
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010689 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010690 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010691 Diag(New->getLocation(),
10692 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010693 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010694 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10695 return true;
10696 };
Mike Stump1eb44332009-09-09 15:08:12 +000010697
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010698
10699 // The new class type must have the same or less qualifiers as the old type.
10700 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
10701 Diag(New->getLocation(),
10702 diag::err_covariant_return_type_class_type_more_qualified)
10703 << New->getDeclName() << NewTy << OldTy;
10704 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10705 return true;
10706 };
Mike Stump1eb44332009-09-09 15:08:12 +000010707
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010708 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010709}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010710
Douglas Gregor4ba31362009-12-01 17:24:26 +000010711/// \brief Mark the given method pure.
10712///
10713/// \param Method the method to be marked pure.
10714///
10715/// \param InitRange the source range that covers the "0" initializer.
10716bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnara796aa442011-03-12 11:17:06 +000010717 SourceLocation EndLoc = InitRange.getEnd();
10718 if (EndLoc.isValid())
10719 Method->setRangeEnd(EndLoc);
10720
Douglas Gregor4ba31362009-12-01 17:24:26 +000010721 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
10722 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +000010723 return false;
Abramo Bagnara796aa442011-03-12 11:17:06 +000010724 }
Douglas Gregor4ba31362009-12-01 17:24:26 +000010725
10726 if (!Method->isInvalidDecl())
10727 Diag(Method->getLocation(), diag::err_non_virtual_pure)
10728 << Method->getDeclName() << InitRange;
10729 return true;
10730}
10731
John McCall731ad842009-12-19 09:28:58 +000010732/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
10733/// an initializer for the out-of-line declaration 'Dcl'. The scope
10734/// is a fresh scope pushed for just this purpose.
10735///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010736/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
10737/// static data member of class X, names should be looked up in the scope of
10738/// class X.
John McCalld226f652010-08-21 09:40:31 +000010739void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010740 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000010741 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010742
John McCall731ad842009-12-19 09:28:58 +000010743 // We should only get called for declarations with scope specifiers, like:
10744 // int foo::bar;
10745 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000010746 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010747}
10748
10749/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +000010750/// initializer for the out-of-line declaration 'D'.
10751void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010752 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000010753 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010754
John McCall731ad842009-12-19 09:28:58 +000010755 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000010756 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010757}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010758
10759/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
10760/// C++ if/switch/while/for statement.
10761/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +000010762DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010763 // C++ 6.4p2:
10764 // The declarator shall not specify a function or an array.
10765 // The type-specifier-seq shall not contain typedef and shall not declare a
10766 // new class or enumeration.
10767 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
10768 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000010769
10770 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor9a30c992011-07-05 16:13:20 +000010771 if (!Dcl)
10772 return true;
10773
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000010774 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
10775 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010776 << D.getSourceRange();
Douglas Gregor9a30c992011-07-05 16:13:20 +000010777 return true;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010778 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010779
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010780 return Dcl;
10781}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010782
Douglas Gregordfe65432011-07-28 19:11:31 +000010783void Sema::LoadExternalVTableUses() {
10784 if (!ExternalSource)
10785 return;
10786
10787 SmallVector<ExternalVTableUse, 4> VTables;
10788 ExternalSource->ReadUsedVTables(VTables);
10789 SmallVector<VTableUse, 4> NewUses;
10790 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
10791 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
10792 = VTablesUsed.find(VTables[I].Record);
10793 // Even if a definition wasn't required before, it may be required now.
10794 if (Pos != VTablesUsed.end()) {
10795 if (!Pos->second && VTables[I].DefinitionRequired)
10796 Pos->second = true;
10797 continue;
10798 }
10799
10800 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
10801 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
10802 }
10803
10804 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
10805}
10806
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010807void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
10808 bool DefinitionRequired) {
10809 // Ignore any vtable uses in unevaluated operands or for classes that do
10810 // not have a vtable.
10811 if (!Class->isDynamicClass() || Class->isDependentContext() ||
10812 CurContext->isDependentContext() ||
Eli Friedman78a54242012-01-21 04:44:06 +000010813 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolabbf58bb2010-03-10 02:19:29 +000010814 return;
10815
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010816 // Try to insert this class into the map.
Douglas Gregordfe65432011-07-28 19:11:31 +000010817 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010818 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10819 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
10820 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
10821 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +000010822 // If we already had an entry, check to see if we are promoting this vtable
10823 // to required a definition. If so, we need to reappend to the VTableUses
10824 // list, since we may have already processed the first entry.
10825 if (DefinitionRequired && !Pos.first->second) {
10826 Pos.first->second = true;
10827 } else {
10828 // Otherwise, we can early exit.
10829 return;
10830 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010831 }
10832
10833 // Local classes need to have their virtual members marked
10834 // immediately. For all other classes, we mark their virtual members
10835 // at the end of the translation unit.
10836 if (Class->isLocalClass())
10837 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +000010838 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010839 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +000010840}
10841
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010842bool Sema::DefineUsedVTables() {
Douglas Gregordfe65432011-07-28 19:11:31 +000010843 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010844 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +000010845 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +000010846
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010847 // Note: The VTableUses vector could grow as a result of marking
10848 // the members of a class as "used", so we check the size each
10849 // time through the loop and prefer indices (with are stable) to
10850 // iterators (which are not).
Douglas Gregor78844032011-04-22 22:25:37 +000010851 bool DefinedAnything = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010852 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +000010853 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010854 if (!Class)
10855 continue;
10856
10857 SourceLocation Loc = VTableUses[I].second;
10858
10859 // If this class has a key function, but that key function is
10860 // defined in another translation unit, we don't need to emit the
10861 // vtable even though we're using it.
10862 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +000010863 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010864 switch (KeyFunction->getTemplateSpecializationKind()) {
10865 case TSK_Undeclared:
10866 case TSK_ExplicitSpecialization:
10867 case TSK_ExplicitInstantiationDeclaration:
10868 // The key function is in another translation unit.
10869 continue;
10870
10871 case TSK_ExplicitInstantiationDefinition:
10872 case TSK_ImplicitInstantiation:
10873 // We will be instantiating the key function.
10874 break;
10875 }
10876 } else if (!KeyFunction) {
10877 // If we have a class with no key function that is the subject
10878 // of an explicit instantiation declaration, suppress the
10879 // vtable; it will live with the explicit instantiation
10880 // definition.
10881 bool IsExplicitInstantiationDeclaration
10882 = Class->getTemplateSpecializationKind()
10883 == TSK_ExplicitInstantiationDeclaration;
10884 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
10885 REnd = Class->redecls_end();
10886 R != REnd; ++R) {
10887 TemplateSpecializationKind TSK
10888 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
10889 if (TSK == TSK_ExplicitInstantiationDeclaration)
10890 IsExplicitInstantiationDeclaration = true;
10891 else if (TSK == TSK_ExplicitInstantiationDefinition) {
10892 IsExplicitInstantiationDeclaration = false;
10893 break;
10894 }
10895 }
10896
10897 if (IsExplicitInstantiationDeclaration)
10898 continue;
10899 }
10900
10901 // Mark all of the virtual members of this class as referenced, so
10902 // that we can build a vtable. Then, tell the AST consumer that a
10903 // vtable for this class is required.
Douglas Gregor78844032011-04-22 22:25:37 +000010904 DefinedAnything = true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010905 MarkVirtualMembersReferenced(Loc, Class);
10906 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10907 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
10908
10909 // Optionally warn if we're emitting a weak vtable.
10910 if (Class->getLinkage() == ExternalLinkage &&
10911 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Douglas Gregora120d012011-09-23 19:04:03 +000010912 const FunctionDecl *KeyFunctionDef = 0;
10913 if (!KeyFunction ||
10914 (KeyFunction->hasBody(KeyFunctionDef) &&
10915 KeyFunctionDef->isInlined()))
David Blaikie44d95b52011-12-09 18:32:50 +000010916 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
10917 TSK_ExplicitInstantiationDefinition
10918 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
10919 << Class;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010920 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010921 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010922 VTableUses.clear();
10923
Douglas Gregor78844032011-04-22 22:25:37 +000010924 return DefinedAnything;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010925}
Anders Carlssond6a637f2009-12-07 08:24:59 +000010926
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010927void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
10928 const CXXRecordDecl *RD) {
Anders Carlssond6a637f2009-12-07 08:24:59 +000010929 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
10930 e = RD->method_end(); i != e; ++i) {
10931 CXXMethodDecl *MD = *i;
10932
10933 // C++ [basic.def.odr]p2:
10934 // [...] A virtual member function is used if it is not pure. [...]
10935 if (MD->isVirtual() && !MD->isPure())
Eli Friedman5f2987c2012-02-02 03:46:19 +000010936 MarkFunctionReferenced(Loc, MD);
Anders Carlssond6a637f2009-12-07 08:24:59 +000010937 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010938
10939 // Only classes that have virtual bases need a VTT.
10940 if (RD->getNumVBases() == 0)
10941 return;
10942
10943 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
10944 e = RD->bases_end(); i != e; ++i) {
10945 const CXXRecordDecl *Base =
10946 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010947 if (Base->getNumVBases() == 0)
10948 continue;
10949 MarkVirtualMembersReferenced(Loc, Base);
10950 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000010951}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010952
10953/// SetIvarInitializers - This routine builds initialization ASTs for the
10954/// Objective-C implementation whose ivars need be initialized.
10955void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
10956 if (!getLangOptions().CPlusPlus)
10957 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +000010958 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +000010959 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010960 CollectIvarsToConstructOrDestruct(OID, ivars);
10961 if (ivars.empty())
10962 return;
Chris Lattner5f9e2722011-07-23 10:55:15 +000010963 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010964 for (unsigned i = 0; i < ivars.size(); i++) {
10965 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010966 if (Field->isInvalidDecl())
10967 continue;
10968
Sean Huntcbb67482011-01-08 20:30:50 +000010969 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010970 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
10971 InitializationKind InitKind =
10972 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
10973
10974 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +000010975 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +000010976 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregor53c374f2010-12-07 00:41:46 +000010977 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010978 // Note, MemberInit could actually come back empty if no initialization
10979 // is required (e.g., because it would call a trivial default constructor)
10980 if (!MemberInit.get() || MemberInit.isInvalid())
10981 continue;
John McCallb4eb64d2010-10-08 02:01:28 +000010982
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010983 Member =
Sean Huntcbb67482011-01-08 20:30:50 +000010984 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
10985 SourceLocation(),
10986 MemberInit.takeAs<Expr>(),
10987 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010988 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010989
10990 // Be sure that the destructor is accessible and is marked as referenced.
10991 if (const RecordType *RecordTy
10992 = Context.getBaseElementType(Field->getType())
10993 ->getAs<RecordType>()) {
10994 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +000010995 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010996 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010997 CheckDestructorAccess(Field->getLocation(), Destructor,
10998 PDiag(diag::err_access_dtor_ivar)
10999 << Context.getBaseElementType(Field->getType()));
11000 }
11001 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011002 }
11003 ObjCImplementation->setIvarInitializers(Context,
11004 AllToInit.data(), AllToInit.size());
11005 }
11006}
Sean Huntfe57eef2011-05-04 05:57:24 +000011007
Sean Huntebcbe1d2011-05-04 23:29:54 +000011008static
11009void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
11010 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
11011 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
11012 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
11013 Sema &S) {
11014 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11015 CE = Current.end();
11016 if (Ctor->isInvalidDecl())
11017 return;
11018
11019 const FunctionDecl *FNTarget = 0;
11020 CXXConstructorDecl *Target;
11021
11022 // We ignore the result here since if we don't have a body, Target will be
11023 // null below.
11024 (void)Ctor->getTargetConstructor()->hasBody(FNTarget);
11025 Target
11026= const_cast<CXXConstructorDecl*>(cast_or_null<CXXConstructorDecl>(FNTarget));
11027
11028 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
11029 // Avoid dereferencing a null pointer here.
11030 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
11031
11032 if (!Current.insert(Canonical))
11033 return;
11034
11035 // We know that beyond here, we aren't chaining into a cycle.
11036 if (!Target || !Target->isDelegatingConstructor() ||
11037 Target->isInvalidDecl() || Valid.count(TCanonical)) {
11038 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11039 Valid.insert(*CI);
11040 Current.clear();
11041 // We've hit a cycle.
11042 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
11043 Current.count(TCanonical)) {
11044 // If we haven't diagnosed this cycle yet, do so now.
11045 if (!Invalid.count(TCanonical)) {
11046 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Sean Huntc1598702011-05-05 00:05:47 +000011047 diag::warn_delegating_ctor_cycle)
Sean Huntebcbe1d2011-05-04 23:29:54 +000011048 << Ctor;
11049
11050 // Don't add a note for a function delegating directo to itself.
11051 if (TCanonical != Canonical)
11052 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
11053
11054 CXXConstructorDecl *C = Target;
11055 while (C->getCanonicalDecl() != Canonical) {
11056 (void)C->getTargetConstructor()->hasBody(FNTarget);
11057 assert(FNTarget && "Ctor cycle through bodiless function");
11058
11059 C
11060 = const_cast<CXXConstructorDecl*>(cast<CXXConstructorDecl>(FNTarget));
11061 S.Diag(C->getLocation(), diag::note_which_delegates_to);
11062 }
11063 }
11064
11065 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11066 Invalid.insert(*CI);
11067 Current.clear();
11068 } else {
11069 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
11070 }
11071}
11072
11073
Sean Huntfe57eef2011-05-04 05:57:24 +000011074void Sema::CheckDelegatingCtorCycles() {
11075 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
11076
Sean Huntebcbe1d2011-05-04 23:29:54 +000011077 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11078 CE = Current.end();
Sean Huntfe57eef2011-05-04 05:57:24 +000011079
Douglas Gregor0129b562011-07-27 21:57:17 +000011080 for (DelegatingCtorDeclsType::iterator
11081 I = DelegatingCtorDecls.begin(ExternalSource),
Sean Huntebcbe1d2011-05-04 23:29:54 +000011082 E = DelegatingCtorDecls.end();
11083 I != E; ++I) {
11084 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Sean Huntfe57eef2011-05-04 05:57:24 +000011085 }
Sean Huntebcbe1d2011-05-04 23:29:54 +000011086
11087 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
11088 (*CI)->setInvalidDecl();
Sean Huntfe57eef2011-05-04 05:57:24 +000011089}
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000011090
11091/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
11092Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
11093 // Implicitly declared functions (e.g. copy constructors) are
11094 // __host__ __device__
11095 if (D->isImplicit())
11096 return CFT_HostDevice;
11097
11098 if (D->hasAttr<CUDAGlobalAttr>())
11099 return CFT_Global;
11100
11101 if (D->hasAttr<CUDADeviceAttr>()) {
11102 if (D->hasAttr<CUDAHostAttr>())
11103 return CFT_HostDevice;
11104 else
11105 return CFT_Device;
11106 }
11107
11108 return CFT_Host;
11109}
11110
11111bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
11112 CUDAFunctionTarget CalleeTarget) {
11113 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
11114 // Callable from the device only."
11115 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
11116 return true;
11117
11118 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
11119 // Callable from the host only."
11120 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
11121 // Callable from the host only."
11122 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
11123 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
11124 return true;
11125
11126 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
11127 return true;
11128
11129 return false;
11130}