blob: 82e59ddafeef3d07d038199290ea3f960b4c6a2c [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);
Douglas Gregorf0459f82012-02-10 23:30:22 +000065 bool VisitLambdaExpr(LambdaExpr *Lambda);
Chris Lattner9e979552008-04-12 23:52:44 +000066 };
Chris Lattner8123a952008-04-10 02:22:51 +000067
Chris Lattner9e979552008-04-12 23:52:44 +000068 /// VisitExpr - Visit all of the children of this expression.
69 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
70 bool IsInvalid = false;
John McCall7502c1d2011-02-13 04:07:26 +000071 for (Stmt::child_range I = Node->children(); I; ++I)
Chris Lattnerb77792e2008-07-26 22:17:49 +000072 IsInvalid |= Visit(*I);
Chris Lattner9e979552008-04-12 23:52:44 +000073 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000074 }
75
Chris Lattner9e979552008-04-12 23:52:44 +000076 /// VisitDeclRefExpr - Visit a reference to a declaration, to
77 /// determine whether this declaration can be used in the default
78 /// argument expression.
79 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000080 NamedDecl *Decl = DRE->getDecl();
Chris Lattner9e979552008-04-12 23:52:44 +000081 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
82 // C++ [dcl.fct.default]p9
83 // Default arguments are evaluated each time the function is
84 // called. The order of evaluation of function arguments is
85 // unspecified. Consequently, parameters of a function shall not
86 // be used in default argument expressions, even if they are not
87 // evaluated. Parameters of a function declared before a default
88 // argument expression are in scope and can hide namespace and
89 // class member names.
Mike Stump1eb44332009-09-09 15:08:12 +000090 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000091 diag::err_param_default_argument_references_param)
Chris Lattner08631c52008-11-23 21:45:46 +000092 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff248a7532008-04-15 22:42:06 +000093 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000094 // C++ [dcl.fct.default]p7
95 // Local variables shall not be used in default argument
96 // expressions.
John McCallb6bbcc92010-10-15 04:57:14 +000097 if (VDecl->isLocalVarDecl())
Mike Stump1eb44332009-09-09 15:08:12 +000098 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000099 diag::err_param_default_argument_references_local)
Chris Lattner08631c52008-11-23 21:45:46 +0000100 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000101 }
Chris Lattner8123a952008-04-10 02:22:51 +0000102
Douglas Gregor3996f232008-11-04 13:41:56 +0000103 return false;
104 }
Chris Lattner9e979552008-04-12 23:52:44 +0000105
Douglas Gregor796da182008-11-04 14:32:21 +0000106 /// VisitCXXThisExpr - Visit a C++ "this" expression.
107 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
108 // C++ [dcl.fct.default]p8:
109 // The keyword this shall not be used in a default argument of a
110 // member function.
111 return S->Diag(ThisE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000112 diag::err_param_default_argument_references_this)
113 << ThisE->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000114 }
Douglas Gregorf0459f82012-02-10 23:30:22 +0000115
116 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
117 // C++11 [expr.lambda.prim]p13:
118 // A lambda-expression appearing in a default argument shall not
119 // implicitly or explicitly capture any entity.
120 if (Lambda->capture_begin() == Lambda->capture_end())
121 return false;
122
123 return S->Diag(Lambda->getLocStart(),
124 diag::err_lambda_capture_default_arg);
125 }
Chris Lattner8123a952008-04-10 02:22:51 +0000126}
127
Sean Hunt001cad92011-05-10 00:49:42 +0000128void Sema::ImplicitExceptionSpecification::CalledDecl(CXXMethodDecl *Method) {
Sean Hunt49634cf2011-05-13 06:10:58 +0000129 assert(Context && "ImplicitExceptionSpecification without an ASTContext");
Richard Smith7a614d82011-06-11 17:19:42 +0000130 // If we have an MSAny or unknown spec already, don't bother.
131 if (!Method || ComputedEST == EST_MSAny || ComputedEST == EST_Delayed)
Sean Hunt001cad92011-05-10 00:49:42 +0000132 return;
133
134 const FunctionProtoType *Proto
135 = Method->getType()->getAs<FunctionProtoType>();
136
137 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
138
139 // If this function can throw any exceptions, make a note of that.
Richard Smith7a614d82011-06-11 17:19:42 +0000140 if (EST == EST_Delayed || EST == EST_MSAny || EST == EST_None) {
Sean Hunt001cad92011-05-10 00:49:42 +0000141 ClearExceptions();
142 ComputedEST = EST;
143 return;
144 }
145
Richard Smith7a614d82011-06-11 17:19:42 +0000146 // FIXME: If the call to this decl is using any of its default arguments, we
147 // need to search them for potentially-throwing calls.
148
Sean Hunt001cad92011-05-10 00:49:42 +0000149 // If this function has a basic noexcept, it doesn't affect the outcome.
150 if (EST == EST_BasicNoexcept)
151 return;
152
153 // If we have a throw-all spec at this point, ignore the function.
154 if (ComputedEST == EST_None)
155 return;
156
157 // If we're still at noexcept(true) and there's a nothrow() callee,
158 // change to that specification.
159 if (EST == EST_DynamicNone) {
160 if (ComputedEST == EST_BasicNoexcept)
161 ComputedEST = EST_DynamicNone;
162 return;
163 }
164
165 // Check out noexcept specs.
166 if (EST == EST_ComputedNoexcept) {
Sean Hunt49634cf2011-05-13 06:10:58 +0000167 FunctionProtoType::NoexceptResult NR = Proto->getNoexceptSpec(*Context);
Sean Hunt001cad92011-05-10 00:49:42 +0000168 assert(NR != FunctionProtoType::NR_NoNoexcept &&
169 "Must have noexcept result for EST_ComputedNoexcept.");
170 assert(NR != FunctionProtoType::NR_Dependent &&
171 "Should not generate implicit declarations for dependent cases, "
172 "and don't know how to handle them anyway.");
173
174 // noexcept(false) -> no spec on the new function
175 if (NR == FunctionProtoType::NR_Throw) {
176 ClearExceptions();
177 ComputedEST = EST_None;
178 }
179 // noexcept(true) won't change anything either.
180 return;
181 }
182
183 assert(EST == EST_Dynamic && "EST case not considered earlier.");
184 assert(ComputedEST != EST_None &&
185 "Shouldn't collect exceptions when throw-all is guaranteed.");
186 ComputedEST = EST_Dynamic;
187 // Record the exceptions in this function's exception specification.
188 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
189 EEnd = Proto->exception_end();
190 E != EEnd; ++E)
Sean Hunt49634cf2011-05-13 06:10:58 +0000191 if (ExceptionsSeen.insert(Context->getCanonicalType(*E)))
Sean Hunt001cad92011-05-10 00:49:42 +0000192 Exceptions.push_back(*E);
193}
194
Richard Smith7a614d82011-06-11 17:19:42 +0000195void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
196 if (!E || ComputedEST == EST_MSAny || ComputedEST == EST_Delayed)
197 return;
198
199 // FIXME:
200 //
201 // C++0x [except.spec]p14:
NAKAMURA Takumi48579472011-06-21 03:19:28 +0000202 // [An] implicit exception-specification specifies the type-id T if and
203 // only if T is allowed by the exception-specification of a function directly
204 // invoked by f's implicit definition; f shall allow all exceptions if any
Richard Smith7a614d82011-06-11 17:19:42 +0000205 // function it directly invokes allows all exceptions, and f shall allow no
206 // exceptions if every function it directly invokes allows no exceptions.
207 //
208 // Note in particular that if an implicit exception-specification is generated
209 // for a function containing a throw-expression, that specification can still
210 // be noexcept(true).
211 //
212 // Note also that 'directly invoked' is not defined in the standard, and there
213 // is no indication that we should only consider potentially-evaluated calls.
214 //
215 // Ultimately we should implement the intent of the standard: the exception
216 // specification should be the set of exceptions which can be thrown by the
217 // implicit definition. For now, we assume that any non-nothrow expression can
218 // throw any exception.
219
220 if (E->CanThrow(*Context))
221 ComputedEST = EST_None;
222}
223
Anders Carlssoned961f92009-08-25 02:29:20 +0000224bool
John McCall9ae2f072010-08-23 23:25:46 +0000225Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump1eb44332009-09-09 15:08:12 +0000226 SourceLocation EqualLoc) {
Anders Carlsson5653ca52009-08-25 13:46:13 +0000227 if (RequireCompleteType(Param->getLocation(), Param->getType(),
228 diag::err_typecheck_decl_incomplete_type)) {
229 Param->setInvalidDecl();
230 return true;
231 }
232
Anders Carlssoned961f92009-08-25 02:29:20 +0000233 // C++ [dcl.fct.default]p5
234 // A default argument expression is implicitly converted (clause
235 // 4) to the parameter type. The default argument expression has
236 // the same semantic constraints as the initializer expression in
237 // a declaration of a variable of the parameter type, using the
238 // copy-initialization semantics (8.5).
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000239 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
240 Param);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000241 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
242 EqualLoc);
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000243 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
John McCall60d7b3a2010-08-24 06:29:42 +0000244 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
Nico Weber6bb4dcb2010-11-28 22:53:37 +0000245 MultiExprArg(*this, &Arg, 1));
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000246 if (Result.isInvalid())
Anders Carlsson9351c172009-08-25 03:18:48 +0000247 return true;
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000248 Arg = Result.takeAs<Expr>();
Anders Carlssoned961f92009-08-25 02:29:20 +0000249
John McCallb4eb64d2010-10-08 02:01:28 +0000250 CheckImplicitConversions(Arg, EqualLoc);
John McCall4765fa02010-12-06 08:20:24 +0000251 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000252
Anders Carlssoned961f92009-08-25 02:29:20 +0000253 // Okay: add the default argument to the parameter
254 Param->setDefaultArg(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000255
Douglas Gregor8cfb7a32010-10-12 18:23:32 +0000256 // We have already instantiated this parameter; provide each of the
257 // instantiations with the uninstantiated default argument.
258 UnparsedDefaultArgInstantiationsMap::iterator InstPos
259 = UnparsedDefaultArgInstantiations.find(Param);
260 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
261 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
262 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
263
264 // We're done tracking this parameter's instantiations.
265 UnparsedDefaultArgInstantiations.erase(InstPos);
266 }
267
Anders Carlsson9351c172009-08-25 03:18:48 +0000268 return false;
Anders Carlssoned961f92009-08-25 02:29:20 +0000269}
270
Chris Lattner8123a952008-04-10 02:22:51 +0000271/// ActOnParamDefaultArgument - Check whether the default argument
272/// provided for a function parameter is well-formed. If so, attach it
273/// to the parameter declaration.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000274void
John McCalld226f652010-08-21 09:40:31 +0000275Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000276 Expr *DefaultArg) {
277 if (!param || !DefaultArg)
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000278 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000279
John McCalld226f652010-08-21 09:40:31 +0000280 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000281 UnparsedDefaultArgLocs.erase(Param);
282
Chris Lattner3d1cee32008-04-08 05:04:30 +0000283 // Default arguments are only permitted in C++
284 if (!getLangOptions().CPlusPlus) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000285 Diag(EqualLoc, diag::err_param_default_argument)
286 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000287 Param->setInvalidDecl();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000288 return;
289 }
290
Douglas Gregor6f526752010-12-16 08:48:57 +0000291 // Check for unexpanded parameter packs.
292 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
293 Param->setInvalidDecl();
294 return;
295 }
296
Anders Carlsson66e30672009-08-25 01:02:06 +0000297 // Check that the default argument is well-formed
John McCall9ae2f072010-08-23 23:25:46 +0000298 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
299 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlsson66e30672009-08-25 01:02:06 +0000300 Param->setInvalidDecl();
301 return;
302 }
Mike Stump1eb44332009-09-09 15:08:12 +0000303
John McCall9ae2f072010-08-23 23:25:46 +0000304 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000305}
306
Douglas Gregor61366e92008-12-24 00:01:03 +0000307/// ActOnParamUnparsedDefaultArgument - We've seen a default
308/// argument for a function parameter, but we can't parse it yet
309/// because we're inside a class definition. Note that this default
310/// argument will be parsed later.
John McCalld226f652010-08-21 09:40:31 +0000311void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson5e300d12009-06-12 16:51:40 +0000312 SourceLocation EqualLoc,
313 SourceLocation ArgLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000314 if (!param)
315 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000316
John McCalld226f652010-08-21 09:40:31 +0000317 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000318 if (Param)
319 Param->setUnparsedDefaultArg();
Mike Stump1eb44332009-09-09 15:08:12 +0000320
Anders Carlsson5e300d12009-06-12 16:51:40 +0000321 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor61366e92008-12-24 00:01:03 +0000322}
323
Douglas Gregor72b505b2008-12-16 21:30:33 +0000324/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
325/// the default argument for the parameter param failed.
John McCalld226f652010-08-21 09:40:31 +0000326void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000327 if (!param)
328 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000329
John McCalld226f652010-08-21 09:40:31 +0000330 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Mike Stump1eb44332009-09-09 15:08:12 +0000331
Anders Carlsson5e300d12009-06-12 16:51:40 +0000332 Param->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000333
Anders Carlsson5e300d12009-06-12 16:51:40 +0000334 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000335}
336
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000337/// CheckExtraCXXDefaultArguments - Check for any extra default
338/// arguments in the declarator, which is not a function declaration
339/// or definition and therefore is not permitted to have default
340/// arguments. This routine should be invoked for every declarator
341/// that is not a function declaration or definition.
342void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
343 // C++ [dcl.fct.default]p3
344 // A default argument expression shall be specified only in the
345 // parameter-declaration-clause of a function declaration or in a
346 // template-parameter (14.1). It shall not be specified for a
347 // parameter pack. If it is specified in a
348 // parameter-declaration-clause, it shall not occur within a
349 // declarator or abstract-declarator of a parameter-declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000350 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000351 DeclaratorChunk &chunk = D.getTypeObject(i);
352 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000353 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
354 ParmVarDecl *Param =
John McCalld226f652010-08-21 09:40:31 +0000355 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000356 if (Param->hasUnparsedDefaultArg()) {
357 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000358 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
359 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
360 delete Toks;
361 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor61366e92008-12-24 00:01:03 +0000362 } else if (Param->getDefaultArg()) {
363 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
364 << Param->getDefaultArg()->getSourceRange();
365 Param->setDefaultArg(0);
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000366 }
367 }
368 }
369 }
370}
371
Chris Lattner3d1cee32008-04-08 05:04:30 +0000372// MergeCXXFunctionDecl - Merge two declarations of the same C++
373// function, once we already know that they have the same
Douglas Gregorcda9c672009-02-16 17:45:42 +0000374// type. Subroutine of MergeFunctionDecl. Returns true if there was an
375// error, false otherwise.
376bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
377 bool Invalid = false;
378
Chris Lattner3d1cee32008-04-08 05:04:30 +0000379 // C++ [dcl.fct.default]p4:
Chris Lattner3d1cee32008-04-08 05:04:30 +0000380 // For non-template functions, default arguments can be added in
381 // later declarations of a function in the same
382 // scope. Declarations in different scopes have completely
383 // distinct sets of default arguments. That is, declarations in
384 // inner scopes do not acquire default arguments from
385 // declarations in outer scopes, and vice versa. In a given
386 // function declaration, all parameters subsequent to a
387 // parameter with a default argument shall have default
388 // arguments supplied in this or previous declarations. A
389 // default argument shall not be redefined by a later
390 // declaration (not even to the same value).
Douglas Gregor6cc15182009-09-11 18:44:32 +0000391 //
392 // C++ [dcl.fct.default]p6:
393 // Except for member functions of class templates, the default arguments
394 // in a member function definition that appears outside of the class
395 // definition are added to the set of default arguments provided by the
396 // member function declaration in the class definition.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000397 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
398 ParmVarDecl *OldParam = Old->getParamDecl(p);
399 ParmVarDecl *NewParam = New->getParamDecl(p);
400
Douglas Gregor6cc15182009-09-11 18:44:32 +0000401 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000402
Francois Pichet8d051e02011-04-10 03:03:52 +0000403 unsigned DiagDefaultParamID =
404 diag::err_param_default_argument_redefinition;
405
406 // MSVC accepts that default parameters be redefined for member functions
407 // of template class. The new default parameter's value is ignored.
408 Invalid = true;
Francois Pichet62ec1f22011-09-17 17:15:52 +0000409 if (getLangOptions().MicrosoftExt) {
Francois Pichet8d051e02011-04-10 03:03:52 +0000410 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
411 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000412 // Merge the old default argument into the new parameter.
413 NewParam->setHasInheritedDefaultArg();
414 if (OldParam->hasUninstantiatedDefaultArg())
415 NewParam->setUninstantiatedDefaultArg(
416 OldParam->getUninstantiatedDefaultArg());
417 else
418 NewParam->setDefaultArg(OldParam->getInit());
Francois Pichetcf320c62011-04-22 08:25:24 +0000419 DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
Francois Pichet8d051e02011-04-10 03:03:52 +0000420 Invalid = false;
421 }
422 }
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000423
Francois Pichet8cf90492011-04-10 04:58:30 +0000424 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
425 // hint here. Alternatively, we could walk the type-source information
426 // for NewParam to find the last source location in the type... but it
427 // isn't worth the effort right now. This is the kind of test case that
428 // is hard to get right:
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000429 // int f(int);
430 // void g(int (*fp)(int) = f);
431 // void g(int (*fp)(int) = &f);
Francois Pichet8d051e02011-04-10 03:03:52 +0000432 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000433 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000434
435 // Look for the function declaration where the default argument was
436 // actually written, which may be a declaration prior to Old.
Douglas Gregoref96ee02012-01-14 16:38:05 +0000437 for (FunctionDecl *Older = Old->getPreviousDecl();
438 Older; Older = Older->getPreviousDecl()) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000439 if (!Older->getParamDecl(p)->hasDefaultArg())
440 break;
441
442 OldParam = Older->getParamDecl(p);
443 }
444
445 Diag(OldParam->getLocation(), diag::note_previous_definition)
446 << OldParam->getDefaultArgRange();
Douglas Gregord85cef52009-09-17 19:51:30 +0000447 } else if (OldParam->hasDefaultArg()) {
John McCall3d6c1782010-05-04 01:53:42 +0000448 // Merge the old default argument into the new parameter.
449 // It's important to use getInit() here; getDefaultArg()
John McCall4765fa02010-12-06 08:20:24 +0000450 // strips off any top-level ExprWithCleanups.
John McCallbf73b352010-03-12 18:31:32 +0000451 NewParam->setHasInheritedDefaultArg();
Douglas Gregord85cef52009-09-17 19:51:30 +0000452 if (OldParam->hasUninstantiatedDefaultArg())
453 NewParam->setUninstantiatedDefaultArg(
454 OldParam->getUninstantiatedDefaultArg());
455 else
John McCall3d6c1782010-05-04 01:53:42 +0000456 NewParam->setDefaultArg(OldParam->getInit());
Douglas Gregor6cc15182009-09-11 18:44:32 +0000457 } else if (NewParam->hasDefaultArg()) {
458 if (New->getDescribedFunctionTemplate()) {
459 // Paragraph 4, quoted above, only applies to non-template functions.
460 Diag(NewParam->getLocation(),
461 diag::err_param_default_argument_template_redecl)
462 << NewParam->getDefaultArgRange();
463 Diag(Old->getLocation(), diag::note_template_prev_declaration)
464 << false;
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000465 } else if (New->getTemplateSpecializationKind()
466 != TSK_ImplicitInstantiation &&
467 New->getTemplateSpecializationKind() != TSK_Undeclared) {
468 // C++ [temp.expr.spec]p21:
469 // Default function arguments shall not be specified in a declaration
470 // or a definition for one of the following explicit specializations:
471 // - the explicit specialization of a function template;
Douglas Gregor8c638ab2009-10-13 23:52:38 +0000472 // - the explicit specialization of a member function template;
473 // - the explicit specialization of a member function of a class
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000474 // template where the class template specialization to which the
475 // member function specialization belongs is implicitly
476 // instantiated.
477 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
478 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
479 << New->getDeclName()
480 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000481 } else if (New->getDeclContext()->isDependentContext()) {
482 // C++ [dcl.fct.default]p6 (DR217):
483 // Default arguments for a member function of a class template shall
484 // be specified on the initial declaration of the member function
485 // within the class template.
486 //
487 // Reading the tea leaves a bit in DR217 and its reference to DR205
488 // leads me to the conclusion that one cannot add default function
489 // arguments for an out-of-line definition of a member function of a
490 // dependent type.
491 int WhichKind = 2;
492 if (CXXRecordDecl *Record
493 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
494 if (Record->getDescribedClassTemplate())
495 WhichKind = 0;
496 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
497 WhichKind = 1;
498 else
499 WhichKind = 2;
500 }
501
502 Diag(NewParam->getLocation(),
503 diag::err_param_default_argument_member_template_redecl)
504 << WhichKind
505 << NewParam->getDefaultArgRange();
Sean Hunt9ae60d52011-05-26 01:26:05 +0000506 } else if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(New)) {
507 CXXSpecialMember NewSM = getSpecialMember(Ctor),
508 OldSM = getSpecialMember(cast<CXXConstructorDecl>(Old));
509 if (NewSM != OldSM) {
510 Diag(NewParam->getLocation(),diag::warn_default_arg_makes_ctor_special)
511 << NewParam->getDefaultArgRange() << NewSM;
512 Diag(Old->getLocation(), diag::note_previous_declaration_special)
513 << OldSM;
514 }
Douglas Gregor6cc15182009-09-11 18:44:32 +0000515 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000516 }
517 }
518
Richard Smith9f569cc2011-10-01 02:31:28 +0000519 // C++0x [dcl.constexpr]p1: If any declaration of a function or function
520 // template has a constexpr specifier then all its declarations shall
521 // contain the constexpr specifier. [Note: An explicit specialization can
522 // differ from the template declaration with respect to the constexpr
523 // specifier. -- end note]
524 //
525 // FIXME: Don't reject changes in constexpr in explicit specializations.
526 if (New->isConstexpr() != Old->isConstexpr()) {
527 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
528 << New << New->isConstexpr();
529 Diag(Old->getLocation(), diag::note_previous_declaration);
530 Invalid = true;
531 }
532
Douglas Gregore13ad832010-02-12 07:32:17 +0000533 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000534 Invalid = true;
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000535
Douglas Gregorcda9c672009-02-16 17:45:42 +0000536 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000537}
538
Sebastian Redl60618fa2011-03-12 11:50:43 +0000539/// \brief Merge the exception specifications of two variable declarations.
540///
541/// This is called when there's a redeclaration of a VarDecl. The function
542/// checks if the redeclaration might have an exception specification and
543/// validates compatibility and merges the specs if necessary.
544void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
545 // Shortcut if exceptions are disabled.
546 if (!getLangOptions().CXXExceptions)
547 return;
548
549 assert(Context.hasSameType(New->getType(), Old->getType()) &&
550 "Should only be called if types are otherwise the same.");
551
552 QualType NewType = New->getType();
553 QualType OldType = Old->getType();
554
555 // We're only interested in pointers and references to functions, as well
556 // as pointers to member functions.
557 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
558 NewType = R->getPointeeType();
559 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
560 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
561 NewType = P->getPointeeType();
562 OldType = OldType->getAs<PointerType>()->getPointeeType();
563 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
564 NewType = M->getPointeeType();
565 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
566 }
567
568 if (!NewType->isFunctionProtoType())
569 return;
570
571 // There's lots of special cases for functions. For function pointers, system
572 // libraries are hopefully not as broken so that we don't need these
573 // workarounds.
574 if (CheckEquivalentExceptionSpec(
575 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
576 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
577 New->setInvalidDecl();
578 }
579}
580
Chris Lattner3d1cee32008-04-08 05:04:30 +0000581/// CheckCXXDefaultArguments - Verify that the default arguments for a
582/// function declaration are well-formed according to C++
583/// [dcl.fct.default].
584void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
585 unsigned NumParams = FD->getNumParams();
586 unsigned p;
587
Douglas Gregorc6889e72012-02-14 22:28:59 +0000588 bool IsLambda = FD->getOverloadedOperator() == OO_Call &&
589 isa<CXXMethodDecl>(FD) &&
590 cast<CXXMethodDecl>(FD)->getParent()->isLambda();
591
Chris Lattner3d1cee32008-04-08 05:04:30 +0000592 // Find first parameter with a default argument
593 for (p = 0; p < NumParams; ++p) {
594 ParmVarDecl *Param = FD->getParamDecl(p);
Douglas Gregorc6889e72012-02-14 22:28:59 +0000595 if (Param->hasDefaultArg()) {
596 // C++11 [expr.prim.lambda]p5:
597 // [...] Default arguments (8.3.6) shall not be specified in the
598 // parameter-declaration-clause of a lambda-declarator.
599 //
600 // FIXME: Core issue 974 strikes this sentence, we only provide an
601 // extension warning.
602 if (IsLambda)
603 Diag(Param->getLocation(), diag::ext_lambda_default_arguments)
604 << Param->getDefaultArgRange();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000605 break;
Douglas Gregorc6889e72012-02-14 22:28:59 +0000606 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000607 }
608
609 // C++ [dcl.fct.default]p4:
610 // In a given function declaration, all parameters
611 // subsequent to a parameter with a default argument shall
612 // have default arguments supplied in this or previous
613 // declarations. A default argument shall not be redefined
614 // by a later declaration (not even to the same value).
615 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000616 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000617 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000618 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000619 if (Param->isInvalidDecl())
620 /* We already complained about this parameter. */;
621 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000622 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000623 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000624 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000625 else
Mike Stump1eb44332009-09-09 15:08:12 +0000626 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000627 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000628
Chris Lattner3d1cee32008-04-08 05:04:30 +0000629 LastMissingDefaultArg = p;
630 }
631 }
632
633 if (LastMissingDefaultArg > 0) {
634 // Some default arguments were missing. Clear out all of the
635 // default arguments up to (and including) the last missing
636 // default argument, so that we leave the function parameters
637 // in a semantically valid state.
638 for (p = 0; p <= LastMissingDefaultArg; ++p) {
639 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000640 if (Param->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000641 Param->setDefaultArg(0);
642 }
643 }
644 }
645}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000646
Richard Smith9f569cc2011-10-01 02:31:28 +0000647// CheckConstexprParameterTypes - Check whether a function's parameter types
648// are all literal types. If so, return true. If not, produce a suitable
Richard Smith86c3ae42012-02-13 03:54:03 +0000649// diagnostic and return false.
650static bool CheckConstexprParameterTypes(Sema &SemaRef,
651 const FunctionDecl *FD) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000652 unsigned ArgIndex = 0;
653 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
654 for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(),
655 e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) {
656 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
657 SourceLocation ParamLoc = PD->getLocation();
658 if (!(*i)->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000659 SemaRef.RequireLiteralType(ParamLoc, *i,
Richard Smith9f569cc2011-10-01 02:31:28 +0000660 SemaRef.PDiag(diag::err_constexpr_non_literal_param)
661 << ArgIndex+1 << PD->getSourceRange()
Richard Smith86c3ae42012-02-13 03:54:03 +0000662 << isa<CXXConstructorDecl>(FD)))
Richard Smith9f569cc2011-10-01 02:31:28 +0000663 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000664 }
665 return true;
666}
667
668// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
Richard Smith86c3ae42012-02-13 03:54:03 +0000669// the requirements of a constexpr function definition or a constexpr
670// constructor definition. If so, return true. If not, produce appropriate
671// diagnostics and return false.
Richard Smith9f569cc2011-10-01 02:31:28 +0000672//
Richard Smith86c3ae42012-02-13 03:54:03 +0000673// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
674bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
Richard Smith35340502012-01-13 04:54:00 +0000675 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
676 if (MD && MD->isInstance()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000677 // C++11 [dcl.constexpr]p4:
678 // The definition of a constexpr constructor shall satisfy the following
679 // constraints:
Richard Smith9f569cc2011-10-01 02:31:28 +0000680 // - the class shall not have any virtual base classes;
Richard Smith35340502012-01-13 04:54:00 +0000681 const CXXRecordDecl *RD = MD->getParent();
Richard Smith9f569cc2011-10-01 02:31:28 +0000682 if (RD->getNumVBases()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000683 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
684 << isa<CXXConstructorDecl>(NewFD) << RD->isStruct()
685 << RD->getNumVBases();
686 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
687 E = RD->vbases_end(); I != E; ++I)
688 Diag(I->getSourceRange().getBegin(),
689 diag::note_constexpr_virtual_base_here) << I->getSourceRange();
Richard Smith9f569cc2011-10-01 02:31:28 +0000690 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()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000701 Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
Richard Smith9f569cc2011-10-01 02:31:28 +0000702
Richard Smith86c3ae42012-02-13 03:54:03 +0000703 // If it's not obvious why this function is virtual, find an overridden
704 // function which uses the 'virtual' keyword.
705 const CXXMethodDecl *WrittenVirtual = Method;
706 while (!WrittenVirtual->isVirtualAsWritten())
707 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
708 if (WrittenVirtual != Method)
709 Diag(WrittenVirtual->getLocation(),
710 diag::note_overridden_virtual_function);
Richard Smith9f569cc2011-10-01 02:31:28 +0000711 return false;
712 }
713
714 // - its return type shall be a literal type;
715 QualType RT = NewFD->getResultType();
716 if (!RT->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000717 RequireLiteralType(NewFD->getLocation(), RT,
718 PDiag(diag::err_constexpr_non_literal_return)))
Richard Smith9f569cc2011-10-01 02:31:28 +0000719 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000720 }
721
Richard Smith35340502012-01-13 04:54:00 +0000722 // - each of its parameter types shall be a literal type;
Richard Smith86c3ae42012-02-13 03:54:03 +0000723 if (!CheckConstexprParameterTypes(*this, NewFD))
Richard Smith35340502012-01-13 04:54:00 +0000724 return false;
725
Richard Smith9f569cc2011-10-01 02:31:28 +0000726 return true;
727}
728
729/// Check the given declaration statement is legal within a constexpr function
730/// body. C++0x [dcl.constexpr]p3,p4.
731///
732/// \return true if the body is OK, false if we have diagnosed a problem.
733static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
734 DeclStmt *DS) {
735 // C++0x [dcl.constexpr]p3 and p4:
736 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
737 // contain only
738 for (DeclStmt::decl_iterator DclIt = DS->decl_begin(),
739 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
740 switch ((*DclIt)->getKind()) {
741 case Decl::StaticAssert:
742 case Decl::Using:
743 case Decl::UsingShadow:
744 case Decl::UsingDirective:
745 case Decl::UnresolvedUsingTypename:
746 // - static_assert-declarations
747 // - using-declarations,
748 // - using-directives,
749 continue;
750
751 case Decl::Typedef:
752 case Decl::TypeAlias: {
753 // - typedef declarations and alias-declarations that do not define
754 // classes or enumerations,
755 TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt);
756 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
757 // Don't allow variably-modified types in constexpr functions.
758 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
759 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
760 << TL.getSourceRange() << TL.getType()
761 << isa<CXXConstructorDecl>(Dcl);
762 return false;
763 }
764 continue;
765 }
766
767 case Decl::Enum:
768 case Decl::CXXRecord:
769 // As an extension, we allow the declaration (but not the definition) of
770 // classes and enumerations in all declarations, not just in typedef and
771 // alias declarations.
772 if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition()) {
773 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_type_definition)
774 << isa<CXXConstructorDecl>(Dcl);
775 return false;
776 }
777 continue;
778
779 case Decl::Var:
780 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_var_declaration)
781 << isa<CXXConstructorDecl>(Dcl);
782 return false;
783
784 default:
785 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
786 << isa<CXXConstructorDecl>(Dcl);
787 return false;
788 }
789 }
790
791 return true;
792}
793
794/// Check that the given field is initialized within a constexpr constructor.
795///
796/// \param Dcl The constexpr constructor being checked.
797/// \param Field The field being checked. This may be a member of an anonymous
798/// struct or union nested within the class being checked.
799/// \param Inits All declarations, including anonymous struct/union members and
800/// indirect members, for which any initialization was provided.
801/// \param Diagnosed Set to true if an error is produced.
802static void CheckConstexprCtorInitializer(Sema &SemaRef,
803 const FunctionDecl *Dcl,
804 FieldDecl *Field,
805 llvm::SmallSet<Decl*, 16> &Inits,
806 bool &Diagnosed) {
Douglas Gregord61db332011-10-10 17:22:13 +0000807 if (Field->isUnnamedBitfield())
808 return;
Richard Smith30ecfad2012-02-09 06:40:58 +0000809
810 if (Field->isAnonymousStructOrUnion() &&
811 Field->getType()->getAsCXXRecordDecl()->isEmpty())
812 return;
813
Richard Smith9f569cc2011-10-01 02:31:28 +0000814 if (!Inits.count(Field)) {
815 if (!Diagnosed) {
816 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
817 Diagnosed = true;
818 }
819 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
820 } else if (Field->isAnonymousStructOrUnion()) {
821 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
822 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
823 I != E; ++I)
824 // If an anonymous union contains an anonymous struct of which any member
825 // is initialized, all members must be initialized.
826 if (!RD->isUnion() || Inits.count(*I))
827 CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed);
828 }
829}
830
831/// Check the body for the given constexpr function declaration only contains
832/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
833///
834/// \return true if the body is OK, false if we have diagnosed a problem.
Richard Smith86c3ae42012-02-13 03:54:03 +0000835bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000836 if (isa<CXXTryStmt>(Body)) {
Richard Smith5ba73e12012-02-04 00:33:54 +0000837 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +0000838 // The definition of a constexpr function shall satisfy the following
839 // constraints: [...]
840 // - its function-body shall be = delete, = default, or a
841 // compound-statement
842 //
Richard Smith5ba73e12012-02-04 00:33:54 +0000843 // C++11 [dcl.constexpr]p4:
Richard Smith9f569cc2011-10-01 02:31:28 +0000844 // In the definition of a constexpr constructor, [...]
845 // - its function-body shall not be a function-try-block;
846 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
847 << isa<CXXConstructorDecl>(Dcl);
848 return false;
849 }
850
851 // - its function-body shall be [...] a compound-statement that contains only
852 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
853
854 llvm::SmallVector<SourceLocation, 4> ReturnStmts;
855 for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(),
856 BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) {
857 switch ((*BodyIt)->getStmtClass()) {
858 case Stmt::NullStmtClass:
859 // - null statements,
860 continue;
861
862 case Stmt::DeclStmtClass:
863 // - static_assert-declarations
864 // - using-declarations,
865 // - using-directives,
866 // - typedef declarations and alias-declarations that do not define
867 // classes or enumerations,
868 if (!CheckConstexprDeclStmt(*this, Dcl, cast<DeclStmt>(*BodyIt)))
869 return false;
870 continue;
871
872 case Stmt::ReturnStmtClass:
873 // - and exactly one return statement;
874 if (isa<CXXConstructorDecl>(Dcl))
875 break;
876
877 ReturnStmts.push_back((*BodyIt)->getLocStart());
878 // FIXME
879 // - every constructor call and implicit conversion used in initializing
880 // the return value shall be one of those allowed in a constant
881 // expression.
882 // Deal with this as part of a general check that the function can produce
883 // a constant expression (for [dcl.constexpr]p5).
884 continue;
885
886 default:
887 break;
888 }
889
890 Diag((*BodyIt)->getLocStart(), diag::err_constexpr_body_invalid_stmt)
891 << isa<CXXConstructorDecl>(Dcl);
892 return false;
893 }
894
895 if (const CXXConstructorDecl *Constructor
896 = dyn_cast<CXXConstructorDecl>(Dcl)) {
897 const CXXRecordDecl *RD = Constructor->getParent();
Richard Smith30ecfad2012-02-09 06:40:58 +0000898 // DR1359:
899 // - every non-variant non-static data member and base class sub-object
900 // shall be initialized;
901 // - if the class is a non-empty union, or for each non-empty anonymous
902 // union member of a non-union class, exactly one non-static data member
903 // shall be initialized;
Richard Smith9f569cc2011-10-01 02:31:28 +0000904 if (RD->isUnion()) {
Richard Smith30ecfad2012-02-09 06:40:58 +0000905 if (Constructor->getNumCtorInitializers() == 0 && !RD->isEmpty()) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000906 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
907 return false;
908 }
Richard Smith6e433752011-10-10 16:38:04 +0000909 } else if (!Constructor->isDependentContext() &&
910 !Constructor->isDelegatingConstructor()) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000911 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
912
913 // Skip detailed checking if we have enough initializers, and we would
914 // allow at most one initializer per member.
915 bool AnyAnonStructUnionMembers = false;
916 unsigned Fields = 0;
917 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
918 E = RD->field_end(); I != E; ++I, ++Fields) {
919 if ((*I)->isAnonymousStructOrUnion()) {
920 AnyAnonStructUnionMembers = true;
921 break;
922 }
923 }
924 if (AnyAnonStructUnionMembers ||
925 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
926 // Check initialization of non-static data members. Base classes are
927 // always initialized so do not need to be checked. Dependent bases
928 // might not have initializers in the member initializer list.
929 llvm::SmallSet<Decl*, 16> Inits;
930 for (CXXConstructorDecl::init_const_iterator
931 I = Constructor->init_begin(), E = Constructor->init_end();
932 I != E; ++I) {
933 if (FieldDecl *FD = (*I)->getMember())
934 Inits.insert(FD);
935 else if (IndirectFieldDecl *ID = (*I)->getIndirectMember())
936 Inits.insert(ID->chain_begin(), ID->chain_end());
937 }
938
939 bool Diagnosed = false;
940 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
941 E = RD->field_end(); I != E; ++I)
942 CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed);
943 if (Diagnosed)
944 return false;
945 }
946 }
947
948 // FIXME
949 // - every constructor involved in initializing non-static data members
950 // and base class sub-objects shall be a constexpr constructor;
951 // - every assignment-expression that is an initializer-clause appearing
952 // directly or indirectly within a brace-or-equal-initializer for
953 // a non-static data member that is not named by a mem-initializer-id
954 // shall be a constant expression; and
955 // - every implicit conversion used in converting a constructor argument
956 // to the corresponding parameter type and converting
957 // a full-expression to the corresponding member type shall be one of
958 // those allowed in a constant expression.
959 // Deal with these as part of a general check that the function can produce
960 // a constant expression (for [dcl.constexpr]p5).
961 } else {
962 if (ReturnStmts.empty()) {
963 Diag(Dcl->getLocation(), diag::err_constexpr_body_no_return);
964 return false;
965 }
966 if (ReturnStmts.size() > 1) {
967 Diag(ReturnStmts.back(), diag::err_constexpr_body_multiple_return);
968 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
969 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
970 return false;
971 }
972 }
973
Richard Smith5ba73e12012-02-04 00:33:54 +0000974 // C++11 [dcl.constexpr]p5:
975 // if no function argument values exist such that the function invocation
976 // substitution would produce a constant expression, the program is
977 // ill-formed; no diagnostic required.
978 // C++11 [dcl.constexpr]p3:
979 // - every constructor call and implicit conversion used in initializing the
980 // return value shall be one of those allowed in a constant expression.
981 // C++11 [dcl.constexpr]p4:
982 // - every constructor involved in initializing non-static data members and
983 // base class sub-objects shall be a constexpr constructor.
Richard Smith745f5142012-01-27 01:14:48 +0000984 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith86c3ae42012-02-13 03:54:03 +0000985 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smith745f5142012-01-27 01:14:48 +0000986 Diag(Dcl->getLocation(), diag::err_constexpr_function_never_constant_expr)
987 << isa<CXXConstructorDecl>(Dcl);
988 for (size_t I = 0, N = Diags.size(); I != N; ++I)
989 Diag(Diags[I].first, Diags[I].second);
990 return false;
991 }
992
Richard Smith9f569cc2011-10-01 02:31:28 +0000993 return true;
994}
995
Douglas Gregorb48fe382008-10-31 09:07:45 +0000996/// isCurrentClassName - Determine whether the identifier II is the
997/// name of the class type currently being defined. In the case of
998/// nested classes, this will only return true if II is the name of
999/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00001000bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1001 const CXXScopeSpec *SS) {
Douglas Gregorb862b8f2010-01-11 23:29:10 +00001002 assert(getLangOptions().CPlusPlus && "No class names in C!");
1003
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001004 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +00001005 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +00001006 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001007 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1008 } else
1009 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1010
Douglas Gregor6f7a17b2010-02-05 06:12:42 +00001011 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregorb48fe382008-10-31 09:07:45 +00001012 return &II == CurDecl->getIdentifier();
1013 else
1014 return false;
1015}
1016
Mike Stump1eb44332009-09-09 15:08:12 +00001017/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001018///
1019/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1020/// and returns NULL otherwise.
1021CXXBaseSpecifier *
1022Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1023 SourceRange SpecifierRange,
1024 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001025 TypeSourceInfo *TInfo,
1026 SourceLocation EllipsisLoc) {
Nick Lewycky56062202010-07-26 16:56:01 +00001027 QualType BaseType = TInfo->getType();
1028
Douglas Gregor2943aed2009-03-03 04:44:36 +00001029 // C++ [class.union]p1:
1030 // A union shall not have base classes.
1031 if (Class->isUnion()) {
1032 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1033 << SpecifierRange;
1034 return 0;
1035 }
1036
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001037 if (EllipsisLoc.isValid() &&
1038 !TInfo->getType()->containsUnexpandedParameterPack()) {
1039 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1040 << TInfo->getTypeLoc().getSourceRange();
1041 EllipsisLoc = SourceLocation();
1042 }
1043
Douglas Gregor2943aed2009-03-03 04:44:36 +00001044 if (BaseType->isDependentType())
Mike Stump1eb44332009-09-09 15:08:12 +00001045 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001046 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001047 Access, TInfo, EllipsisLoc);
Nick Lewycky56062202010-07-26 16:56:01 +00001048
1049 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001050
1051 // Base specifiers must be record types.
1052 if (!BaseType->isRecordType()) {
1053 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1054 return 0;
1055 }
1056
1057 // C++ [class.union]p1:
1058 // A union shall not be used as a base class.
1059 if (BaseType->isUnionType()) {
1060 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1061 return 0;
1062 }
1063
1064 // C++ [class.derived]p2:
1065 // The class-name in a base-specifier shall not be an incompletely
1066 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +00001067 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssonb7906612009-08-26 23:45:07 +00001068 PDiag(diag::err_incomplete_base_class)
John McCall572fc622010-08-17 07:23:57 +00001069 << SpecifierRange)) {
1070 Class->setInvalidDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001071 return 0;
John McCall572fc622010-08-17 07:23:57 +00001072 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001073
Eli Friedman1d954f62009-08-15 21:55:26 +00001074 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +00001075 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001076 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor952b0172010-02-11 01:04:33 +00001077 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001078 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedman1d954f62009-08-15 21:55:26 +00001079 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
1080 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +00001081
Anders Carlsson1d209272011-03-25 14:55:14 +00001082 // C++ [class]p3:
1083 // If a class is marked final and it appears as a base-type-specifier in
1084 // base-clause, the program is ill-formed.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001085 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
Anders Carlssondfc2f102011-01-22 17:51:53 +00001086 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1087 << CXXBaseDecl->getDeclName();
1088 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1089 << CXXBaseDecl->getDeclName();
1090 return 0;
1091 }
1092
John McCall572fc622010-08-17 07:23:57 +00001093 if (BaseDecl->isInvalidDecl())
1094 Class->setInvalidDecl();
Anders Carlsson51f94042009-12-03 17:49:57 +00001095
1096 // Create the base specifier.
Anders Carlsson51f94042009-12-03 17:49:57 +00001097 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001098 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001099 Access, TInfo, EllipsisLoc);
Anders Carlsson51f94042009-12-03 17:49:57 +00001100}
1101
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001102/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1103/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +00001104/// example:
1105/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001106/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallf312b1e2010-08-26 23:41:50 +00001107BaseResult
John McCalld226f652010-08-21 09:40:31 +00001108Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001109 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001110 ParsedType basetype, SourceLocation BaseLoc,
1111 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001112 if (!classdecl)
1113 return true;
1114
Douglas Gregor40808ce2009-03-09 23:48:35 +00001115 AdjustDeclIfTemplate(classdecl);
John McCalld226f652010-08-21 09:40:31 +00001116 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregor5fe8c042010-02-27 00:25:28 +00001117 if (!Class)
1118 return true;
1119
Nick Lewycky56062202010-07-26 16:56:01 +00001120 TypeSourceInfo *TInfo = 0;
1121 GetTypeFromParser(basetype, &TInfo);
Douglas Gregord0937222010-12-13 22:49:22 +00001122
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001123 if (EllipsisLoc.isInvalid() &&
1124 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregord0937222010-12-13 22:49:22 +00001125 UPPC_BaseType))
1126 return true;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001127
Douglas Gregor2943aed2009-03-03 04:44:36 +00001128 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001129 Virtual, Access, TInfo,
1130 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +00001131 return BaseSpec;
Mike Stump1eb44332009-09-09 15:08:12 +00001132
Douglas Gregor2943aed2009-03-03 04:44:36 +00001133 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001134}
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001135
Douglas Gregor2943aed2009-03-03 04:44:36 +00001136/// \brief Performs the actual work of attaching the given base class
1137/// specifiers to a C++ class.
1138bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1139 unsigned NumBases) {
1140 if (NumBases == 0)
1141 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001142
1143 // Used to keep track of which base types we have already seen, so
1144 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +00001145 // that the key is always the unqualified canonical type of the base
1146 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001147 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1148
1149 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +00001150 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +00001151 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +00001152 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001153 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +00001154 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +00001155 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001156 if (KnownBaseTypes[NewBaseType]) {
1157 // C++ [class.mi]p3:
1158 // A class shall not be specified as a direct base class of a
1159 // derived class more than once.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001160 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001161 diag::err_duplicate_base_class)
Chris Lattnerd1625842008-11-24 06:25:27 +00001162 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +00001163 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +00001164
1165 // Delete the duplicate base class specifier; we're going to
1166 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001167 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001168
1169 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001170 } else {
1171 // Okay, add this new base class.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001172 KnownBaseTypes[NewBaseType] = Bases[idx];
1173 Bases[NumGoodBases++] = Bases[idx];
Fariborz Jahanian91589022011-10-24 17:30:45 +00001174 if (const RecordType *Record = NewBaseType->getAs<RecordType>())
Fariborz Jahanian13c7fcc2011-10-21 22:27:12 +00001175 if (const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()))
1176 if (RD->hasAttr<WeakAttr>())
1177 Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context));
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001178 }
1179 }
1180
1181 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +00001182 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +00001183
1184 // Delete the remaining (good) base class specifiers, since their
1185 // data has been copied into the CXXRecordDecl.
1186 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001187 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001188
1189 return Invalid;
1190}
1191
1192/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1193/// class, after checking whether there are any duplicate base
1194/// classes.
Richard Trieu90ab75b2011-09-09 03:18:59 +00001195void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001196 unsigned NumBases) {
1197 if (!ClassDecl || !Bases || !NumBases)
1198 return;
1199
1200 AdjustDeclIfTemplate(ClassDecl);
John McCalld226f652010-08-21 09:40:31 +00001201 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor2943aed2009-03-03 04:44:36 +00001202 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001203}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001204
John McCall3cb0ebd2010-03-10 03:28:59 +00001205static CXXRecordDecl *GetClassForType(QualType T) {
1206 if (const RecordType *RT = T->getAs<RecordType>())
1207 return cast<CXXRecordDecl>(RT->getDecl());
1208 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
1209 return ICT->getDecl();
1210 else
1211 return 0;
1212}
1213
Douglas Gregora8f32e02009-10-06 17:59:45 +00001214/// \brief Determine whether the type \p Derived is a C++ class that is
1215/// derived from the type \p Base.
1216bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
1217 if (!getLangOptions().CPlusPlus)
1218 return false;
John McCall3cb0ebd2010-03-10 03:28:59 +00001219
1220 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1221 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001222 return false;
1223
John McCall3cb0ebd2010-03-10 03:28:59 +00001224 CXXRecordDecl *BaseRD = GetClassForType(Base);
1225 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001226 return false;
1227
John McCall86ff3082010-02-04 22:26:26 +00001228 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1229 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001230}
1231
1232/// \brief Determine whether the type \p Derived is a C++ class that is
1233/// derived from the type \p Base.
1234bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
1235 if (!getLangOptions().CPlusPlus)
1236 return false;
1237
John McCall3cb0ebd2010-03-10 03:28:59 +00001238 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1239 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001240 return false;
1241
John McCall3cb0ebd2010-03-10 03:28:59 +00001242 CXXRecordDecl *BaseRD = GetClassForType(Base);
1243 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001244 return false;
1245
Douglas Gregora8f32e02009-10-06 17:59:45 +00001246 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1247}
1248
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001249void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallf871d0c2010-08-07 06:22:56 +00001250 CXXCastPath &BasePathArray) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001251 assert(BasePathArray.empty() && "Base path array must be empty!");
1252 assert(Paths.isRecordingPaths() && "Must record paths!");
1253
1254 const CXXBasePath &Path = Paths.front();
1255
1256 // We first go backward and check if we have a virtual base.
1257 // FIXME: It would be better if CXXBasePath had the base specifier for
1258 // the nearest virtual base.
1259 unsigned Start = 0;
1260 for (unsigned I = Path.size(); I != 0; --I) {
1261 if (Path[I - 1].Base->isVirtual()) {
1262 Start = I - 1;
1263 break;
1264 }
1265 }
1266
1267 // Now add all bases.
1268 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallf871d0c2010-08-07 06:22:56 +00001269 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001270}
1271
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001272/// \brief Determine whether the given base path includes a virtual
1273/// base class.
John McCallf871d0c2010-08-07 06:22:56 +00001274bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1275 for (CXXCastPath::const_iterator B = BasePath.begin(),
1276 BEnd = BasePath.end();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001277 B != BEnd; ++B)
1278 if ((*B)->isVirtual())
1279 return true;
1280
1281 return false;
1282}
1283
Douglas Gregora8f32e02009-10-06 17:59:45 +00001284/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1285/// conversion (where Derived and Base are class types) is
1286/// well-formed, meaning that the conversion is unambiguous (and
1287/// that all of the base classes are accessible). Returns true
1288/// and emits a diagnostic if the code is ill-formed, returns false
1289/// otherwise. Loc is the location where this routine should point to
1290/// if there is an error, and Range is the source range to highlight
1291/// if there is an error.
1292bool
1293Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall58e6f342010-03-16 05:22:47 +00001294 unsigned InaccessibleBaseID,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001295 unsigned AmbigiousBaseConvID,
1296 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001297 DeclarationName Name,
John McCallf871d0c2010-08-07 06:22:56 +00001298 CXXCastPath *BasePath) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001299 // First, determine whether the path from Derived to Base is
1300 // ambiguous. This is slightly more expensive than checking whether
1301 // the Derived to Base conversion exists, because here we need to
1302 // explore multiple paths to determine if there is an ambiguity.
1303 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1304 /*DetectVirtual=*/false);
1305 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1306 assert(DerivationOkay &&
1307 "Can only be used with a derived-to-base conversion");
1308 (void)DerivationOkay;
1309
1310 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001311 if (InaccessibleBaseID) {
1312 // Check that the base class can be accessed.
1313 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1314 InaccessibleBaseID)) {
1315 case AR_inaccessible:
1316 return true;
1317 case AR_accessible:
1318 case AR_dependent:
1319 case AR_delayed:
1320 break;
Anders Carlssone25a96c2010-04-24 17:11:09 +00001321 }
John McCall6b2accb2010-02-10 09:31:12 +00001322 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001323
1324 // Build a base path if necessary.
1325 if (BasePath)
1326 BuildBasePathArray(Paths, *BasePath);
1327 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001328 }
1329
1330 // We know that the derived-to-base conversion is ambiguous, and
1331 // we're going to produce a diagnostic. Perform the derived-to-base
1332 // search just one more time to compute all of the possible paths so
1333 // that we can print them out. This is more expensive than any of
1334 // the previous derived-to-base checks we've done, but at this point
1335 // performance isn't as much of an issue.
1336 Paths.clear();
1337 Paths.setRecordingPaths(true);
1338 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1339 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1340 (void)StillOkay;
1341
1342 // Build up a textual representation of the ambiguous paths, e.g.,
1343 // D -> B -> A, that will be used to illustrate the ambiguous
1344 // conversions in the diagnostic. We only print one of the paths
1345 // to each base class subobject.
1346 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1347
1348 Diag(Loc, AmbigiousBaseConvID)
1349 << Derived << Base << PathDisplayStr << Range << Name;
1350 return true;
1351}
1352
1353bool
1354Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001355 SourceLocation Loc, SourceRange Range,
John McCallf871d0c2010-08-07 06:22:56 +00001356 CXXCastPath *BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001357 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001358 return CheckDerivedToBaseConversion(Derived, Base,
John McCall58e6f342010-03-16 05:22:47 +00001359 IgnoreAccess ? 0
1360 : diag::err_upcast_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001361 diag::err_ambiguous_derived_to_base_conv,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001362 Loc, Range, DeclarationName(),
1363 BasePath);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001364}
1365
1366
1367/// @brief Builds a string representing ambiguous paths from a
1368/// specific derived class to different subobjects of the same base
1369/// class.
1370///
1371/// This function builds a string that can be used in error messages
1372/// to show the different paths that one can take through the
1373/// inheritance hierarchy to go from the derived class to different
1374/// subobjects of a base class. The result looks something like this:
1375/// @code
1376/// struct D -> struct B -> struct A
1377/// struct D -> struct C -> struct A
1378/// @endcode
1379std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1380 std::string PathDisplayStr;
1381 std::set<unsigned> DisplayedPaths;
1382 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1383 Path != Paths.end(); ++Path) {
1384 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1385 // We haven't displayed a path to this particular base
1386 // class subobject yet.
1387 PathDisplayStr += "\n ";
1388 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1389 for (CXXBasePath::const_iterator Element = Path->begin();
1390 Element != Path->end(); ++Element)
1391 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1392 }
1393 }
1394
1395 return PathDisplayStr;
1396}
1397
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001398//===----------------------------------------------------------------------===//
1399// C++ class member Handling
1400//===----------------------------------------------------------------------===//
1401
Abramo Bagnara6206d532010-06-05 05:09:32 +00001402/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001403bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1404 SourceLocation ASLoc,
1405 SourceLocation ColonLoc,
1406 AttributeList *Attrs) {
Abramo Bagnara6206d532010-06-05 05:09:32 +00001407 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCalld226f652010-08-21 09:40:31 +00001408 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnara6206d532010-06-05 05:09:32 +00001409 ASLoc, ColonLoc);
1410 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001411 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnara6206d532010-06-05 05:09:32 +00001412}
1413
Anders Carlsson9e682d92011-01-20 05:57:14 +00001414/// CheckOverrideControl - Check C++0x override control semantics.
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001415void Sema::CheckOverrideControl(const Decl *D) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001416 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001417 if (!MD || !MD->isVirtual())
1418 return;
1419
Anders Carlsson3ffe1832011-01-20 06:33:26 +00001420 if (MD->isDependentContext())
1421 return;
1422
Anders Carlsson9e682d92011-01-20 05:57:14 +00001423 // C++0x [class.virtual]p3:
1424 // If a virtual function is marked with the virt-specifier override and does
1425 // not override a member function of a base class,
1426 // the program is ill-formed.
1427 bool HasOverriddenMethods =
1428 MD->begin_overridden_methods() != MD->end_overridden_methods();
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001429 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) {
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001430 Diag(MD->getLocation(),
Anders Carlsson9e682d92011-01-20 05:57:14 +00001431 diag::err_function_marked_override_not_overriding)
1432 << MD->getDeclName();
1433 return;
1434 }
1435}
1436
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001437/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
1438/// function overrides a virtual member function marked 'final', according to
1439/// C++0x [class.virtual]p3.
1440bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1441 const CXXMethodDecl *Old) {
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001442 if (!Old->hasAttr<FinalAttr>())
Anders Carlssonf89e0422011-01-23 21:07:30 +00001443 return false;
1444
1445 Diag(New->getLocation(), diag::err_final_function_overridden)
1446 << New->getDeclName();
1447 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1448 return true;
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001449}
1450
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001451/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1452/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith7a614d82011-06-11 17:19:42 +00001453/// bitfield width if there is one, 'InitExpr' specifies the initializer if
1454/// one has been parsed, and 'HasDeferredInit' is true if an initializer is
1455/// present but parsing it has been deferred.
John McCalld226f652010-08-21 09:40:31 +00001456Decl *
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001457Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +00001458 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001459 Expr *BW, const VirtSpecifiers &VS,
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00001460 bool HasDeferredInit) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001461 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00001462 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1463 DeclarationName Name = NameInfo.getName();
1464 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001465
1466 // For anonymous bitfields, the location should point to the type.
1467 if (Loc.isInvalid())
1468 Loc = D.getSourceRange().getBegin();
1469
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001470 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001471
John McCall4bde1e12010-06-04 08:34:12 +00001472 assert(isa<CXXRecordDecl>(CurContext));
John McCall67d1a672009-08-06 02:15:43 +00001473 assert(!DS.isFriendSpecified());
1474
Richard Smith1ab0d902011-06-25 02:28:38 +00001475 bool isFunc = D.isDeclarationOfFunction();
John McCall4bde1e12010-06-04 08:34:12 +00001476
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001477 // C++ 9.2p6: A member shall not be declared to have automatic storage
1478 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001479 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1480 // data members and cannot be applied to names declared const or static,
1481 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001482 switch (DS.getStorageClassSpec()) {
1483 case DeclSpec::SCS_unspecified:
1484 case DeclSpec::SCS_typedef:
1485 case DeclSpec::SCS_static:
1486 // FALL THROUGH.
1487 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +00001488 case DeclSpec::SCS_mutable:
1489 if (isFunc) {
1490 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001491 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +00001492 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001493 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +00001494
Sebastian Redla11f42f2008-11-17 23:24:37 +00001495 // FIXME: It would be nicer if the keyword was ignored only for this
1496 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001497 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redl669d5d72008-11-14 23:42:31 +00001498 }
1499 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001500 default:
1501 if (DS.getStorageClassSpecLoc().isValid())
1502 Diag(DS.getStorageClassSpecLoc(),
1503 diag::err_storageclass_invalid_for_member);
1504 else
1505 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
1506 D.getMutableDeclSpec().ClearStorageClassSpecs();
1507 }
1508
Sebastian Redl669d5d72008-11-14 23:42:31 +00001509 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1510 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +00001511 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001512
1513 Decl *Member;
Chris Lattner24793662009-03-05 22:45:59 +00001514 if (isInstField) {
Douglas Gregor922fff22010-10-13 22:19:53 +00001515 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorb5a01872011-10-09 18:55:59 +00001516
1517 // Data members must have identifiers for names.
1518 if (Name.getNameKind() != DeclarationName::Identifier) {
1519 Diag(Loc, diag::err_bad_variable_name)
1520 << Name;
1521 return 0;
1522 }
Douglas Gregor922fff22010-10-13 22:19:53 +00001523
Douglas Gregorf2503652011-09-21 14:40:46 +00001524 IdentifierInfo *II = Name.getAsIdentifierInfo();
1525
1526 // Member field could not be with "template" keyword.
1527 // So TemplateParameterLists should be empty in this case.
1528 if (TemplateParameterLists.size()) {
1529 TemplateParameterList* TemplateParams = TemplateParameterLists.get()[0];
1530 if (TemplateParams->size()) {
1531 // There is no such thing as a member field template.
1532 Diag(D.getIdentifierLoc(), diag::err_template_member)
1533 << II
1534 << SourceRange(TemplateParams->getTemplateLoc(),
1535 TemplateParams->getRAngleLoc());
1536 } else {
1537 // There is an extraneous 'template<>' for this member.
1538 Diag(TemplateParams->getTemplateLoc(),
1539 diag::err_template_member_noparams)
1540 << II
1541 << SourceRange(TemplateParams->getTemplateLoc(),
1542 TemplateParams->getRAngleLoc());
1543 }
1544 return 0;
1545 }
1546
Douglas Gregor922fff22010-10-13 22:19:53 +00001547 if (SS.isSet() && !SS.isInvalid()) {
1548 // The user provided a superfluous scope specifier inside a class
1549 // definition:
1550 //
1551 // class X {
1552 // int X::member;
1553 // };
1554 DeclContext *DC = 0;
1555 if ((DC = computeDeclContext(SS, false)) && DC->Equals(CurContext))
1556 Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification)
Douglas Gregor5d8419c2011-11-01 22:13:30 +00001557 << Name << FixItHint::CreateRemoval(SS.getRange());
Douglas Gregor922fff22010-10-13 22:19:53 +00001558 else
1559 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1560 << Name << SS.getRange();
Douglas Gregor5d8419c2011-11-01 22:13:30 +00001561
Douglas Gregor922fff22010-10-13 22:19:53 +00001562 SS.clear();
1563 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001564
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001565 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
Richard Smith7a614d82011-06-11 17:19:42 +00001566 HasDeferredInit, AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001567 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +00001568 } else {
Richard Smith7a614d82011-06-11 17:19:42 +00001569 assert(!HasDeferredInit);
1570
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00001571 Member = HandleDeclarator(S, D, move(TemplateParameterLists));
Chris Lattner6f8ce142009-03-05 23:03:49 +00001572 if (!Member) {
John McCalld226f652010-08-21 09:40:31 +00001573 return 0;
Chris Lattner6f8ce142009-03-05 23:03:49 +00001574 }
Chris Lattner8b963ef2009-03-05 23:01:03 +00001575
1576 // Non-instance-fields can't have a bitfield.
1577 if (BitWidth) {
1578 if (Member->isInvalidDecl()) {
1579 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00001580 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00001581 // C++ 9.6p3: A bit-field shall not be a static member.
1582 // "static member 'A' cannot be a bit-field"
1583 Diag(Loc, diag::err_static_not_bitfield)
1584 << Name << BitWidth->getSourceRange();
1585 } else if (isa<TypedefDecl>(Member)) {
1586 // "typedef member 'x' cannot be a bit-field"
1587 Diag(Loc, diag::err_typedef_not_bitfield)
1588 << Name << BitWidth->getSourceRange();
1589 } else {
1590 // A function typedef ("typedef int f(); f a;").
1591 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1592 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +00001593 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +00001594 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +00001595 }
Mike Stump1eb44332009-09-09 15:08:12 +00001596
Chris Lattner8b963ef2009-03-05 23:01:03 +00001597 BitWidth = 0;
1598 Member->setInvalidDecl();
1599 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001600
1601 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +00001602
Douglas Gregor37b372b2009-08-20 22:52:58 +00001603 // If we have declared a member function template, set the access of the
1604 // templated declaration as well.
1605 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1606 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +00001607 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001608
Anders Carlssonaae5af22011-01-20 04:34:22 +00001609 if (VS.isOverrideSpecified()) {
1610 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1611 if (!MD || !MD->isVirtual()) {
1612 Diag(Member->getLocStart(),
1613 diag::override_keyword_only_allowed_on_virtual_member_functions)
1614 << "override" << FixItHint::CreateRemoval(VS.getOverrideLoc());
Anders Carlsson9e682d92011-01-20 05:57:14 +00001615 } else
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001616 MD->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
Anders Carlssonaae5af22011-01-20 04:34:22 +00001617 }
1618 if (VS.isFinalSpecified()) {
1619 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1620 if (!MD || !MD->isVirtual()) {
1621 Diag(Member->getLocStart(),
1622 diag::override_keyword_only_allowed_on_virtual_member_functions)
1623 << "final" << FixItHint::CreateRemoval(VS.getFinalLoc());
Anders Carlsson9e682d92011-01-20 05:57:14 +00001624 } else
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001625 MD->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlssonaae5af22011-01-20 04:34:22 +00001626 }
Anders Carlsson9e682d92011-01-20 05:57:14 +00001627
Douglas Gregorf5251602011-03-08 17:10:18 +00001628 if (VS.getLastLocation().isValid()) {
1629 // Update the end location of a method that has a virt-specifiers.
1630 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1631 MD->setRangeEnd(VS.getLastLocation());
1632 }
1633
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001634 CheckOverrideControl(Member);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001635
Douglas Gregor10bd3682008-11-17 22:58:34 +00001636 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001637
John McCallb25b2952011-02-15 07:12:36 +00001638 if (isInstField)
Douglas Gregor44b43212008-12-11 16:49:14 +00001639 FieldCollector->Add(cast<FieldDecl>(Member));
John McCalld226f652010-08-21 09:40:31 +00001640 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001641}
1642
Richard Smith7a614d82011-06-11 17:19:42 +00001643/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
Richard Smith0ff6f8f2011-07-20 00:12:52 +00001644/// in-class initializer for a non-static C++ class member, and after
1645/// instantiating an in-class initializer in a class template. Such actions
1646/// are deferred until the class is complete.
Richard Smith7a614d82011-06-11 17:19:42 +00001647void
1648Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation EqualLoc,
1649 Expr *InitExpr) {
1650 FieldDecl *FD = cast<FieldDecl>(D);
1651
1652 if (!InitExpr) {
1653 FD->setInvalidDecl();
1654 FD->removeInClassInitializer();
1655 return;
1656 }
1657
Peter Collingbournefef21892011-10-23 18:59:44 +00001658 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
1659 FD->setInvalidDecl();
1660 FD->removeInClassInitializer();
1661 return;
1662 }
1663
Richard Smith7a614d82011-06-11 17:19:42 +00001664 ExprResult Init = InitExpr;
1665 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
1666 // FIXME: if there is no EqualLoc, this is list-initialization.
1667 Init = PerformCopyInitialization(
1668 InitializedEntity::InitializeMember(FD), EqualLoc, InitExpr);
1669 if (Init.isInvalid()) {
1670 FD->setInvalidDecl();
1671 return;
1672 }
1673
1674 CheckImplicitConversions(Init.get(), EqualLoc);
1675 }
1676
1677 // C++0x [class.base.init]p7:
1678 // The initialization of each base and member constitutes a
1679 // full-expression.
1680 Init = MaybeCreateExprWithCleanups(Init);
1681 if (Init.isInvalid()) {
1682 FD->setInvalidDecl();
1683 return;
1684 }
1685
1686 InitExpr = Init.release();
1687
1688 FD->setInClassInitializer(InitExpr);
1689}
1690
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001691/// \brief Find the direct and/or virtual base specifiers that
1692/// correspond to the given base type, for use in base initialization
1693/// within a constructor.
1694static bool FindBaseInitializer(Sema &SemaRef,
1695 CXXRecordDecl *ClassDecl,
1696 QualType BaseType,
1697 const CXXBaseSpecifier *&DirectBaseSpec,
1698 const CXXBaseSpecifier *&VirtualBaseSpec) {
1699 // First, check for a direct base class.
1700 DirectBaseSpec = 0;
1701 for (CXXRecordDecl::base_class_const_iterator Base
1702 = ClassDecl->bases_begin();
1703 Base != ClassDecl->bases_end(); ++Base) {
1704 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1705 // We found a direct base of this type. That's what we're
1706 // initializing.
1707 DirectBaseSpec = &*Base;
1708 break;
1709 }
1710 }
1711
1712 // Check for a virtual base class.
1713 // FIXME: We might be able to short-circuit this if we know in advance that
1714 // there are no virtual bases.
1715 VirtualBaseSpec = 0;
1716 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1717 // We haven't found a base yet; search the class hierarchy for a
1718 // virtual base class.
1719 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1720 /*DetectVirtual=*/false);
1721 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1722 BaseType, Paths)) {
1723 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1724 Path != Paths.end(); ++Path) {
1725 if (Path->back().Base->isVirtual()) {
1726 VirtualBaseSpec = Path->back().Base;
1727 break;
1728 }
1729 }
1730 }
1731 }
1732
1733 return DirectBaseSpec || VirtualBaseSpec;
1734}
1735
Sebastian Redl6df65482011-09-24 17:48:25 +00001736/// \brief Handle a C++ member initializer using braced-init-list syntax.
1737MemInitResult
1738Sema::ActOnMemInitializer(Decl *ConstructorD,
1739 Scope *S,
1740 CXXScopeSpec &SS,
1741 IdentifierInfo *MemberOrBase,
1742 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00001743 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00001744 SourceLocation IdLoc,
1745 Expr *InitList,
1746 SourceLocation EllipsisLoc) {
1747 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001748 DS, IdLoc, InitList,
David Blaikief2116622012-01-24 06:03:59 +00001749 EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00001750}
1751
1752/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallf312b1e2010-08-26 23:41:50 +00001753MemInitResult
John McCalld226f652010-08-21 09:40:31 +00001754Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001755 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001756 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001757 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00001758 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00001759 const DeclSpec &DS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001760 SourceLocation IdLoc,
1761 SourceLocation LParenLoc,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001762 Expr **Args, unsigned NumArgs,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001763 SourceLocation RParenLoc,
1764 SourceLocation EllipsisLoc) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001765 Expr *List = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1766 RParenLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00001767 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001768 DS, IdLoc, List, EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00001769}
1770
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001771namespace {
1772
Kaelyn Uhraindc98cd02012-01-11 21:17:51 +00001773// Callback to only accept typo corrections that can be a valid C++ member
1774// intializer: either a non-static field member or a base class.
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001775class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
1776 public:
1777 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
1778 : ClassDecl(ClassDecl) {}
1779
1780 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
1781 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
1782 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
1783 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
1784 else
1785 return isa<TypeDecl>(ND);
1786 }
1787 return false;
1788 }
1789
1790 private:
1791 CXXRecordDecl *ClassDecl;
1792};
1793
1794}
1795
Sebastian Redl6df65482011-09-24 17:48:25 +00001796/// \brief Handle a C++ member initializer.
1797MemInitResult
1798Sema::BuildMemInitializer(Decl *ConstructorD,
1799 Scope *S,
1800 CXXScopeSpec &SS,
1801 IdentifierInfo *MemberOrBase,
1802 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00001803 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00001804 SourceLocation IdLoc,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001805 Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00001806 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001807 if (!ConstructorD)
1808 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001809
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001810 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00001811
1812 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00001813 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001814 if (!Constructor) {
1815 // The user wrote a constructor initializer on a function that is
1816 // not a C++ constructor. Ignore the error for now, because we may
1817 // have more member initializers coming; we'll diagnose it just
1818 // once in ActOnMemInitializers.
1819 return true;
1820 }
1821
1822 CXXRecordDecl *ClassDecl = Constructor->getParent();
1823
1824 // C++ [class.base.init]p2:
1825 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky7663f392010-11-20 01:29:55 +00001826 // constructor's class and, if not found in that scope, are looked
1827 // up in the scope containing the constructor's definition.
1828 // [Note: if the constructor's class contains a member with the
1829 // same name as a direct or virtual base class of the class, a
1830 // mem-initializer-id naming the member or base class and composed
1831 // of a single identifier refers to the class member. A
Douglas Gregor7ad83902008-11-05 04:29:56 +00001832 // mem-initializer-id for the hidden base class may be specified
1833 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00001834 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001835 // Look for a member, first.
Mike Stump1eb44332009-09-09 15:08:12 +00001836 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001837 = ClassDecl->lookup(MemberOrBase);
Francois Pichet87c2e122010-11-21 06:08:52 +00001838 if (Result.first != Result.second) {
Peter Collingbournedc69be22011-10-23 18:59:37 +00001839 ValueDecl *Member;
1840 if ((Member = dyn_cast<FieldDecl>(*Result.first)) ||
1841 (Member = dyn_cast<IndirectFieldDecl>(*Result.first))) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001842 if (EllipsisLoc.isValid())
1843 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001844 << MemberOrBase
1845 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00001846
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001847 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001848 }
Francois Pichet00eb3f92010-12-04 09:14:42 +00001849 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001850 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001851 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00001852 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00001853 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00001854
1855 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00001856 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikief2116622012-01-24 06:03:59 +00001857 } else if (DS.getTypeSpecType() == TST_decltype) {
1858 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCall2b194412009-12-21 10:41:20 +00001859 } else {
1860 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1861 LookupParsedName(R, S, &SS);
1862
1863 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1864 if (!TyD) {
1865 if (R.isAmbiguous()) return true;
1866
John McCallfd225442010-04-09 19:01:14 +00001867 // We don't want access-control diagnostics here.
1868 R.suppressDiagnostics();
1869
Douglas Gregor7a886e12010-01-19 06:46:48 +00001870 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1871 bool NotUnknownSpecialization = false;
1872 DeclContext *DC = computeDeclContext(SS, false);
1873 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1874 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1875
1876 if (!NotUnknownSpecialization) {
1877 // When the scope specifier can refer to a member of an unknown
1878 // specialization, we take it as a type name.
Douglas Gregore29425b2011-02-28 22:42:13 +00001879 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
1880 SS.getWithLocInContext(Context),
1881 *MemberOrBase, IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00001882 if (BaseType.isNull())
1883 return true;
1884
Douglas Gregor7a886e12010-01-19 06:46:48 +00001885 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00001886 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001887 }
1888 }
1889
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001890 // If no results were found, try to correct typos.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001891 TypoCorrection Corr;
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001892 MemInitializerValidatorCCC Validator(ClassDecl);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001893 if (R.empty() && BaseType.isNull() &&
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001894 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00001895 Validator, ClassDecl))) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001896 std::string CorrectedStr(Corr.getAsString(getLangOptions()));
1897 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOptions()));
1898 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001899 // We have found a non-static data member with a similar
1900 // name to what was typed; complain and initialize that
1901 // member.
1902 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1903 << MemberOrBase << true << CorrectedQuotedStr
1904 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1905 Diag(Member->getLocation(), diag::note_previous_decl)
1906 << CorrectedQuotedStr;
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001907
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001908 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001909 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001910 const CXXBaseSpecifier *DirectBaseSpec;
1911 const CXXBaseSpecifier *VirtualBaseSpec;
1912 if (FindBaseInitializer(*this, ClassDecl,
1913 Context.getTypeDeclType(Type),
1914 DirectBaseSpec, VirtualBaseSpec)) {
1915 // We have found a direct or virtual base class with a
1916 // similar name to what was typed; complain and initialize
1917 // that base class.
1918 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001919 << MemberOrBase << false << CorrectedQuotedStr
1920 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor0d535c82010-01-07 00:26:25 +00001921
1922 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1923 : VirtualBaseSpec;
1924 Diag(BaseSpec->getSourceRange().getBegin(),
1925 diag::note_base_class_specified_here)
1926 << BaseSpec->getType()
1927 << BaseSpec->getSourceRange();
1928
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001929 TyD = Type;
1930 }
1931 }
1932 }
1933
Douglas Gregor7a886e12010-01-19 06:46:48 +00001934 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001935 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001936 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001937 return true;
1938 }
John McCall2b194412009-12-21 10:41:20 +00001939 }
1940
Douglas Gregor7a886e12010-01-19 06:46:48 +00001941 if (BaseType.isNull()) {
1942 BaseType = Context.getTypeDeclType(TyD);
1943 if (SS.isSet()) {
1944 NestedNameSpecifier *Qualifier =
1945 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00001946
Douglas Gregor7a886e12010-01-19 06:46:48 +00001947 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001948 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001949 }
John McCall2b194412009-12-21 10:41:20 +00001950 }
1951 }
Mike Stump1eb44332009-09-09 15:08:12 +00001952
John McCalla93c9342009-12-07 02:54:59 +00001953 if (!TInfo)
1954 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001955
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001956 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00001957}
1958
Chandler Carruth81c64772011-09-03 01:14:15 +00001959/// Checks a member initializer expression for cases where reference (or
1960/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth81c64772011-09-03 01:14:15 +00001961static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
1962 Expr *Init,
1963 SourceLocation IdLoc) {
1964 QualType MemberTy = Member->getType();
1965
1966 // We only handle pointers and references currently.
1967 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
1968 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
1969 return;
1970
1971 const bool IsPointer = MemberTy->isPointerType();
1972 if (IsPointer) {
1973 if (const UnaryOperator *Op
1974 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
1975 // The only case we're worried about with pointers requires taking the
1976 // address.
1977 if (Op->getOpcode() != UO_AddrOf)
1978 return;
1979
1980 Init = Op->getSubExpr();
1981 } else {
1982 // We only handle address-of expression initializers for pointers.
1983 return;
1984 }
1985 }
1986
Chandler Carruthbf3380a2011-09-03 02:21:57 +00001987 if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) {
1988 // Taking the address of a temporary will be diagnosed as a hard error.
1989 if (IsPointer)
1990 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00001991
Chandler Carruthbf3380a2011-09-03 02:21:57 +00001992 S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary)
1993 << Member << Init->getSourceRange();
1994 } else if (const DeclRefExpr *DRE
1995 = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
1996 // We only warn when referring to a non-reference parameter declaration.
1997 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
1998 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth81c64772011-09-03 01:14:15 +00001999 return;
2000
2001 S.Diag(Init->getExprLoc(),
2002 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2003 : diag::warn_bind_ref_member_to_parameter)
2004 << Member << Parameter << Init->getSourceRange();
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002005 } else {
2006 // Other initializers are fine.
2007 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002008 }
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002009
2010 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2011 << (unsigned)IsPointer;
Chandler Carruth81c64772011-09-03 01:14:15 +00002012}
2013
John McCallb4190042009-11-04 23:02:40 +00002014/// Checks an initializer expression for use of uninitialized fields, such as
2015/// containing the field that is being initialized. Returns true if there is an
2016/// uninitialized field was used an updates the SourceLocation parameter; false
2017/// otherwise.
Nick Lewycky43ad1822010-06-15 07:32:55 +00002018static bool InitExprContainsUninitializedFields(const Stmt *S,
Francois Pichet00eb3f92010-12-04 09:14:42 +00002019 const ValueDecl *LhsField,
Nick Lewycky43ad1822010-06-15 07:32:55 +00002020 SourceLocation *L) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002021 assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField));
2022
Nick Lewycky43ad1822010-06-15 07:32:55 +00002023 if (isa<CallExpr>(S)) {
2024 // Do not descend into function calls or constructors, as the use
2025 // of an uninitialized field may be valid. One would have to inspect
2026 // the contents of the function/ctor to determine if it is safe or not.
2027 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
2028 // may be safe, depending on what the function/ctor does.
2029 return false;
2030 }
2031 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
2032 const NamedDecl *RhsField = ME->getMemberDecl();
Anders Carlsson175ffbf2010-10-06 02:43:25 +00002033
2034 if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) {
2035 // The member expression points to a static data member.
2036 assert(VD->isStaticDataMember() &&
2037 "Member points to non-static data member!");
Nick Lewyckyedd59112010-10-06 18:37:39 +00002038 (void)VD;
Anders Carlsson175ffbf2010-10-06 02:43:25 +00002039 return false;
2040 }
2041
2042 if (isa<EnumConstantDecl>(RhsField)) {
2043 // The member expression points to an enum.
2044 return false;
2045 }
2046
John McCallb4190042009-11-04 23:02:40 +00002047 if (RhsField == LhsField) {
2048 // Initializing a field with itself. Throw a warning.
2049 // But wait; there are exceptions!
2050 // Exception #1: The field may not belong to this record.
2051 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
Nick Lewycky43ad1822010-06-15 07:32:55 +00002052 const Expr *base = ME->getBase();
John McCallb4190042009-11-04 23:02:40 +00002053 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
2054 // Even though the field matches, it does not belong to this record.
2055 return false;
2056 }
2057 // None of the exceptions triggered; return true to indicate an
2058 // uninitialized field was used.
2059 *L = ME->getMemberLoc();
2060 return true;
2061 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002062 } else if (isa<UnaryExprOrTypeTraitExpr>(S)) {
Argyrios Kyrtzidisff8819b2010-09-21 10:47:20 +00002063 // sizeof/alignof doesn't reference contents, do not warn.
2064 return false;
2065 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) {
2066 // address-of doesn't reference contents (the pointer may be dereferenced
2067 // in the same expression but it would be rare; and weird).
2068 if (UOE->getOpcode() == UO_AddrOf)
2069 return false;
John McCallb4190042009-11-04 23:02:40 +00002070 }
John McCall7502c1d2011-02-13 04:07:26 +00002071 for (Stmt::const_child_range it = S->children(); it; ++it) {
Nick Lewycky43ad1822010-06-15 07:32:55 +00002072 if (!*it) {
2073 // An expression such as 'member(arg ?: "")' may trigger this.
John McCallb4190042009-11-04 23:02:40 +00002074 continue;
2075 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00002076 if (InitExprContainsUninitializedFields(*it, LhsField, L))
2077 return true;
John McCallb4190042009-11-04 23:02:40 +00002078 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00002079 return false;
John McCallb4190042009-11-04 23:02:40 +00002080}
2081
John McCallf312b1e2010-08-26 23:41:50 +00002082MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002083Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002084 SourceLocation IdLoc) {
Chandler Carruth894aed92010-12-06 09:23:57 +00002085 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2086 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2087 assert((DirectMember || IndirectMember) &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00002088 "Member must be a FieldDecl or IndirectFieldDecl");
2089
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002090 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbournefef21892011-10-23 18:59:44 +00002091 return true;
2092
Douglas Gregor464b2f02010-11-05 22:21:31 +00002093 if (Member->isInvalidDecl())
2094 return true;
Chandler Carruth894aed92010-12-06 09:23:57 +00002095
John McCallb4190042009-11-04 23:02:40 +00002096 // Diagnose value-uses of fields to initialize themselves, e.g.
2097 // foo(foo)
2098 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00002099 // TODO: implement -Wuninitialized and fold this into that framework.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002100 Expr **Args;
2101 unsigned NumArgs;
2102 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2103 Args = ParenList->getExprs();
2104 NumArgs = ParenList->getNumExprs();
2105 } else {
2106 InitListExpr *InitList = cast<InitListExpr>(Init);
2107 Args = InitList->getInits();
2108 NumArgs = InitList->getNumInits();
2109 }
2110 for (unsigned i = 0; i < NumArgs; ++i) {
John McCallb4190042009-11-04 23:02:40 +00002111 SourceLocation L;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002112 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
John McCallb4190042009-11-04 23:02:40 +00002113 // FIXME: Return true in the case when other fields are used before being
2114 // uninitialized. For example, let this field be the i'th field. When
2115 // initializing the i'th field, throw a warning if any of the >= i'th
2116 // fields are used, as they are not yet initialized.
2117 // Right now we are only handling the case where the i'th field uses
2118 // itself in its initializer.
2119 Diag(L, diag::warn_field_is_uninit);
2120 }
2121 }
2122
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002123 SourceRange InitRange = Init->getSourceRange();
Eli Friedman59c04372009-07-29 19:44:27 +00002124
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002125 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002126 // Can't check initialization for a member of dependent type or when
2127 // any of the arguments are type-dependent expressions.
John McCallf85e1932011-06-15 23:02:42 +00002128 DiscardCleanupsInEvaluationContext();
Chandler Carruth894aed92010-12-06 09:23:57 +00002129 } else {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002130 bool InitList = false;
2131 if (isa<InitListExpr>(Init)) {
2132 InitList = true;
2133 Args = &Init;
2134 NumArgs = 1;
2135 }
2136
Chandler Carruth894aed92010-12-06 09:23:57 +00002137 // Initialize the member.
2138 InitializedEntity MemberEntity =
2139 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2140 : InitializedEntity::InitializeMember(IndirectMember, 0);
2141 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002142 InitList ? InitializationKind::CreateDirectList(IdLoc)
2143 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2144 InitRange.getEnd());
John McCallb4eb64d2010-10-08 02:01:28 +00002145
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002146 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
2147 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind,
2148 MultiExprArg(*this, Args, NumArgs),
2149 0);
Chandler Carruth894aed92010-12-06 09:23:57 +00002150 if (MemberInit.isInvalid())
2151 return true;
2152
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002153 CheckImplicitConversions(MemberInit.get(),
2154 InitRange.getBegin());
Chandler Carruth894aed92010-12-06 09:23:57 +00002155
2156 // C++0x [class.base.init]p7:
2157 // The initialization of each base and member constitutes a
2158 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00002159 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Chandler Carruth894aed92010-12-06 09:23:57 +00002160 if (MemberInit.isInvalid())
2161 return true;
2162
2163 // If we are in a dependent context, template instantiation will
2164 // perform this type-checking again. Just save the arguments that we
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002165 // received.
Chandler Carruth894aed92010-12-06 09:23:57 +00002166 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2167 // of the information that we have about the member
2168 // initializer. However, deconstructing the ASTs is a dicey process,
2169 // and this approach is far more likely to get the corner cases right.
Chandler Carruth81c64772011-09-03 01:14:15 +00002170 if (CurContext->isDependentContext()) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002171 // The existing Init will do fine.
Chandler Carruth81c64772011-09-03 01:14:15 +00002172 } else {
Chandler Carruth894aed92010-12-06 09:23:57 +00002173 Init = MemberInit.get();
Chandler Carruth81c64772011-09-03 01:14:15 +00002174 CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc);
2175 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002176 }
2177
Chandler Carruth894aed92010-12-06 09:23:57 +00002178 if (DirectMember) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002179 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2180 InitRange.getBegin(), Init,
2181 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002182 } else {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002183 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2184 InitRange.getBegin(), Init,
2185 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002186 }
Eli Friedman59c04372009-07-29 19:44:27 +00002187}
2188
John McCallf312b1e2010-08-26 23:41:50 +00002189MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002190Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Sean Hunt41717662011-02-26 19:13:13 +00002191 CXXRecordDecl *ClassDecl) {
Douglas Gregor76852c22011-11-01 01:16:03 +00002192 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sean Hunt97fcc492011-01-08 19:20:43 +00002193 if (!LangOpts.CPlusPlus0x)
Douglas Gregor76852c22011-11-01 01:16:03 +00002194 return Diag(NameLoc, diag::err_delegating_ctor)
Sean Hunt97fcc492011-01-08 19:20:43 +00002195 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor76852c22011-11-01 01:16:03 +00002196 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redlf9c32eb2011-03-12 13:53:51 +00002197
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002198 bool InitList = true;
2199 Expr **Args = &Init;
2200 unsigned NumArgs = 1;
2201 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2202 InitList = false;
2203 Args = ParenList->getExprs();
2204 NumArgs = ParenList->getNumExprs();
2205 }
2206
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002207 SourceRange InitRange = Init->getSourceRange();
Sean Hunt41717662011-02-26 19:13:13 +00002208 // Initialize the object.
2209 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2210 QualType(ClassDecl->getTypeForDecl(), 0));
2211 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002212 InitList ? InitializationKind::CreateDirectList(NameLoc)
2213 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2214 InitRange.getEnd());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002215 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs);
2216 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
2217 MultiExprArg(*this, Args,NumArgs),
2218 0);
Sean Hunt41717662011-02-26 19:13:13 +00002219 if (DelegationInit.isInvalid())
2220 return true;
2221
Matt Beaumont-Gay2eb0ce32011-11-01 18:10:22 +00002222 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2223 "Delegating constructor with no target?");
Sean Hunt41717662011-02-26 19:13:13 +00002224
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002225 CheckImplicitConversions(DelegationInit.get(), InitRange.getBegin());
Sean Hunt41717662011-02-26 19:13:13 +00002226
2227 // C++0x [class.base.init]p7:
2228 // The initialization of each base and member constitutes a
2229 // full-expression.
2230 DelegationInit = MaybeCreateExprWithCleanups(DelegationInit);
2231 if (DelegationInit.isInvalid())
2232 return true;
2233
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002234 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Sean Hunt41717662011-02-26 19:13:13 +00002235 DelegationInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002236 InitRange.getEnd());
Sean Hunt97fcc492011-01-08 19:20:43 +00002237}
2238
2239MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00002240Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002241 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002242 SourceLocation EllipsisLoc) {
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002243 SourceLocation BaseLoc
2244 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redl6df65482011-09-24 17:48:25 +00002245
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002246 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2247 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2248 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2249
2250 // C++ [class.base.init]p2:
2251 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00002252 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002253 // of that class, the mem-initializer is ill-formed. A
2254 // mem-initializer-list can initialize a base class using any
2255 // name that denotes that base class type.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002256 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002257
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002258 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002259 if (EllipsisLoc.isValid()) {
2260 // This is a pack expansion.
2261 if (!BaseType->containsUnexpandedParameterPack()) {
2262 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002263 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002264
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002265 EllipsisLoc = SourceLocation();
2266 }
2267 } else {
2268 // Check for any unexpanded parameter packs.
2269 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2270 return true;
Sebastian Redl6df65482011-09-24 17:48:25 +00002271
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002272 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redl6df65482011-09-24 17:48:25 +00002273 return true;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002274 }
Sebastian Redl6df65482011-09-24 17:48:25 +00002275
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002276 // Check for direct and virtual base classes.
2277 const CXXBaseSpecifier *DirectBaseSpec = 0;
2278 const CXXBaseSpecifier *VirtualBaseSpec = 0;
2279 if (!Dependent) {
Sean Hunt97fcc492011-01-08 19:20:43 +00002280 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2281 BaseType))
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002282 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Sean Hunt97fcc492011-01-08 19:20:43 +00002283
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002284 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2285 VirtualBaseSpec);
2286
2287 // C++ [base.class.init]p2:
2288 // Unless the mem-initializer-id names a nonstatic data member of the
2289 // constructor's class or a direct or virtual base of that class, the
2290 // mem-initializer is ill-formed.
2291 if (!DirectBaseSpec && !VirtualBaseSpec) {
2292 // If the class has any dependent bases, then it's possible that
2293 // one of those types will resolve to the same type as
2294 // BaseType. Therefore, just treat this as a dependent base
2295 // class initialization. FIXME: Should we try to check the
2296 // initialization anyway? It seems odd.
2297 if (ClassDecl->hasAnyDependentBases())
2298 Dependent = true;
2299 else
2300 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2301 << BaseType << Context.getTypeDeclType(ClassDecl)
2302 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2303 }
2304 }
2305
2306 if (Dependent) {
John McCallf85e1932011-06-15 23:02:42 +00002307 DiscardCleanupsInEvaluationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002308
Sebastian Redl6df65482011-09-24 17:48:25 +00002309 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2310 /*IsVirtual=*/false,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002311 InitRange.getBegin(), Init,
2312 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002313 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002314
2315 // C++ [base.class.init]p2:
2316 // If a mem-initializer-id is ambiguous because it designates both
2317 // a direct non-virtual base class and an inherited virtual base
2318 // class, the mem-initializer is ill-formed.
2319 if (DirectBaseSpec && VirtualBaseSpec)
2320 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002321 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002322
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002323 CXXBaseSpecifier *BaseSpec = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002324 if (!BaseSpec)
2325 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
2326
2327 // Initialize the base.
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002328 bool InitList = true;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002329 Expr **Args = &Init;
2330 unsigned NumArgs = 1;
2331 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002332 InitList = false;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002333 Args = ParenList->getExprs();
2334 NumArgs = ParenList->getNumExprs();
2335 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002336
2337 InitializedEntity BaseEntity =
2338 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2339 InitializationKind Kind =
2340 InitList ? InitializationKind::CreateDirectList(BaseLoc)
2341 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2342 InitRange.getEnd());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002343 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
2344 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind,
2345 MultiExprArg(*this, Args, NumArgs),
2346 0);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002347 if (BaseInit.isInvalid())
2348 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00002349
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002350 CheckImplicitConversions(BaseInit.get(), InitRange.getBegin());
Sebastian Redl6df65482011-09-24 17:48:25 +00002351
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002352 // C++0x [class.base.init]p7:
2353 // The initialization of each base and member constitutes a
2354 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00002355 BaseInit = MaybeCreateExprWithCleanups(BaseInit);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002356 if (BaseInit.isInvalid())
2357 return true;
2358
2359 // If we are in a dependent context, template instantiation will
2360 // perform this type-checking again. Just save the arguments that we
2361 // received in a ParenListExpr.
2362 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2363 // of the information that we have about the base
2364 // initializer. However, deconstructing the ASTs is a dicey process,
2365 // and this approach is far more likely to get the corner cases right.
Sebastian Redl6df65482011-09-24 17:48:25 +00002366 if (CurContext->isDependentContext())
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002367 BaseInit = Owned(Init);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002368
Sean Huntcbb67482011-01-08 20:30:50 +00002369 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00002370 BaseSpec->isVirtual(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002371 InitRange.getBegin(),
Sebastian Redl6df65482011-09-24 17:48:25 +00002372 BaseInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002373 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002374}
2375
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002376// Create a static_cast\<T&&>(expr).
2377static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
2378 QualType ExprType = E->getType();
2379 QualType TargetType = SemaRef.Context.getRValueReferenceType(ExprType);
2380 SourceLocation ExprLoc = E->getLocStart();
2381 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2382 TargetType, ExprLoc);
2383
2384 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2385 SourceRange(ExprLoc, ExprLoc),
2386 E->getSourceRange()).take();
2387}
2388
Anders Carlssone5ef7402010-04-23 03:10:23 +00002389/// ImplicitInitializerKind - How an implicit base or member initializer should
2390/// initialize its base or member.
2391enum ImplicitInitializerKind {
2392 IIK_Default,
2393 IIK_Copy,
2394 IIK_Move
2395};
2396
Anders Carlssondefefd22010-04-23 02:00:02 +00002397static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002398BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002399 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002400 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00002401 bool IsInheritedVirtualBase,
Sean Huntcbb67482011-01-08 20:30:50 +00002402 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00002403 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00002404 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2405 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00002406
John McCall60d7b3a2010-08-24 06:29:42 +00002407 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002408
2409 switch (ImplicitInitKind) {
2410 case IIK_Default: {
2411 InitializationKind InitKind
2412 = InitializationKind::CreateDefault(Constructor->getLocation());
2413 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
2414 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00002415 MultiExprArg(SemaRef, 0, 0));
Anders Carlssone5ef7402010-04-23 03:10:23 +00002416 break;
2417 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002418
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002419 case IIK_Move:
Anders Carlssone5ef7402010-04-23 03:10:23 +00002420 case IIK_Copy: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002421 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002422 ParmVarDecl *Param = Constructor->getParamDecl(0);
2423 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedmancf7c14c2012-01-16 21:00:51 +00002424
Anders Carlssone5ef7402010-04-23 03:10:23 +00002425 Expr *CopyCtorArg =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002426 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
2427 SourceLocation(), Param,
John McCallf89e55a2010-11-18 06:31:45 +00002428 Constructor->getLocation(), ParamType,
2429 VK_LValue, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002430
Eli Friedman5f2987c2012-02-02 03:46:19 +00002431 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
2432
Anders Carlssonc7957502010-04-24 22:02:54 +00002433 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00002434 QualType ArgTy =
2435 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2436 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00002437
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002438 if (Moving) {
2439 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2440 }
2441
John McCallf871d0c2010-08-07 06:22:56 +00002442 CXXCastPath BasePath;
2443 BasePath.push_back(BaseSpec);
John Wiegley429bb272011-04-08 18:41:53 +00002444 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2445 CK_UncheckedDerivedToBase,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002446 Moving ? VK_XValue : VK_LValue,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002447 &BasePath).take();
Anders Carlssonc7957502010-04-24 22:02:54 +00002448
Anders Carlssone5ef7402010-04-23 03:10:23 +00002449 InitializationKind InitKind
2450 = InitializationKind::CreateDirect(Constructor->getLocation(),
2451 SourceLocation(), SourceLocation());
2452 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
2453 &CopyCtorArg, 1);
2454 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00002455 MultiExprArg(&CopyCtorArg, 1));
Anders Carlssone5ef7402010-04-23 03:10:23 +00002456 break;
2457 }
Anders Carlssone5ef7402010-04-23 03:10:23 +00002458 }
John McCall9ae2f072010-08-23 23:25:46 +00002459
Douglas Gregor53c374f2010-12-07 00:41:46 +00002460 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00002461 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00002462 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00002463
Anders Carlssondefefd22010-04-23 02:00:02 +00002464 CXXBaseInit =
Sean Huntcbb67482011-01-08 20:30:50 +00002465 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlsson84688f22010-04-20 23:11:20 +00002466 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2467 SourceLocation()),
2468 BaseSpec->isVirtual(),
2469 SourceLocation(),
2470 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002471 SourceLocation(),
Anders Carlsson84688f22010-04-20 23:11:20 +00002472 SourceLocation());
2473
Anders Carlssondefefd22010-04-23 02:00:02 +00002474 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00002475}
2476
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002477static bool RefersToRValueRef(Expr *MemRef) {
2478 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2479 return Referenced->getType()->isRValueReferenceType();
2480}
2481
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002482static bool
2483BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002484 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002485 FieldDecl *Field, IndirectFieldDecl *Indirect,
Sean Huntcbb67482011-01-08 20:30:50 +00002486 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002487 if (Field->isInvalidDecl())
2488 return true;
2489
Chandler Carruthf186b542010-06-29 23:50:44 +00002490 SourceLocation Loc = Constructor->getLocation();
2491
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002492 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2493 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002494 ParmVarDecl *Param = Constructor->getParamDecl(0);
2495 QualType ParamType = Param->getType().getNonReferenceType();
John McCallb77115d2011-06-17 00:18:42 +00002496
2497 // Suppress copying zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002498 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
2499 return false;
Douglas Gregorddb21472011-11-02 23:04:16 +00002500
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002501 Expr *MemberExprBase =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002502 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
2503 SourceLocation(), Param,
John McCallf89e55a2010-11-18 06:31:45 +00002504 Loc, ParamType, VK_LValue, 0);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002505
Eli Friedman5f2987c2012-02-02 03:46:19 +00002506 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
2507
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002508 if (Moving) {
2509 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2510 }
2511
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002512 // Build a reference to this field within the parameter.
2513 CXXScopeSpec SS;
2514 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2515 Sema::LookupMemberName);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002516 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2517 : cast<ValueDecl>(Field), AS_public);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002518 MemberLookup.resolveKind();
Sebastian Redl74e611a2011-09-04 18:14:28 +00002519 ExprResult CtorArg
John McCall9ae2f072010-08-23 23:25:46 +00002520 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002521 ParamType, Loc,
2522 /*IsArrow=*/false,
2523 SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002524 /*TemplateKWLoc=*/SourceLocation(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002525 /*FirstQualifierInScope=*/0,
2526 MemberLookup,
2527 /*TemplateArgs=*/0);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002528 if (CtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002529 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002530
2531 // C++11 [class.copy]p15:
2532 // - if a member m has rvalue reference type T&&, it is direct-initialized
2533 // with static_cast<T&&>(x.m);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002534 if (RefersToRValueRef(CtorArg.get())) {
2535 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002536 }
2537
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002538 // When the field we are copying is an array, create index variables for
2539 // each dimension of the array. We use these index variables to subscript
2540 // the source array, and other clients (e.g., CodeGen) will perform the
2541 // necessary iteration with these index variables.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002542 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002543 QualType BaseType = Field->getType();
2544 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002545 bool InitializingArray = false;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002546 while (const ConstantArrayType *Array
2547 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002548 InitializingArray = true;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002549 // Create the iteration variable for this array index.
2550 IdentifierInfo *IterationVarName = 0;
2551 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002552 SmallString<8> Str;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002553 llvm::raw_svector_ostream OS(Str);
2554 OS << "__i" << IndexVariables.size();
2555 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
2556 }
2557 VarDecl *IterationVar
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002558 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002559 IterationVarName, SizeType,
2560 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00002561 SC_None, SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002562 IndexVariables.push_back(IterationVar);
2563
2564 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00002565 ExprResult IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00002566 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002567 assert(!IterationVarRef.isInvalid() &&
2568 "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00002569 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
2570 assert(!IterationVarRef.isInvalid() &&
2571 "Conversion of invented variable cannot fail!");
Sebastian Redl74e611a2011-09-04 18:14:28 +00002572
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002573 // Subscript the array with this iteration variable.
Sebastian Redl74e611a2011-09-04 18:14:28 +00002574 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCall9ae2f072010-08-23 23:25:46 +00002575 IterationVarRef.take(),
Sebastian Redl74e611a2011-09-04 18:14:28 +00002576 Loc);
2577 if (CtorArg.isInvalid())
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002578 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002579
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002580 BaseType = Array->getElementType();
2581 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002582
2583 // The array subscript expression is an lvalue, which is wrong for moving.
2584 if (Moving && InitializingArray)
Sebastian Redl74e611a2011-09-04 18:14:28 +00002585 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002586
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002587 // Construct the entity that we will be initializing. For an array, this
2588 // will be first element in the array, which may require several levels
2589 // of array-subscript entities.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002590 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002591 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002592 if (Indirect)
2593 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
2594 else
2595 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002596 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
2597 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
2598 0,
2599 Entities.back()));
2600
2601 // Direct-initialize to use the copy constructor.
2602 InitializationKind InitKind =
2603 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
2604
Sebastian Redl74e611a2011-09-04 18:14:28 +00002605 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002606 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002607 &CtorArgE, 1);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002608
John McCall60d7b3a2010-08-24 06:29:42 +00002609 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002610 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002611 MultiExprArg(&CtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00002612 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002613 if (MemberInit.isInvalid())
2614 return true;
2615
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002616 if (Indirect) {
2617 assert(IndexVariables.size() == 0 &&
2618 "Indirect field improperly initialized");
2619 CXXMemberInit
2620 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2621 Loc, Loc,
2622 MemberInit.takeAs<Expr>(),
2623 Loc);
2624 } else
2625 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
2626 Loc, MemberInit.takeAs<Expr>(),
2627 Loc,
2628 IndexVariables.data(),
2629 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00002630 return false;
2631 }
2632
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002633 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
2634
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002635 QualType FieldBaseElementType =
2636 SemaRef.Context.getBaseElementType(Field->getType());
2637
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002638 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002639 InitializedEntity InitEntity
2640 = Indirect? InitializedEntity::InitializeMember(Indirect)
2641 : InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002642 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00002643 InitializationKind::CreateDefault(Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002644
2645 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00002646 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00002647 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCall9ae2f072010-08-23 23:25:46 +00002648
Douglas Gregor53c374f2010-12-07 00:41:46 +00002649 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002650 if (MemberInit.isInvalid())
2651 return true;
2652
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002653 if (Indirect)
2654 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2655 Indirect, Loc,
2656 Loc,
2657 MemberInit.get(),
2658 Loc);
2659 else
2660 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2661 Field, Loc, Loc,
2662 MemberInit.get(),
2663 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002664 return false;
2665 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002666
Sean Hunt1f2f3842011-05-17 00:19:05 +00002667 if (!Field->getParent()->isUnion()) {
2668 if (FieldBaseElementType->isReferenceType()) {
2669 SemaRef.Diag(Constructor->getLocation(),
2670 diag::err_uninitialized_member_in_ctor)
2671 << (int)Constructor->isImplicit()
2672 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2673 << 0 << Field->getDeclName();
2674 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2675 return true;
2676 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002677
Sean Hunt1f2f3842011-05-17 00:19:05 +00002678 if (FieldBaseElementType.isConstQualified()) {
2679 SemaRef.Diag(Constructor->getLocation(),
2680 diag::err_uninitialized_member_in_ctor)
2681 << (int)Constructor->isImplicit()
2682 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2683 << 1 << Field->getDeclName();
2684 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2685 return true;
2686 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002687 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002688
John McCallf85e1932011-06-15 23:02:42 +00002689 if (SemaRef.getLangOptions().ObjCAutoRefCount &&
2690 FieldBaseElementType->isObjCRetainableType() &&
2691 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
2692 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
2693 // Instant objects:
2694 // Default-initialize Objective-C pointers to NULL.
2695 CXXMemberInit
2696 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2697 Loc, Loc,
2698 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
2699 Loc);
2700 return false;
2701 }
2702
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002703 // Nothing to initialize.
2704 CXXMemberInit = 0;
2705 return false;
2706}
John McCallf1860e52010-05-20 23:23:51 +00002707
2708namespace {
2709struct BaseAndFieldInfo {
2710 Sema &S;
2711 CXXConstructorDecl *Ctor;
2712 bool AnyErrorsInInits;
2713 ImplicitInitializerKind IIK;
Sean Huntcbb67482011-01-08 20:30:50 +00002714 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002715 SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallf1860e52010-05-20 23:23:51 +00002716
2717 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
2718 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002719 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
2720 if (Generated && Ctor->isCopyConstructor())
John McCallf1860e52010-05-20 23:23:51 +00002721 IIK = IIK_Copy;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002722 else if (Generated && Ctor->isMoveConstructor())
2723 IIK = IIK_Move;
John McCallf1860e52010-05-20 23:23:51 +00002724 else
2725 IIK = IIK_Default;
2726 }
Douglas Gregorf4853882011-11-28 20:03:15 +00002727
2728 bool isImplicitCopyOrMove() const {
2729 switch (IIK) {
2730 case IIK_Copy:
2731 case IIK_Move:
2732 return true;
2733
2734 case IIK_Default:
2735 return false;
2736 }
David Blaikie30263482012-01-20 21:50:17 +00002737
2738 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregorf4853882011-11-28 20:03:15 +00002739 }
John McCallf1860e52010-05-20 23:23:51 +00002740};
2741}
2742
Richard Smitha4950662011-09-19 13:34:43 +00002743/// \brief Determine whether the given indirect field declaration is somewhere
2744/// within an anonymous union.
2745static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
2746 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
2747 CEnd = F->chain_end();
2748 C != CEnd; ++C)
2749 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
2750 if (Record->isUnion())
2751 return true;
2752
2753 return false;
2754}
2755
Douglas Gregorddb21472011-11-02 23:04:16 +00002756/// \brief Determine whether the given type is an incomplete or zero-lenfgth
2757/// array type.
2758static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
2759 if (T->isIncompleteArrayType())
2760 return true;
2761
2762 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
2763 if (!ArrayT->getSize())
2764 return true;
2765
2766 T = ArrayT->getElementType();
2767 }
2768
2769 return false;
2770}
2771
Richard Smith7a614d82011-06-11 17:19:42 +00002772static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002773 FieldDecl *Field,
2774 IndirectFieldDecl *Indirect = 0) {
John McCallf1860e52010-05-20 23:23:51 +00002775
Chandler Carruthe861c602010-06-30 02:59:29 +00002776 // Overwhelmingly common case: we have a direct initializer for this field.
Sean Huntcbb67482011-01-08 20:30:50 +00002777 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002778 Info.AllToInit.push_back(Init);
John McCallf1860e52010-05-20 23:23:51 +00002779 return false;
2780 }
2781
Richard Smith7a614d82011-06-11 17:19:42 +00002782 // C++0x [class.base.init]p8: if the entity is a non-static data member that
2783 // has a brace-or-equal-initializer, the entity is initialized as specified
2784 // in [dcl.init].
Douglas Gregorf4853882011-11-28 20:03:15 +00002785 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002786 CXXCtorInitializer *Init;
2787 if (Indirect)
2788 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2789 SourceLocation(),
2790 SourceLocation(), 0,
2791 SourceLocation());
2792 else
2793 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2794 SourceLocation(),
2795 SourceLocation(), 0,
2796 SourceLocation());
2797 Info.AllToInit.push_back(Init);
Richard Smith7a614d82011-06-11 17:19:42 +00002798 return false;
2799 }
2800
Richard Smithc115f632011-09-18 11:14:50 +00002801 // Don't build an implicit initializer for union members if none was
2802 // explicitly specified.
Richard Smitha4950662011-09-19 13:34:43 +00002803 if (Field->getParent()->isUnion() ||
2804 (Indirect && isWithinAnonymousUnion(Indirect)))
Richard Smithc115f632011-09-18 11:14:50 +00002805 return false;
2806
Douglas Gregorddb21472011-11-02 23:04:16 +00002807 // Don't initialize incomplete or zero-length arrays.
2808 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
2809 return false;
2810
John McCallf1860e52010-05-20 23:23:51 +00002811 // Don't try to build an implicit initializer if there were semantic
2812 // errors in any of the initializers (and therefore we might be
2813 // missing some that the user actually wrote).
Richard Smith7a614d82011-06-11 17:19:42 +00002814 if (Info.AnyErrorsInInits || Field->isInvalidDecl())
John McCallf1860e52010-05-20 23:23:51 +00002815 return false;
2816
Sean Huntcbb67482011-01-08 20:30:50 +00002817 CXXCtorInitializer *Init = 0;
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002818 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
2819 Indirect, Init))
John McCallf1860e52010-05-20 23:23:51 +00002820 return true;
John McCallf1860e52010-05-20 23:23:51 +00002821
Francois Pichet00eb3f92010-12-04 09:14:42 +00002822 if (Init)
2823 Info.AllToInit.push_back(Init);
2824
John McCallf1860e52010-05-20 23:23:51 +00002825 return false;
2826}
Sean Hunt059ce0d2011-05-01 07:04:31 +00002827
2828bool
2829Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
2830 CXXCtorInitializer *Initializer) {
Sean Huntfe57eef2011-05-04 05:57:24 +00002831 assert(Initializer->isDelegatingInitializer());
Sean Hunt01aacc02011-05-03 20:43:02 +00002832 Constructor->setNumCtorInitializers(1);
2833 CXXCtorInitializer **initializer =
2834 new (Context) CXXCtorInitializer*[1];
2835 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
2836 Constructor->setCtorInitializers(initializer);
2837
Sean Huntb76af9c2011-05-03 23:05:34 +00002838 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00002839 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Sean Huntb76af9c2011-05-03 23:05:34 +00002840 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
2841 }
2842
Sean Huntc1598702011-05-05 00:05:47 +00002843 DelegatingCtorDecls.push_back(Constructor);
Sean Huntfe57eef2011-05-04 05:57:24 +00002844
Sean Hunt059ce0d2011-05-01 07:04:31 +00002845 return false;
2846}
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002847
John McCallb77115d2011-06-17 00:18:42 +00002848bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
2849 CXXCtorInitializer **Initializers,
2850 unsigned NumInitializers,
2851 bool AnyErrors) {
Douglas Gregord836c0d2011-09-22 23:04:35 +00002852 if (Constructor->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002853 // Just store the initializers as written, they will be checked during
2854 // instantiation.
2855 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00002856 Constructor->setNumCtorInitializers(NumInitializers);
2857 CXXCtorInitializer **baseOrMemberInitializers =
2858 new (Context) CXXCtorInitializer*[NumInitializers];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002859 memcpy(baseOrMemberInitializers, Initializers,
Sean Huntcbb67482011-01-08 20:30:50 +00002860 NumInitializers * sizeof(CXXCtorInitializer*));
2861 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002862 }
2863
2864 return false;
2865 }
2866
John McCallf1860e52010-05-20 23:23:51 +00002867 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00002868
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002869 // We need to build the initializer AST according to order of construction
2870 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00002871 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00002872 if (!ClassDecl)
2873 return true;
2874
Eli Friedman80c30da2009-11-09 19:20:36 +00002875 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002876
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002877 for (unsigned i = 0; i < NumInitializers; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00002878 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002879
2880 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00002881 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002882 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00002883 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002884 }
2885
Anders Carlsson711f34a2010-04-21 19:52:01 +00002886 // Keep track of the direct virtual bases.
2887 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
2888 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
2889 E = ClassDecl->bases_end(); I != E; ++I) {
2890 if (I->isVirtual())
2891 DirectVBases.insert(I);
2892 }
2893
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002894 // Push virtual bases before others.
2895 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2896 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2897
Sean Huntcbb67482011-01-08 20:30:50 +00002898 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00002899 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
2900 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002901 } else if (!AnyErrors) {
Anders Carlsson711f34a2010-04-21 19:52:01 +00002902 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00002903 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00002904 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002905 VBase, IsInheritedVirtualBase,
2906 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002907 HadError = true;
2908 continue;
2909 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002910
John McCallf1860e52010-05-20 23:23:51 +00002911 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002912 }
2913 }
Mike Stump1eb44332009-09-09 15:08:12 +00002914
John McCallf1860e52010-05-20 23:23:51 +00002915 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002916 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2917 E = ClassDecl->bases_end(); Base != E; ++Base) {
2918 // Virtuals are in the virtual base list and already constructed.
2919 if (Base->isVirtual())
2920 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00002921
Sean Huntcbb67482011-01-08 20:30:50 +00002922 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00002923 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
2924 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002925 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00002926 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00002927 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002928 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00002929 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002930 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002931 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002932 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00002933
John McCallf1860e52010-05-20 23:23:51 +00002934 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002935 }
2936 }
Mike Stump1eb44332009-09-09 15:08:12 +00002937
John McCallf1860e52010-05-20 23:23:51 +00002938 // Fields.
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002939 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
2940 MemEnd = ClassDecl->decls_end();
2941 Mem != MemEnd; ++Mem) {
2942 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
Douglas Gregord61db332011-10-10 17:22:13 +00002943 // C++ [class.bit]p2:
2944 // A declaration for a bit-field that omits the identifier declares an
2945 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
2946 // initialized.
2947 if (F->isUnnamedBitfield())
2948 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00002949
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002950 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002951 // handle anonymous struct/union fields based on their individual
2952 // indirect fields.
2953 if (F->isAnonymousStructOrUnion() && Info.IIK == IIK_Default)
2954 continue;
2955
2956 if (CollectFieldInitializer(*this, Info, F))
2957 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00002958 continue;
2959 }
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002960
2961 // Beyond this point, we only consider default initialization.
2962 if (Info.IIK != IIK_Default)
2963 continue;
2964
2965 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
2966 if (F->getType()->isIncompleteArrayType()) {
2967 assert(ClassDecl->hasFlexibleArrayMember() &&
2968 "Incomplete array type is not valid");
2969 continue;
2970 }
2971
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002972 // Initialize each field of an anonymous struct individually.
2973 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
2974 HadError = true;
2975
2976 continue;
2977 }
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00002978 }
Mike Stump1eb44332009-09-09 15:08:12 +00002979
John McCallf1860e52010-05-20 23:23:51 +00002980 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002981 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00002982 Constructor->setNumCtorInitializers(NumInitializers);
2983 CXXCtorInitializer **baseOrMemberInitializers =
2984 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00002985 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00002986 NumInitializers * sizeof(CXXCtorInitializer*));
2987 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00002988
John McCallef027fe2010-03-16 21:39:52 +00002989 // Constructors implicitly reference the base and member
2990 // destructors.
2991 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
2992 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002993 }
Eli Friedman80c30da2009-11-09 19:20:36 +00002994
2995 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002996}
2997
Eli Friedman6347f422009-07-21 19:28:10 +00002998static void *GetKeyForTopLevelField(FieldDecl *Field) {
2999 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00003000 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00003001 if (RT->getDecl()->isAnonymousStructOrUnion())
3002 return static_cast<void *>(RT->getDecl());
3003 }
3004 return static_cast<void *>(Field);
3005}
3006
Anders Carlssonea356fb2010-04-02 05:42:15 +00003007static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCallf4c73712011-01-19 06:33:43 +00003008 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssoncdc83c72009-09-01 06:22:14 +00003009}
3010
Anders Carlssonea356fb2010-04-02 05:42:15 +00003011static void *GetKeyForMember(ASTContext &Context,
Sean Huntcbb67482011-01-08 20:30:50 +00003012 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003013 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00003014 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00003015
Eli Friedman6347f422009-07-21 19:28:10 +00003016 // For fields injected into the class via declaration of an anonymous union,
3017 // use its anonymous union class declaration as the unique key.
Francois Pichet00eb3f92010-12-04 09:14:42 +00003018 FieldDecl *Field = Member->getAnyMember();
3019
John McCall3c3ccdb2010-04-10 09:28:51 +00003020 // If the field is a member of an anonymous struct or union, our key
3021 // is the anonymous record decl that's a direct child of the class.
Anders Carlssonee11b2d2010-03-30 16:19:37 +00003022 RecordDecl *RD = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003023 if (RD->isAnonymousStructOrUnion()) {
3024 while (true) {
3025 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
3026 if (Parent->isAnonymousStructOrUnion())
3027 RD = Parent;
3028 else
3029 break;
3030 }
3031
Anders Carlssonee11b2d2010-03-30 16:19:37 +00003032 return static_cast<void *>(RD);
John McCall3c3ccdb2010-04-10 09:28:51 +00003033 }
Mike Stump1eb44332009-09-09 15:08:12 +00003034
Anders Carlsson8f1a2402010-03-30 15:39:27 +00003035 return static_cast<void *>(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00003036}
3037
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003038static void
3039DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson071d6102010-04-02 03:38:04 +00003040 const CXXConstructorDecl *Constructor,
Sean Huntcbb67482011-01-08 20:30:50 +00003041 CXXCtorInitializer **Inits,
John McCalld6ca8da2010-04-10 07:37:23 +00003042 unsigned NumInits) {
3043 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00003044 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003045
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003046 // Don't check initializers order unless the warning is enabled at the
3047 // location of at least one initializer.
3048 bool ShouldCheckOrder = false;
3049 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003050 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003051 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3052 Init->getSourceLocation())
David Blaikied6471f72011-09-25 23:23:43 +00003053 != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003054 ShouldCheckOrder = true;
3055 break;
3056 }
3057 }
3058 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003059 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003060
John McCalld6ca8da2010-04-10 07:37:23 +00003061 // Build the list of bases and members in the order that they'll
3062 // actually be initialized. The explicit initializers should be in
3063 // this same order but may be missing things.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003064 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00003065
Anders Carlsson071d6102010-04-02 03:38:04 +00003066 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3067
John McCalld6ca8da2010-04-10 07:37:23 +00003068 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003069 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003070 ClassDecl->vbases_begin(),
3071 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00003072 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003073
John McCalld6ca8da2010-04-10 07:37:23 +00003074 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003075 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003076 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003077 if (Base->isVirtual())
3078 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00003079 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003080 }
Mike Stump1eb44332009-09-09 15:08:12 +00003081
John McCalld6ca8da2010-04-10 07:37:23 +00003082 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003083 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Douglas Gregord61db332011-10-10 17:22:13 +00003084 E = ClassDecl->field_end(); Field != E; ++Field) {
3085 if (Field->isUnnamedBitfield())
3086 continue;
3087
John McCalld6ca8da2010-04-10 07:37:23 +00003088 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Douglas Gregord61db332011-10-10 17:22:13 +00003089 }
3090
John McCalld6ca8da2010-04-10 07:37:23 +00003091 unsigned NumIdealInits = IdealInitKeys.size();
3092 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00003093
Sean Huntcbb67482011-01-08 20:30:50 +00003094 CXXCtorInitializer *PrevInit = 0;
John McCalld6ca8da2010-04-10 07:37:23 +00003095 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003096 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichet00eb3f92010-12-04 09:14:42 +00003097 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00003098
3099 // Scan forward to try to find this initializer in the idealized
3100 // initializers list.
3101 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3102 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003103 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003104
3105 // If we didn't find this initializer, it must be because we
3106 // scanned past it on a previous iteration. That can only
3107 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00003108 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00003109 Sema::SemaDiagnosticBuilder D =
3110 SemaRef.Diag(PrevInit->getSourceLocation(),
3111 diag::warn_initializer_out_of_order);
3112
Francois Pichet00eb3f92010-12-04 09:14:42 +00003113 if (PrevInit->isAnyMemberInitializer())
3114 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003115 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003116 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003117
Francois Pichet00eb3f92010-12-04 09:14:42 +00003118 if (Init->isAnyMemberInitializer())
3119 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003120 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003121 D << 1 << Init->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003122
3123 // Move back to the initializer's location in the ideal list.
3124 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3125 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003126 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003127
3128 assert(IdealIndex != NumIdealInits &&
3129 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003130 }
John McCalld6ca8da2010-04-10 07:37:23 +00003131
3132 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003133 }
Anders Carlssona7b35212009-03-25 02:58:17 +00003134}
3135
John McCall3c3ccdb2010-04-10 09:28:51 +00003136namespace {
3137bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003138 CXXCtorInitializer *Init,
3139 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003140 if (!PrevInit) {
3141 PrevInit = Init;
3142 return false;
3143 }
3144
3145 if (FieldDecl *Field = Init->getMember())
3146 S.Diag(Init->getSourceLocation(),
3147 diag::err_multiple_mem_initialization)
3148 << Field->getDeclName()
3149 << Init->getSourceRange();
3150 else {
John McCallf4c73712011-01-19 06:33:43 +00003151 const Type *BaseClass = Init->getBaseClass();
John McCall3c3ccdb2010-04-10 09:28:51 +00003152 assert(BaseClass && "neither field nor base");
3153 S.Diag(Init->getSourceLocation(),
3154 diag::err_multiple_base_initialization)
3155 << QualType(BaseClass, 0)
3156 << Init->getSourceRange();
3157 }
3158 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3159 << 0 << PrevInit->getSourceRange();
3160
3161 return true;
3162}
3163
Sean Huntcbb67482011-01-08 20:30:50 +00003164typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00003165typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3166
3167bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003168 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00003169 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003170 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003171 RecordDecl *Parent = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003172 NamedDecl *Child = Field;
David Blaikie6fe29652011-11-17 06:01:57 +00003173
3174 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003175 if (Parent->isUnion()) {
3176 UnionEntry &En = Unions[Parent];
3177 if (En.first && En.first != Child) {
3178 S.Diag(Init->getSourceLocation(),
3179 diag::err_multiple_mem_union_initialization)
3180 << Field->getDeclName()
3181 << Init->getSourceRange();
3182 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3183 << 0 << En.second->getSourceRange();
3184 return true;
David Blaikie5bbe8162011-11-12 20:54:14 +00003185 }
3186 if (!En.first) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003187 En.first = Child;
3188 En.second = Init;
3189 }
David Blaikie6fe29652011-11-17 06:01:57 +00003190 if (!Parent->isAnonymousStructOrUnion())
3191 return false;
John McCall3c3ccdb2010-04-10 09:28:51 +00003192 }
3193
3194 Child = Parent;
3195 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie6fe29652011-11-17 06:01:57 +00003196 }
John McCall3c3ccdb2010-04-10 09:28:51 +00003197
3198 return false;
3199}
3200}
3201
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003202/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00003203void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003204 SourceLocation ColonLoc,
Richard Trieu90ab75b2011-09-09 03:18:59 +00003205 CXXCtorInitializer **meminits,
3206 unsigned NumMemInits,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003207 bool AnyErrors) {
3208 if (!ConstructorDecl)
3209 return;
3210
3211 AdjustDeclIfTemplate(ConstructorDecl);
3212
3213 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003214 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003215
3216 if (!Constructor) {
3217 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3218 return;
3219 }
3220
Sean Huntcbb67482011-01-08 20:30:50 +00003221 CXXCtorInitializer **MemInits =
3222 reinterpret_cast<CXXCtorInitializer **>(meminits);
John McCall3c3ccdb2010-04-10 09:28:51 +00003223
3224 // Mapping for the duplicate initializers check.
3225 // For member initializers, this is keyed with a FieldDecl*.
3226 // For base initializers, this is keyed with a Type*.
Sean Huntcbb67482011-01-08 20:30:50 +00003227 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00003228
3229 // Mapping for the inconsistent anonymous-union initializers check.
3230 RedundantUnionMap MemberUnions;
3231
Anders Carlssonea356fb2010-04-02 05:42:15 +00003232 bool HadError = false;
3233 for (unsigned i = 0; i < NumMemInits; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003234 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003235
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00003236 // Set the source order index.
3237 Init->setSourceOrder(i);
3238
Francois Pichet00eb3f92010-12-04 09:14:42 +00003239 if (Init->isAnyMemberInitializer()) {
3240 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003241 if (CheckRedundantInit(*this, Init, Members[Field]) ||
3242 CheckRedundantUnionInit(*this, Init, MemberUnions))
3243 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003244 } else if (Init->isBaseInitializer()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003245 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
3246 if (CheckRedundantInit(*this, Init, Members[Key]))
3247 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003248 } else {
3249 assert(Init->isDelegatingInitializer());
3250 // This must be the only initializer
3251 if (i != 0 || NumMemInits > 1) {
3252 Diag(MemInits[0]->getSourceLocation(),
3253 diag::err_delegating_initializer_alone)
3254 << MemInits[0]->getSourceRange();
3255 HadError = true;
Sean Hunt059ce0d2011-05-01 07:04:31 +00003256 // We will treat this as being the only initializer.
Sean Hunt41717662011-02-26 19:13:13 +00003257 }
Sean Huntfe57eef2011-05-04 05:57:24 +00003258 SetDelegatingInitializer(Constructor, MemInits[i]);
Sean Hunt059ce0d2011-05-01 07:04:31 +00003259 // Return immediately as the initializer is set.
3260 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003261 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003262 }
3263
Anders Carlssonea356fb2010-04-02 05:42:15 +00003264 if (HadError)
3265 return;
3266
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003267 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00003268
Sean Huntcbb67482011-01-08 20:30:50 +00003269 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003270}
3271
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003272void
John McCallef027fe2010-03-16 21:39:52 +00003273Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3274 CXXRecordDecl *ClassDecl) {
Richard Smith416f63e2011-09-18 12:11:43 +00003275 // Ignore dependent contexts. Also ignore unions, since their members never
3276 // have destructors implicitly called.
3277 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003278 return;
John McCall58e6f342010-03-16 05:22:47 +00003279
3280 // FIXME: all the access-control diagnostics are positioned on the
3281 // field/base declaration. That's probably good; that said, the
3282 // user might reasonably want to know why the destructor is being
3283 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003284
Anders Carlsson9f853df2009-11-17 04:44:12 +00003285 // Non-static data members.
3286 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3287 E = ClassDecl->field_end(); I != E; ++I) {
3288 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00003289 if (Field->isInvalidDecl())
3290 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003291
3292 // Don't destroy incomplete or zero-length arrays.
3293 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3294 continue;
3295
Anders Carlsson9f853df2009-11-17 04:44:12 +00003296 QualType FieldType = Context.getBaseElementType(Field->getType());
3297
3298 const RecordType* RT = FieldType->getAs<RecordType>();
3299 if (!RT)
3300 continue;
3301
3302 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003303 if (FieldClassDecl->isInvalidDecl())
3304 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00003305 if (FieldClassDecl->hasTrivialDestructor())
3306 continue;
3307
Douglas Gregordb89f282010-07-01 22:47:18 +00003308 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003309 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003310 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003311 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00003312 << Field->getDeclName()
3313 << FieldType);
3314
Eli Friedman5f2987c2012-02-02 03:46:19 +00003315 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00003316 }
3317
John McCall58e6f342010-03-16 05:22:47 +00003318 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3319
Anders Carlsson9f853df2009-11-17 04:44:12 +00003320 // Bases.
3321 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3322 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00003323 // Bases are always records in a well-formed non-dependent class.
3324 const RecordType *RT = Base->getType()->getAs<RecordType>();
3325
3326 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003327 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00003328 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003329
John McCall58e6f342010-03-16 05:22:47 +00003330 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003331 // If our base class is invalid, we probably can't get its dtor anyway.
3332 if (BaseClassDecl->isInvalidDecl())
3333 continue;
3334 // Ignore trivial destructors.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003335 if (BaseClassDecl->hasTrivialDestructor())
3336 continue;
John McCall58e6f342010-03-16 05:22:47 +00003337
Douglas Gregordb89f282010-07-01 22:47:18 +00003338 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003339 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003340
3341 // FIXME: caret should be on the start of the class name
3342 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003343 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00003344 << Base->getType()
3345 << Base->getSourceRange());
Anders Carlsson9f853df2009-11-17 04:44:12 +00003346
Eli Friedman5f2987c2012-02-02 03:46:19 +00003347 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00003348 }
3349
3350 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003351 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3352 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00003353
3354 // Bases are always records in a well-formed non-dependent class.
3355 const RecordType *RT = VBase->getType()->getAs<RecordType>();
3356
3357 // Ignore direct virtual bases.
3358 if (DirectVirtualBases.count(RT))
3359 continue;
3360
John McCall58e6f342010-03-16 05:22:47 +00003361 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003362 // If our base class is invalid, we probably can't get its dtor anyway.
3363 if (BaseClassDecl->isInvalidDecl())
3364 continue;
3365 // Ignore trivial destructors.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003366 if (BaseClassDecl->hasTrivialDestructor())
3367 continue;
John McCall58e6f342010-03-16 05:22:47 +00003368
Douglas Gregordb89f282010-07-01 22:47:18 +00003369 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003370 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003371 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003372 PDiag(diag::err_access_dtor_vbase)
John McCall58e6f342010-03-16 05:22:47 +00003373 << VBase->getType());
3374
Eli Friedman5f2987c2012-02-02 03:46:19 +00003375 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003376 }
3377}
3378
John McCalld226f652010-08-21 09:40:31 +00003379void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00003380 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003381 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003382
Mike Stump1eb44332009-09-09 15:08:12 +00003383 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003384 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Sean Huntcbb67482011-01-08 20:30:50 +00003385 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003386}
3387
Mike Stump1eb44332009-09-09 15:08:12 +00003388bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00003389 unsigned DiagID, AbstractDiagSelID SelID) {
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003390 if (SelID == -1)
John McCall94c3b562010-08-18 09:41:07 +00003391 return RequireNonAbstractType(Loc, T, PDiag(DiagID));
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003392 else
John McCall94c3b562010-08-18 09:41:07 +00003393 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
Mike Stump1eb44332009-09-09 15:08:12 +00003394}
3395
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003396bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00003397 const PartialDiagnostic &PD) {
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003398 if (!getLangOptions().CPlusPlus)
3399 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003400
Anders Carlsson11f21a02009-03-23 19:10:31 +00003401 if (const ArrayType *AT = Context.getAsArrayType(T))
John McCall94c3b562010-08-18 09:41:07 +00003402 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Mike Stump1eb44332009-09-09 15:08:12 +00003403
Ted Kremenek6217b802009-07-29 21:53:49 +00003404 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003405 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00003406 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003407 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00003408
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003409 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
John McCall94c3b562010-08-18 09:41:07 +00003410 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003411 }
Mike Stump1eb44332009-09-09 15:08:12 +00003412
Ted Kremenek6217b802009-07-29 21:53:49 +00003413 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003414 if (!RT)
3415 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003416
John McCall86ff3082010-02-04 22:26:26 +00003417 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003418
John McCall94c3b562010-08-18 09:41:07 +00003419 // We can't answer whether something is abstract until it has a
3420 // definition. If it's currently being defined, we'll walk back
3421 // over all the declarations when we have a full definition.
3422 const CXXRecordDecl *Def = RD->getDefinition();
3423 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00003424 return false;
3425
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003426 if (!RD->isAbstract())
3427 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003428
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003429 Diag(Loc, PD) << RD->getDeclName();
John McCall94c3b562010-08-18 09:41:07 +00003430 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00003431
John McCall94c3b562010-08-18 09:41:07 +00003432 return true;
3433}
3434
3435void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
3436 // Check if we've already emitted the list of pure virtual functions
3437 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003438 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00003439 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003440
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003441 CXXFinalOverriderMap FinalOverriders;
3442 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00003443
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003444 // Keep a set of seen pure methods so we won't diagnose the same method
3445 // more than once.
3446 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
3447
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003448 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
3449 MEnd = FinalOverriders.end();
3450 M != MEnd;
3451 ++M) {
3452 for (OverridingMethods::iterator SO = M->second.begin(),
3453 SOEnd = M->second.end();
3454 SO != SOEnd; ++SO) {
3455 // C++ [class.abstract]p4:
3456 // A class is abstract if it contains or inherits at least one
3457 // pure virtual function for which the final overrider is pure
3458 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00003459
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003460 //
3461 if (SO->second.size() != 1)
3462 continue;
3463
3464 if (!SO->second.front().Method->isPure())
3465 continue;
3466
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003467 if (!SeenPureMethods.insert(SO->second.front().Method))
3468 continue;
3469
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003470 Diag(SO->second.front().Method->getLocation(),
3471 diag::note_pure_virtual_function)
Chandler Carruth45f11b72011-02-18 23:59:51 +00003472 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003473 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003474 }
3475
3476 if (!PureVirtualClassDiagSet)
3477 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
3478 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003479}
3480
Anders Carlsson8211eff2009-03-24 01:19:16 +00003481namespace {
John McCall94c3b562010-08-18 09:41:07 +00003482struct AbstractUsageInfo {
3483 Sema &S;
3484 CXXRecordDecl *Record;
3485 CanQualType AbstractType;
3486 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00003487
John McCall94c3b562010-08-18 09:41:07 +00003488 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
3489 : S(S), Record(Record),
3490 AbstractType(S.Context.getCanonicalType(
3491 S.Context.getTypeDeclType(Record))),
3492 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00003493
John McCall94c3b562010-08-18 09:41:07 +00003494 void DiagnoseAbstractType() {
3495 if (Invalid) return;
3496 S.DiagnoseAbstractType(Record);
3497 Invalid = true;
3498 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00003499
John McCall94c3b562010-08-18 09:41:07 +00003500 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
3501};
3502
3503struct CheckAbstractUsage {
3504 AbstractUsageInfo &Info;
3505 const NamedDecl *Ctx;
3506
3507 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
3508 : Info(Info), Ctx(Ctx) {}
3509
3510 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3511 switch (TL.getTypeLocClass()) {
3512#define ABSTRACT_TYPELOC(CLASS, PARENT)
3513#define TYPELOC(CLASS, PARENT) \
3514 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
3515#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00003516 }
John McCall94c3b562010-08-18 09:41:07 +00003517 }
Mike Stump1eb44332009-09-09 15:08:12 +00003518
John McCall94c3b562010-08-18 09:41:07 +00003519 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3520 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
3521 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor70191862011-02-22 23:21:06 +00003522 if (!TL.getArg(I))
3523 continue;
3524
John McCall94c3b562010-08-18 09:41:07 +00003525 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
3526 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003527 }
John McCall94c3b562010-08-18 09:41:07 +00003528 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003529
John McCall94c3b562010-08-18 09:41:07 +00003530 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3531 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
3532 }
Mike Stump1eb44332009-09-09 15:08:12 +00003533
John McCall94c3b562010-08-18 09:41:07 +00003534 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3535 // Visit the type parameters from a permissive context.
3536 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3537 TemplateArgumentLoc TAL = TL.getArgLoc(I);
3538 if (TAL.getArgument().getKind() == TemplateArgument::Type)
3539 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
3540 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
3541 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00003542 }
John McCall94c3b562010-08-18 09:41:07 +00003543 }
Mike Stump1eb44332009-09-09 15:08:12 +00003544
John McCall94c3b562010-08-18 09:41:07 +00003545 // Visit pointee types from a permissive context.
3546#define CheckPolymorphic(Type) \
3547 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
3548 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
3549 }
3550 CheckPolymorphic(PointerTypeLoc)
3551 CheckPolymorphic(ReferenceTypeLoc)
3552 CheckPolymorphic(MemberPointerTypeLoc)
3553 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedmanb001de72011-10-06 23:00:33 +00003554 CheckPolymorphic(AtomicTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00003555
John McCall94c3b562010-08-18 09:41:07 +00003556 /// Handle all the types we haven't given a more specific
3557 /// implementation for above.
3558 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3559 // Every other kind of type that we haven't called out already
3560 // that has an inner type is either (1) sugar or (2) contains that
3561 // inner type in some way as a subobject.
3562 if (TypeLoc Next = TL.getNextTypeLoc())
3563 return Visit(Next, Sel);
3564
3565 // If there's no inner type and we're in a permissive context,
3566 // don't diagnose.
3567 if (Sel == Sema::AbstractNone) return;
3568
3569 // Check whether the type matches the abstract type.
3570 QualType T = TL.getType();
3571 if (T->isArrayType()) {
3572 Sel = Sema::AbstractArrayType;
3573 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003574 }
John McCall94c3b562010-08-18 09:41:07 +00003575 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
3576 if (CT != Info.AbstractType) return;
3577
3578 // It matched; do some magic.
3579 if (Sel == Sema::AbstractArrayType) {
3580 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
3581 << T << TL.getSourceRange();
3582 } else {
3583 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
3584 << Sel << T << TL.getSourceRange();
3585 }
3586 Info.DiagnoseAbstractType();
3587 }
3588};
3589
3590void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
3591 Sema::AbstractDiagSelID Sel) {
3592 CheckAbstractUsage(*this, D).Visit(TL, Sel);
3593}
3594
3595}
3596
3597/// Check for invalid uses of an abstract type in a method declaration.
3598static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3599 CXXMethodDecl *MD) {
3600 // No need to do the check on definitions, which require that
3601 // the return/param types be complete.
Sean Hunt10620eb2011-05-06 20:44:56 +00003602 if (MD->doesThisDeclarationHaveABody())
John McCall94c3b562010-08-18 09:41:07 +00003603 return;
3604
3605 // For safety's sake, just ignore it if we don't have type source
3606 // information. This should never happen for non-implicit methods,
3607 // but...
3608 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
3609 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
3610}
3611
3612/// Check for invalid uses of an abstract type within a class definition.
3613static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3614 CXXRecordDecl *RD) {
3615 for (CXXRecordDecl::decl_iterator
3616 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
3617 Decl *D = *I;
3618 if (D->isImplicit()) continue;
3619
3620 // Methods and method templates.
3621 if (isa<CXXMethodDecl>(D)) {
3622 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
3623 } else if (isa<FunctionTemplateDecl>(D)) {
3624 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
3625 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
3626
3627 // Fields and static variables.
3628 } else if (isa<FieldDecl>(D)) {
3629 FieldDecl *FD = cast<FieldDecl>(D);
3630 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
3631 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
3632 } else if (isa<VarDecl>(D)) {
3633 VarDecl *VD = cast<VarDecl>(D);
3634 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
3635 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
3636
3637 // Nested classes and class templates.
3638 } else if (isa<CXXRecordDecl>(D)) {
3639 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
3640 } else if (isa<ClassTemplateDecl>(D)) {
3641 CheckAbstractClassUsage(Info,
3642 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
3643 }
3644 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003645}
3646
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003647/// \brief Perform semantic checks on a class definition that has been
3648/// completing, introducing implicitly-declared members, checking for
3649/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00003650void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00003651 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003652 return;
3653
John McCall94c3b562010-08-18 09:41:07 +00003654 if (Record->isAbstract() && !Record->isInvalidDecl()) {
3655 AbstractUsageInfo Info(*this, Record);
3656 CheckAbstractClassUsage(Info, Record);
3657 }
Douglas Gregor325e5932010-04-15 00:00:53 +00003658
3659 // If this is not an aggregate type and has no user-declared constructor,
3660 // complain about any non-static data members of reference or const scalar
3661 // type, since they will never get initializers.
3662 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregor5e058eb2012-02-09 02:20:38 +00003663 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
3664 !Record->isLambda()) {
Douglas Gregor325e5932010-04-15 00:00:53 +00003665 bool Complained = false;
3666 for (RecordDecl::field_iterator F = Record->field_begin(),
3667 FEnd = Record->field_end();
3668 F != FEnd; ++F) {
Douglas Gregord61db332011-10-10 17:22:13 +00003669 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith7a614d82011-06-11 17:19:42 +00003670 continue;
3671
Douglas Gregor325e5932010-04-15 00:00:53 +00003672 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00003673 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00003674 if (!Complained) {
3675 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
3676 << Record->getTagKind() << Record;
3677 Complained = true;
3678 }
3679
3680 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
3681 << F->getType()->isReferenceType()
3682 << F->getDeclName();
3683 }
3684 }
3685 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003686
Anders Carlssona5c6c2a2011-01-25 18:08:22 +00003687 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003688 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00003689
3690 if (Record->getIdentifier()) {
3691 // C++ [class.mem]p13:
3692 // If T is the name of a class, then each of the following shall have a
3693 // name different from T:
3694 // - every member of every anonymous union that is a member of class T.
3695 //
3696 // C++ [class.mem]p14:
3697 // In addition, if class T has a user-declared constructor (12.1), every
3698 // non-static data member of class T shall have a name different from T.
3699 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
Francois Pichet87c2e122010-11-21 06:08:52 +00003700 R.first != R.second; ++R.first) {
3701 NamedDecl *D = *R.first;
3702 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
3703 isa<IndirectFieldDecl>(D)) {
3704 Diag(D->getLocation(), diag::err_member_name_of_class)
3705 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00003706 break;
3707 }
Francois Pichet87c2e122010-11-21 06:08:52 +00003708 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00003709 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003710
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003711 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregorf4b793c2011-02-19 19:14:36 +00003712 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003713 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003714 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003715 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
3716 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
3717 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003718
3719 // See if a method overloads virtual methods in a base
3720 /// class without overriding any.
3721 if (!Record->isDependentType()) {
3722 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3723 MEnd = Record->method_end();
3724 M != MEnd; ++M) {
Argyrios Kyrtzidis0266aa32011-03-03 22:58:57 +00003725 if (!(*M)->isStatic())
3726 DiagnoseHiddenVirtualMethods(Record, *M);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003727 }
3728 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00003729
Richard Smith9f569cc2011-10-01 02:31:28 +00003730 // C++0x [dcl.constexpr]p8: A constexpr specifier for a non-static member
3731 // function that is not a constructor declares that member function to be
3732 // const. [...] The class of which that function is a member shall be
3733 // a literal type.
3734 //
Richard Smith9f569cc2011-10-01 02:31:28 +00003735 // If the class has virtual bases, any constexpr members will already have
3736 // been diagnosed by the checks performed on the member declaration, so
3737 // suppress this (less useful) diagnostic.
3738 if (LangOpts.CPlusPlus0x && !Record->isDependentType() &&
3739 !Record->isLiteral() && !Record->getNumVBases()) {
3740 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3741 MEnd = Record->method_end();
3742 M != MEnd; ++M) {
Richard Smith86c3ae42012-02-13 03:54:03 +00003743 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) {
Richard Smith9f569cc2011-10-01 02:31:28 +00003744 switch (Record->getTemplateSpecializationKind()) {
3745 case TSK_ImplicitInstantiation:
3746 case TSK_ExplicitInstantiationDeclaration:
3747 case TSK_ExplicitInstantiationDefinition:
3748 // If a template instantiates to a non-literal type, but its members
3749 // instantiate to constexpr functions, the template is technically
Richard Smith86c3ae42012-02-13 03:54:03 +00003750 // ill-formed, but we allow it for sanity.
Richard Smith9f569cc2011-10-01 02:31:28 +00003751 continue;
3752
3753 case TSK_Undeclared:
3754 case TSK_ExplicitSpecialization:
3755 RequireLiteralType((*M)->getLocation(), Context.getRecordType(Record),
3756 PDiag(diag::err_constexpr_method_non_literal));
3757 break;
3758 }
3759
3760 // Only produce one error per class.
3761 break;
3762 }
3763 }
3764 }
3765
Sebastian Redlf677ea32011-02-05 19:23:19 +00003766 // Declare inherited constructors. We do this eagerly here because:
3767 // - The standard requires an eager diagnostic for conflicting inherited
3768 // constructors from different classes.
3769 // - The lazy declaration of the other implicit constructors is so as to not
3770 // waste space and performance on classes that are not meant to be
3771 // instantiated (e.g. meta-functions). This doesn't apply to classes that
3772 // have inherited constructors.
Sebastian Redlcaa35e42011-03-12 13:44:32 +00003773 DeclareInheritedConstructors(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00003774
Sean Hunteb88ae52011-05-23 21:07:59 +00003775 if (!Record->isDependentType())
3776 CheckExplicitlyDefaultedMethods(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00003777}
3778
3779void Sema::CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00003780 for (CXXRecordDecl::method_iterator MI = Record->method_begin(),
3781 ME = Record->method_end();
3782 MI != ME; ++MI) {
3783 if (!MI->isInvalidDecl() && MI->isExplicitlyDefaulted()) {
3784 switch (getSpecialMember(*MI)) {
3785 case CXXDefaultConstructor:
3786 CheckExplicitlyDefaultedDefaultConstructor(
3787 cast<CXXConstructorDecl>(*MI));
3788 break;
Sean Hunt001cad92011-05-10 00:49:42 +00003789
Sean Huntcb45a0f2011-05-12 22:46:25 +00003790 case CXXDestructor:
3791 CheckExplicitlyDefaultedDestructor(cast<CXXDestructorDecl>(*MI));
3792 break;
3793
3794 case CXXCopyConstructor:
Sean Hunt49634cf2011-05-13 06:10:58 +00003795 CheckExplicitlyDefaultedCopyConstructor(cast<CXXConstructorDecl>(*MI));
3796 break;
3797
Sean Huntcb45a0f2011-05-12 22:46:25 +00003798 case CXXCopyAssignment:
Sean Hunt2b188082011-05-14 05:23:28 +00003799 CheckExplicitlyDefaultedCopyAssignment(*MI);
Sean Huntcb45a0f2011-05-12 22:46:25 +00003800 break;
3801
Sean Hunt82713172011-05-25 23:16:36 +00003802 case CXXMoveConstructor:
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003803 CheckExplicitlyDefaultedMoveConstructor(cast<CXXConstructorDecl>(*MI));
Sean Hunt82713172011-05-25 23:16:36 +00003804 break;
3805
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003806 case CXXMoveAssignment:
3807 CheckExplicitlyDefaultedMoveAssignment(*MI);
3808 break;
3809
3810 case CXXInvalid:
Sean Huntcb45a0f2011-05-12 22:46:25 +00003811 llvm_unreachable("non-special member explicitly defaulted!");
3812 }
Sean Hunt001cad92011-05-10 00:49:42 +00003813 }
3814 }
3815
Sean Hunt001cad92011-05-10 00:49:42 +00003816}
3817
3818void Sema::CheckExplicitlyDefaultedDefaultConstructor(CXXConstructorDecl *CD) {
3819 assert(CD->isExplicitlyDefaulted() && CD->isDefaultConstructor());
3820
3821 // Whether this was the first-declared instance of the constructor.
3822 // This affects whether we implicitly add an exception spec (and, eventually,
3823 // constexpr). It is also ill-formed to explicitly default a constructor such
3824 // that it would be deleted. (C++0x [decl.fct.def.default])
3825 bool First = CD == CD->getCanonicalDecl();
3826
Sean Hunt49634cf2011-05-13 06:10:58 +00003827 bool HadError = false;
Sean Hunt001cad92011-05-10 00:49:42 +00003828 if (CD->getNumParams() != 0) {
3829 Diag(CD->getLocation(), diag::err_defaulted_default_ctor_params)
3830 << CD->getSourceRange();
Sean Hunt49634cf2011-05-13 06:10:58 +00003831 HadError = true;
Sean Hunt001cad92011-05-10 00:49:42 +00003832 }
3833
3834 ImplicitExceptionSpecification Spec
3835 = ComputeDefaultedDefaultCtorExceptionSpec(CD->getParent());
3836 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Richard Smith7a614d82011-06-11 17:19:42 +00003837 if (EPI.ExceptionSpecType == EST_Delayed) {
3838 // Exception specification depends on some deferred part of the class. We'll
3839 // try again when the class's definition has been fully processed.
3840 return;
3841 }
Sean Hunt001cad92011-05-10 00:49:42 +00003842 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3843 *ExceptionType = Context.getFunctionType(
3844 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3845
Richard Smith61802452011-12-22 02:22:31 +00003846 // C++11 [dcl.fct.def.default]p2:
3847 // An explicitly-defaulted function may be declared constexpr only if it
3848 // would have been implicitly declared as constexpr,
Richard Smitheb273b72012-02-14 02:33:50 +00003849 // Do not apply this rule to templates, since core issue 1358 makes such
3850 // functions always instantiate to constexpr functions.
3851 if (CD->isConstexpr() &&
3852 CD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
Richard Smith61802452011-12-22 02:22:31 +00003853 if (!CD->getParent()->defaultedDefaultConstructorIsConstexpr()) {
3854 Diag(CD->getLocStart(), diag::err_incorrect_defaulted_constexpr)
3855 << CXXDefaultConstructor;
3856 HadError = true;
3857 }
3858 }
3859 // and may have an explicit exception-specification only if it is compatible
3860 // with the exception-specification on the implicit declaration.
Sean Hunt001cad92011-05-10 00:49:42 +00003861 if (CtorType->hasExceptionSpec()) {
3862 if (CheckEquivalentExceptionSpec(
Sean Huntcb45a0f2011-05-12 22:46:25 +00003863 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00003864 << CXXDefaultConstructor,
Sean Hunt001cad92011-05-10 00:49:42 +00003865 PDiag(),
3866 ExceptionType, SourceLocation(),
3867 CtorType, CD->getLocation())) {
Sean Hunt49634cf2011-05-13 06:10:58 +00003868 HadError = true;
Sean Hunt001cad92011-05-10 00:49:42 +00003869 }
Richard Smith61802452011-12-22 02:22:31 +00003870 }
3871
3872 // If a function is explicitly defaulted on its first declaration,
3873 if (First) {
3874 // -- it is implicitly considered to be constexpr if the implicit
3875 // definition would be,
3876 CD->setConstexpr(CD->getParent()->defaultedDefaultConstructorIsConstexpr());
3877
3878 // -- it is implicitly considered to have the same
3879 // exception-specification as if it had been implicitly declared
3880 //
3881 // FIXME: a compatible, but different, explicit exception specification
3882 // will be silently overridden. We should issue a warning if this happens.
Sean Hunt2b188082011-05-14 05:23:28 +00003883 EPI.ExtInfo = CtorType->getExtInfo();
Sean Hunt001cad92011-05-10 00:49:42 +00003884 }
Sean Huntca46d132011-05-12 03:51:48 +00003885
Sean Hunt49634cf2011-05-13 06:10:58 +00003886 if (HadError) {
3887 CD->setInvalidDecl();
3888 return;
3889 }
3890
Sean Hunte16da072011-10-10 06:18:57 +00003891 if (ShouldDeleteSpecialMember(CD, CXXDefaultConstructor)) {
Sean Hunt49634cf2011-05-13 06:10:58 +00003892 if (First) {
Sean Huntca46d132011-05-12 03:51:48 +00003893 CD->setDeletedAsWritten();
Sean Hunt49634cf2011-05-13 06:10:58 +00003894 } else {
Sean Huntca46d132011-05-12 03:51:48 +00003895 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00003896 << CXXDefaultConstructor;
Sean Hunt49634cf2011-05-13 06:10:58 +00003897 CD->setInvalidDecl();
3898 }
3899 }
3900}
3901
3902void Sema::CheckExplicitlyDefaultedCopyConstructor(CXXConstructorDecl *CD) {
3903 assert(CD->isExplicitlyDefaulted() && CD->isCopyConstructor());
3904
3905 // Whether this was the first-declared instance of the constructor.
3906 bool First = CD == CD->getCanonicalDecl();
3907
3908 bool HadError = false;
3909 if (CD->getNumParams() != 1) {
3910 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_params)
3911 << CD->getSourceRange();
3912 HadError = true;
3913 }
3914
3915 ImplicitExceptionSpecification Spec(Context);
3916 bool Const;
3917 llvm::tie(Spec, Const) =
3918 ComputeDefaultedCopyCtorExceptionSpecAndConst(CD->getParent());
3919
3920 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3921 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3922 *ExceptionType = Context.getFunctionType(
3923 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3924
3925 // Check for parameter type matching.
3926 // This is a copy ctor so we know it's a cv-qualified reference to T.
3927 QualType ArgType = CtorType->getArgType(0);
3928 if (ArgType->getPointeeType().isVolatileQualified()) {
3929 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_volatile_param);
3930 HadError = true;
3931 }
3932 if (ArgType->getPointeeType().isConstQualified() && !Const) {
3933 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_const_param);
3934 HadError = true;
3935 }
3936
Richard Smith61802452011-12-22 02:22:31 +00003937 // C++11 [dcl.fct.def.default]p2:
3938 // An explicitly-defaulted function may be declared constexpr only if it
3939 // would have been implicitly declared as constexpr,
Richard Smitheb273b72012-02-14 02:33:50 +00003940 // Do not apply this rule to templates, since core issue 1358 makes such
3941 // functions always instantiate to constexpr functions.
3942 if (CD->isConstexpr() &&
3943 CD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
Richard Smith61802452011-12-22 02:22:31 +00003944 if (!CD->getParent()->defaultedCopyConstructorIsConstexpr()) {
3945 Diag(CD->getLocStart(), diag::err_incorrect_defaulted_constexpr)
3946 << CXXCopyConstructor;
3947 HadError = true;
3948 }
3949 }
3950 // and may have an explicit exception-specification only if it is compatible
3951 // with the exception-specification on the implicit declaration.
Sean Hunt49634cf2011-05-13 06:10:58 +00003952 if (CtorType->hasExceptionSpec()) {
3953 if (CheckEquivalentExceptionSpec(
3954 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00003955 << CXXCopyConstructor,
Sean Hunt49634cf2011-05-13 06:10:58 +00003956 PDiag(),
3957 ExceptionType, SourceLocation(),
3958 CtorType, CD->getLocation())) {
3959 HadError = true;
3960 }
Richard Smith61802452011-12-22 02:22:31 +00003961 }
3962
3963 // If a function is explicitly defaulted on its first declaration,
3964 if (First) {
3965 // -- it is implicitly considered to be constexpr if the implicit
3966 // definition would be,
3967 CD->setConstexpr(CD->getParent()->defaultedCopyConstructorIsConstexpr());
3968
3969 // -- it is implicitly considered to have the same
3970 // exception-specification as if it had been implicitly declared, and
3971 //
3972 // FIXME: a compatible, but different, explicit exception specification
3973 // will be silently overridden. We should issue a warning if this happens.
Sean Hunt2b188082011-05-14 05:23:28 +00003974 EPI.ExtInfo = CtorType->getExtInfo();
Richard Smith61802452011-12-22 02:22:31 +00003975
3976 // -- [...] it shall have the same parameter type as if it had been
3977 // implicitly declared.
Sean Hunt49634cf2011-05-13 06:10:58 +00003978 CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
3979 }
3980
3981 if (HadError) {
3982 CD->setInvalidDecl();
3983 return;
3984 }
3985
Sean Huntc32d6842011-10-11 04:55:36 +00003986 if (ShouldDeleteSpecialMember(CD, CXXCopyConstructor)) {
Sean Hunt49634cf2011-05-13 06:10:58 +00003987 if (First) {
3988 CD->setDeletedAsWritten();
3989 } else {
3990 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00003991 << CXXCopyConstructor;
Sean Hunt49634cf2011-05-13 06:10:58 +00003992 CD->setInvalidDecl();
3993 }
Sean Huntca46d132011-05-12 03:51:48 +00003994 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00003995}
Sean Hunt001cad92011-05-10 00:49:42 +00003996
Sean Hunt2b188082011-05-14 05:23:28 +00003997void Sema::CheckExplicitlyDefaultedCopyAssignment(CXXMethodDecl *MD) {
3998 assert(MD->isExplicitlyDefaulted());
3999
4000 // Whether this was the first-declared instance of the operator
4001 bool First = MD == MD->getCanonicalDecl();
4002
4003 bool HadError = false;
4004 if (MD->getNumParams() != 1) {
4005 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_params)
4006 << MD->getSourceRange();
4007 HadError = true;
4008 }
4009
4010 QualType ReturnType =
4011 MD->getType()->getAs<FunctionType>()->getResultType();
4012 if (!ReturnType->isLValueReferenceType() ||
4013 !Context.hasSameType(
4014 Context.getCanonicalType(ReturnType->getPointeeType()),
4015 Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
4016 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_return_type);
4017 HadError = true;
4018 }
4019
4020 ImplicitExceptionSpecification Spec(Context);
4021 bool Const;
4022 llvm::tie(Spec, Const) =
4023 ComputeDefaultedCopyCtorExceptionSpecAndConst(MD->getParent());
4024
4025 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4026 const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
4027 *ExceptionType = Context.getFunctionType(
4028 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4029
Sean Hunt2b188082011-05-14 05:23:28 +00004030 QualType ArgType = OperType->getArgType(0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004031 if (!ArgType->isLValueReferenceType()) {
Sean Huntbe631222011-05-17 20:44:43 +00004032 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Sean Hunt2b188082011-05-14 05:23:28 +00004033 HadError = true;
Sean Huntbe631222011-05-17 20:44:43 +00004034 } else {
4035 if (ArgType->getPointeeType().isVolatileQualified()) {
4036 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_volatile_param);
4037 HadError = true;
4038 }
4039 if (ArgType->getPointeeType().isConstQualified() && !Const) {
4040 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_const_param);
4041 HadError = true;
4042 }
Sean Hunt2b188082011-05-14 05:23:28 +00004043 }
Sean Huntbe631222011-05-17 20:44:43 +00004044
Sean Hunt2b188082011-05-14 05:23:28 +00004045 if (OperType->getTypeQuals()) {
4046 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_quals);
4047 HadError = true;
4048 }
4049
4050 if (OperType->hasExceptionSpec()) {
4051 if (CheckEquivalentExceptionSpec(
4052 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00004053 << CXXCopyAssignment,
Sean Hunt2b188082011-05-14 05:23:28 +00004054 PDiag(),
4055 ExceptionType, SourceLocation(),
4056 OperType, MD->getLocation())) {
4057 HadError = true;
4058 }
Richard Smith61802452011-12-22 02:22:31 +00004059 }
4060 if (First) {
Sean Hunt2b188082011-05-14 05:23:28 +00004061 // We set the declaration to have the computed exception spec here.
4062 // We duplicate the one parameter type.
4063 EPI.RefQualifier = OperType->getRefQualifier();
4064 EPI.ExtInfo = OperType->getExtInfo();
4065 MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
4066 }
4067
4068 if (HadError) {
4069 MD->setInvalidDecl();
4070 return;
4071 }
4072
4073 if (ShouldDeleteCopyAssignmentOperator(MD)) {
4074 if (First) {
4075 MD->setDeletedAsWritten();
4076 } else {
4077 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00004078 << CXXCopyAssignment;
Sean Hunt2b188082011-05-14 05:23:28 +00004079 MD->setInvalidDecl();
4080 }
4081 }
4082}
4083
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004084void Sema::CheckExplicitlyDefaultedMoveConstructor(CXXConstructorDecl *CD) {
4085 assert(CD->isExplicitlyDefaulted() && CD->isMoveConstructor());
4086
4087 // Whether this was the first-declared instance of the constructor.
4088 bool First = CD == CD->getCanonicalDecl();
4089
4090 bool HadError = false;
4091 if (CD->getNumParams() != 1) {
4092 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_params)
4093 << CD->getSourceRange();
4094 HadError = true;
4095 }
4096
4097 ImplicitExceptionSpecification Spec(
4098 ComputeDefaultedMoveCtorExceptionSpec(CD->getParent()));
4099
4100 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4101 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
4102 *ExceptionType = Context.getFunctionType(
4103 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4104
4105 // Check for parameter type matching.
4106 // This is a move ctor so we know it's a cv-qualified rvalue reference to T.
4107 QualType ArgType = CtorType->getArgType(0);
4108 if (ArgType->getPointeeType().isVolatileQualified()) {
4109 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_volatile_param);
4110 HadError = true;
4111 }
4112 if (ArgType->getPointeeType().isConstQualified()) {
4113 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_const_param);
4114 HadError = true;
4115 }
4116
Richard Smith61802452011-12-22 02:22:31 +00004117 // C++11 [dcl.fct.def.default]p2:
4118 // An explicitly-defaulted function may be declared constexpr only if it
4119 // would have been implicitly declared as constexpr,
Richard Smitheb273b72012-02-14 02:33:50 +00004120 // Do not apply this rule to templates, since core issue 1358 makes such
4121 // functions always instantiate to constexpr functions.
4122 if (CD->isConstexpr() &&
4123 CD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
Richard Smith61802452011-12-22 02:22:31 +00004124 if (!CD->getParent()->defaultedMoveConstructorIsConstexpr()) {
4125 Diag(CD->getLocStart(), diag::err_incorrect_defaulted_constexpr)
4126 << CXXMoveConstructor;
4127 HadError = true;
4128 }
4129 }
4130 // and may have an explicit exception-specification only if it is compatible
4131 // with the exception-specification on the implicit declaration.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004132 if (CtorType->hasExceptionSpec()) {
4133 if (CheckEquivalentExceptionSpec(
4134 PDiag(diag::err_incorrect_defaulted_exception_spec)
4135 << CXXMoveConstructor,
4136 PDiag(),
4137 ExceptionType, SourceLocation(),
4138 CtorType, CD->getLocation())) {
4139 HadError = true;
4140 }
Richard Smith61802452011-12-22 02:22:31 +00004141 }
4142
4143 // If a function is explicitly defaulted on its first declaration,
4144 if (First) {
4145 // -- it is implicitly considered to be constexpr if the implicit
4146 // definition would be,
4147 CD->setConstexpr(CD->getParent()->defaultedMoveConstructorIsConstexpr());
4148
4149 // -- it is implicitly considered to have the same
4150 // exception-specification as if it had been implicitly declared, and
4151 //
4152 // FIXME: a compatible, but different, explicit exception specification
4153 // will be silently overridden. We should issue a warning if this happens.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004154 EPI.ExtInfo = CtorType->getExtInfo();
Richard Smith61802452011-12-22 02:22:31 +00004155
4156 // -- [...] it shall have the same parameter type as if it had been
4157 // implicitly declared.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004158 CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
4159 }
4160
4161 if (HadError) {
4162 CD->setInvalidDecl();
4163 return;
4164 }
4165
Sean Hunt769bb2d2011-10-11 06:43:29 +00004166 if (ShouldDeleteSpecialMember(CD, CXXMoveConstructor)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004167 if (First) {
4168 CD->setDeletedAsWritten();
4169 } else {
4170 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
4171 << CXXMoveConstructor;
4172 CD->setInvalidDecl();
4173 }
4174 }
4175}
4176
4177void Sema::CheckExplicitlyDefaultedMoveAssignment(CXXMethodDecl *MD) {
4178 assert(MD->isExplicitlyDefaulted());
4179
4180 // Whether this was the first-declared instance of the operator
4181 bool First = MD == MD->getCanonicalDecl();
4182
4183 bool HadError = false;
4184 if (MD->getNumParams() != 1) {
4185 Diag(MD->getLocation(), diag::err_defaulted_move_assign_params)
4186 << MD->getSourceRange();
4187 HadError = true;
4188 }
4189
4190 QualType ReturnType =
4191 MD->getType()->getAs<FunctionType>()->getResultType();
4192 if (!ReturnType->isLValueReferenceType() ||
4193 !Context.hasSameType(
4194 Context.getCanonicalType(ReturnType->getPointeeType()),
4195 Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
4196 Diag(MD->getLocation(), diag::err_defaulted_move_assign_return_type);
4197 HadError = true;
4198 }
4199
4200 ImplicitExceptionSpecification Spec(
4201 ComputeDefaultedMoveCtorExceptionSpec(MD->getParent()));
4202
4203 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4204 const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
4205 *ExceptionType = Context.getFunctionType(
4206 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4207
4208 QualType ArgType = OperType->getArgType(0);
4209 if (!ArgType->isRValueReferenceType()) {
4210 Diag(MD->getLocation(), diag::err_defaulted_move_assign_not_ref);
4211 HadError = true;
4212 } else {
4213 if (ArgType->getPointeeType().isVolatileQualified()) {
4214 Diag(MD->getLocation(), diag::err_defaulted_move_assign_volatile_param);
4215 HadError = true;
4216 }
4217 if (ArgType->getPointeeType().isConstQualified()) {
4218 Diag(MD->getLocation(), diag::err_defaulted_move_assign_const_param);
4219 HadError = true;
4220 }
4221 }
4222
4223 if (OperType->getTypeQuals()) {
4224 Diag(MD->getLocation(), diag::err_defaulted_move_assign_quals);
4225 HadError = true;
4226 }
4227
4228 if (OperType->hasExceptionSpec()) {
4229 if (CheckEquivalentExceptionSpec(
4230 PDiag(diag::err_incorrect_defaulted_exception_spec)
4231 << CXXMoveAssignment,
4232 PDiag(),
4233 ExceptionType, SourceLocation(),
4234 OperType, MD->getLocation())) {
4235 HadError = true;
4236 }
Richard Smith61802452011-12-22 02:22:31 +00004237 }
4238 if (First) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004239 // We set the declaration to have the computed exception spec here.
4240 // We duplicate the one parameter type.
4241 EPI.RefQualifier = OperType->getRefQualifier();
4242 EPI.ExtInfo = OperType->getExtInfo();
4243 MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
4244 }
4245
4246 if (HadError) {
4247 MD->setInvalidDecl();
4248 return;
4249 }
4250
4251 if (ShouldDeleteMoveAssignmentOperator(MD)) {
4252 if (First) {
4253 MD->setDeletedAsWritten();
4254 } else {
4255 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
4256 << CXXMoveAssignment;
4257 MD->setInvalidDecl();
4258 }
4259 }
4260}
4261
Sean Huntcb45a0f2011-05-12 22:46:25 +00004262void Sema::CheckExplicitlyDefaultedDestructor(CXXDestructorDecl *DD) {
4263 assert(DD->isExplicitlyDefaulted());
4264
4265 // Whether this was the first-declared instance of the destructor.
4266 bool First = DD == DD->getCanonicalDecl();
4267
4268 ImplicitExceptionSpecification Spec
4269 = ComputeDefaultedDtorExceptionSpec(DD->getParent());
4270 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4271 const FunctionProtoType *DtorType = DD->getType()->getAs<FunctionProtoType>(),
4272 *ExceptionType = Context.getFunctionType(
4273 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4274
4275 if (DtorType->hasExceptionSpec()) {
4276 if (CheckEquivalentExceptionSpec(
4277 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00004278 << CXXDestructor,
Sean Huntcb45a0f2011-05-12 22:46:25 +00004279 PDiag(),
4280 ExceptionType, SourceLocation(),
4281 DtorType, DD->getLocation())) {
4282 DD->setInvalidDecl();
4283 return;
4284 }
Richard Smith61802452011-12-22 02:22:31 +00004285 }
4286 if (First) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00004287 // We set the declaration to have the computed exception spec here.
4288 // There are no parameters.
Sean Hunt2b188082011-05-14 05:23:28 +00004289 EPI.ExtInfo = DtorType->getExtInfo();
Sean Huntcb45a0f2011-05-12 22:46:25 +00004290 DD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
4291 }
4292
4293 if (ShouldDeleteDestructor(DD)) {
Sean Hunt49634cf2011-05-13 06:10:58 +00004294 if (First) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00004295 DD->setDeletedAsWritten();
Sean Hunt49634cf2011-05-13 06:10:58 +00004296 } else {
Sean Huntcb45a0f2011-05-12 22:46:25 +00004297 Diag(DD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00004298 << CXXDestructor;
Sean Hunt49634cf2011-05-13 06:10:58 +00004299 DD->setInvalidDecl();
4300 }
Sean Huntcb45a0f2011-05-12 22:46:25 +00004301 }
Sean Huntcb45a0f2011-05-12 22:46:25 +00004302}
4303
Sean Hunte16da072011-10-10 06:18:57 +00004304/// This function implements the following C++0x paragraphs:
4305/// - [class.ctor]/5
Sean Huntc32d6842011-10-11 04:55:36 +00004306/// - [class.copy]/11
Sean Hunte16da072011-10-10 06:18:57 +00004307bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM) {
4308 assert(!MD->isInvalidDecl());
4309 CXXRecordDecl *RD = MD->getParent();
Sean Huntcdee3fe2011-05-11 22:34:38 +00004310 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaracdb80762011-07-11 08:52:40 +00004311 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004312 return false;
4313
Sean Hunte16da072011-10-10 06:18:57 +00004314 bool IsUnion = RD->isUnion();
4315 bool IsConstructor = false;
4316 bool IsAssignment = false;
4317 bool IsMove = false;
4318
4319 bool ConstArg = false;
4320
4321 switch (CSM) {
4322 case CXXDefaultConstructor:
4323 IsConstructor = true;
Douglas Gregor215e4e12012-02-12 17:34:23 +00004324
4325 // C++11 [expr.lambda.prim]p19:
4326 // The closure type associated with a lambda-expression has a
4327 // deleted (8.4.3) default constructor.
4328 if (RD->isLambda())
4329 return true;
4330
Sean Hunte16da072011-10-10 06:18:57 +00004331 break;
Sean Huntc32d6842011-10-11 04:55:36 +00004332 case CXXCopyConstructor:
4333 IsConstructor = true;
4334 ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4335 break;
Sean Hunt769bb2d2011-10-11 06:43:29 +00004336 case CXXMoveConstructor:
4337 IsConstructor = true;
4338 IsMove = true;
4339 break;
Sean Hunte16da072011-10-10 06:18:57 +00004340 default:
4341 llvm_unreachable("function only currently implemented for default ctors");
4342 }
4343
4344 SourceLocation Loc = MD->getLocation();
Sean Hunt71a682f2011-05-18 03:41:58 +00004345
Sean Huntc32d6842011-10-11 04:55:36 +00004346 // Do access control from the special member function
Sean Hunte16da072011-10-10 06:18:57 +00004347 ContextRAII MethodContext(*this, MD);
Sean Huntcdee3fe2011-05-11 22:34:38 +00004348
Sean Huntcdee3fe2011-05-11 22:34:38 +00004349 bool AllConst = true;
4350
Sean Huntcdee3fe2011-05-11 22:34:38 +00004351 // We do this because we should never actually use an anonymous
4352 // union's constructor.
Sean Hunte16da072011-10-10 06:18:57 +00004353 if (IsUnion && RD->isAnonymousStructOrUnion())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004354 return false;
4355
4356 // FIXME: We should put some diagnostic logic right into this function.
4357
Sean Huntcdee3fe2011-05-11 22:34:38 +00004358 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4359 BE = RD->bases_end();
4360 BI != BE; ++BI) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00004361 // We'll handle this one later
4362 if (BI->isVirtual())
4363 continue;
4364
Sean Huntcdee3fe2011-05-11 22:34:38 +00004365 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4366 assert(BaseDecl && "base isn't a CXXRecordDecl");
4367
Sean Hunte16da072011-10-10 06:18:57 +00004368 // Unless we have an assignment operator, the base's destructor must
4369 // be accessible and not deleted.
4370 if (!IsAssignment) {
4371 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4372 if (BaseDtor->isDeleted())
4373 return true;
4374 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
4375 AR_accessible)
4376 return true;
4377 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004378
Sean Hunte16da072011-10-10 06:18:57 +00004379 // Finding the corresponding member in the base should lead to a
Sean Huntc32d6842011-10-11 04:55:36 +00004380 // unique, accessible, non-deleted function. If we are doing
4381 // a destructor, we have already checked this case.
Sean Hunte16da072011-10-10 06:18:57 +00004382 if (CSM != CXXDestructor) {
4383 SpecialMemberOverloadResult *SMOR =
Sean Hunt769bb2d2011-10-11 06:43:29 +00004384 LookupSpecialMember(BaseDecl, CSM, ConstArg, false, false, false,
Sean Hunte16da072011-10-10 06:18:57 +00004385 false);
4386 if (!SMOR->hasSuccess())
4387 return true;
4388 CXXMethodDecl *BaseMember = SMOR->getMethod();
4389 if (IsConstructor) {
4390 CXXConstructorDecl *BaseCtor = cast<CXXConstructorDecl>(BaseMember);
4391 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(),
4392 PDiag()) != AR_accessible)
4393 return true;
Sean Hunt769bb2d2011-10-11 06:43:29 +00004394
4395 // For a move operation, the corresponding operation must actually
4396 // be a move operation (and not a copy selected by overload
4397 // resolution) unless we are working on a trivially copyable class.
4398 if (IsMove && !BaseCtor->isMoveConstructor() &&
4399 !BaseDecl->isTriviallyCopyable())
4400 return true;
Sean Hunte16da072011-10-10 06:18:57 +00004401 }
4402 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004403 }
4404
4405 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4406 BE = RD->vbases_end();
4407 BI != BE; ++BI) {
4408 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4409 assert(BaseDecl && "base isn't a CXXRecordDecl");
4410
Sean Hunte16da072011-10-10 06:18:57 +00004411 // Unless we have an assignment operator, the base's destructor must
4412 // be accessible and not deleted.
4413 if (!IsAssignment) {
4414 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4415 if (BaseDtor->isDeleted())
4416 return true;
4417 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
4418 AR_accessible)
4419 return true;
4420 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004421
Sean Hunte16da072011-10-10 06:18:57 +00004422 // Finding the corresponding member in the base should lead to a
4423 // unique, accessible, non-deleted function.
4424 if (CSM != CXXDestructor) {
4425 SpecialMemberOverloadResult *SMOR =
Sean Hunt769bb2d2011-10-11 06:43:29 +00004426 LookupSpecialMember(BaseDecl, CSM, ConstArg, false, false, false,
Sean Hunte16da072011-10-10 06:18:57 +00004427 false);
4428 if (!SMOR->hasSuccess())
4429 return true;
4430 CXXMethodDecl *BaseMember = SMOR->getMethod();
4431 if (IsConstructor) {
4432 CXXConstructorDecl *BaseCtor = cast<CXXConstructorDecl>(BaseMember);
4433 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(),
4434 PDiag()) != AR_accessible)
4435 return true;
Sean Hunt769bb2d2011-10-11 06:43:29 +00004436
4437 // For a move operation, the corresponding operation must actually
4438 // be a move operation (and not a copy selected by overload
4439 // resolution) unless we are working on a trivially copyable class.
4440 if (IsMove && !BaseCtor->isMoveConstructor() &&
4441 !BaseDecl->isTriviallyCopyable())
4442 return true;
Sean Hunte16da072011-10-10 06:18:57 +00004443 }
4444 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004445 }
4446
4447 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4448 FE = RD->field_end();
4449 FI != FE; ++FI) {
Douglas Gregord61db332011-10-10 17:22:13 +00004450 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
Richard Smith7a614d82011-06-11 17:19:42 +00004451 continue;
4452
Sean Huntcdee3fe2011-05-11 22:34:38 +00004453 QualType FieldType = Context.getBaseElementType(FI->getType());
4454 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
Richard Smith7a614d82011-06-11 17:19:42 +00004455
Sean Hunte16da072011-10-10 06:18:57 +00004456 // For a default constructor, all references must be initialized in-class
4457 // and, if a union, it must have a non-const member.
4458 if (CSM == CXXDefaultConstructor) {
4459 if (FieldType->isReferenceType() && !FI->hasInClassInitializer())
4460 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004461
Sean Hunte16da072011-10-10 06:18:57 +00004462 if (IsUnion && !FieldType.isConstQualified())
4463 AllConst = false;
Sean Huntc32d6842011-10-11 04:55:36 +00004464 // For a copy constructor, data members must not be of rvalue reference
4465 // type.
4466 } else if (CSM == CXXCopyConstructor) {
4467 if (FieldType->isRValueReferenceType())
4468 return true;
Sean Hunte16da072011-10-10 06:18:57 +00004469 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004470
4471 if (FieldRecord) {
Sean Hunte16da072011-10-10 06:18:57 +00004472 // For a default constructor, a const member must have a user-provided
4473 // default constructor or else be explicitly initialized.
4474 if (CSM == CXXDefaultConstructor && FieldType.isConstQualified() &&
Richard Smith7a614d82011-06-11 17:19:42 +00004475 !FI->hasInClassInitializer() &&
Sean Huntcdee3fe2011-05-11 22:34:38 +00004476 !FieldRecord->hasUserProvidedDefaultConstructor())
4477 return true;
4478
Sean Huntc32d6842011-10-11 04:55:36 +00004479 // Some additional restrictions exist on the variant members.
4480 if (!IsUnion && FieldRecord->isUnion() &&
Sean Huntcdee3fe2011-05-11 22:34:38 +00004481 FieldRecord->isAnonymousStructOrUnion()) {
4482 // We're okay to reuse AllConst here since we only care about the
4483 // value otherwise if we're in a union.
4484 AllConst = true;
4485
4486 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4487 UE = FieldRecord->field_end();
4488 UI != UE; ++UI) {
4489 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4490 CXXRecordDecl *UnionFieldRecord =
4491 UnionFieldType->getAsCXXRecordDecl();
4492
4493 if (!UnionFieldType.isConstQualified())
4494 AllConst = false;
4495
Sean Huntc32d6842011-10-11 04:55:36 +00004496 if (UnionFieldRecord) {
4497 // FIXME: Checking for accessibility and validity of this
4498 // destructor is technically going beyond the
4499 // standard, but this is believed to be a defect.
4500 if (!IsAssignment) {
4501 CXXDestructorDecl *FieldDtor = LookupDestructor(UnionFieldRecord);
4502 if (FieldDtor->isDeleted())
4503 return true;
4504 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
4505 AR_accessible)
4506 return true;
4507 if (!FieldDtor->isTrivial())
4508 return true;
4509 }
4510
4511 if (CSM != CXXDestructor) {
4512 SpecialMemberOverloadResult *SMOR =
4513 LookupSpecialMember(UnionFieldRecord, CSM, ConstArg, false,
Sean Hunt769bb2d2011-10-11 06:43:29 +00004514 false, false, false);
Sean Huntc32d6842011-10-11 04:55:36 +00004515 // FIXME: Checking for accessibility and validity of this
4516 // corresponding member is technically going beyond the
4517 // standard, but this is believed to be a defect.
4518 if (!SMOR->hasSuccess())
4519 return true;
4520
4521 CXXMethodDecl *FieldMember = SMOR->getMethod();
4522 // A member of a union must have a trivial corresponding
4523 // constructor.
4524 if (!FieldMember->isTrivial())
4525 return true;
4526
4527 if (IsConstructor) {
4528 CXXConstructorDecl *FieldCtor = cast<CXXConstructorDecl>(FieldMember);
4529 if (CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getAccess(),
4530 PDiag()) != AR_accessible)
4531 return true;
4532 }
4533 }
4534 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004535 }
Sean Hunt2be7e902011-05-12 22:46:29 +00004536
Sean Huntc32d6842011-10-11 04:55:36 +00004537 // At least one member in each anonymous union must be non-const
4538 if (CSM == CXXDefaultConstructor && AllConst)
Sean Huntcdee3fe2011-05-11 22:34:38 +00004539 return true;
4540
4541 // Don't try to initialize the anonymous union
Sean Hunta6bff2c2011-05-11 22:50:12 +00004542 // This is technically non-conformant, but sanity demands it.
Sean Huntcdee3fe2011-05-11 22:34:38 +00004543 continue;
4544 }
Sean Huntb320e0c2011-06-10 03:50:41 +00004545
Sean Huntc32d6842011-10-11 04:55:36 +00004546 // Unless we're doing assignment, the field's destructor must be
4547 // accessible and not deleted.
4548 if (!IsAssignment) {
4549 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
4550 if (FieldDtor->isDeleted())
4551 return true;
4552 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
4553 AR_accessible)
4554 return true;
4555 }
4556
Sean Hunte16da072011-10-10 06:18:57 +00004557 // Check that the corresponding member of the field is accessible,
4558 // unique, and non-deleted. We don't do this if it has an explicit
4559 // initialization when default-constructing.
4560 if (CSM != CXXDestructor &&
4561 (CSM != CXXDefaultConstructor || !FI->hasInClassInitializer())) {
4562 SpecialMemberOverloadResult *SMOR =
Sean Hunt769bb2d2011-10-11 06:43:29 +00004563 LookupSpecialMember(FieldRecord, CSM, ConstArg, false, false, false,
Sean Hunte16da072011-10-10 06:18:57 +00004564 false);
4565 if (!SMOR->hasSuccess())
Richard Smith7a614d82011-06-11 17:19:42 +00004566 return true;
Sean Hunte16da072011-10-10 06:18:57 +00004567
4568 CXXMethodDecl *FieldMember = SMOR->getMethod();
4569 if (IsConstructor) {
4570 CXXConstructorDecl *FieldCtor = cast<CXXConstructorDecl>(FieldMember);
4571 if (CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getAccess(),
4572 PDiag()) != AR_accessible)
4573 return true;
Sean Hunt769bb2d2011-10-11 06:43:29 +00004574
4575 // For a move operation, the corresponding operation must actually
4576 // be a move operation (and not a copy selected by overload
4577 // resolution) unless we are working on a trivially copyable class.
4578 if (IsMove && !FieldCtor->isMoveConstructor() &&
4579 !FieldRecord->isTriviallyCopyable())
4580 return true;
Sean Hunte16da072011-10-10 06:18:57 +00004581 }
4582
4583 // We need the corresponding member of a union to be trivial so that
4584 // we can safely copy them all simultaneously.
4585 // FIXME: Note that performing the check here (where we rely on the lack
4586 // of an in-class initializer) is technically ill-formed. However, this
4587 // seems most obviously to be a bug in the standard.
4588 if (IsUnion && !FieldMember->isTrivial())
Richard Smith7a614d82011-06-11 17:19:42 +00004589 return true;
4590 }
Sean Hunte16da072011-10-10 06:18:57 +00004591 } else if (CSM == CXXDefaultConstructor && !IsUnion &&
4592 FieldType.isConstQualified() && !FI->hasInClassInitializer()) {
4593 // We can't initialize a const member of non-class type to any value.
Sean Hunte3406822011-05-20 21:43:47 +00004594 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004595 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004596 }
4597
Sean Hunte16da072011-10-10 06:18:57 +00004598 // We can't have all const members in a union when default-constructing,
4599 // or else they're all nonsensical garbage values that can't be changed.
4600 if (CSM == CXXDefaultConstructor && IsUnion && AllConst)
Sean Huntcdee3fe2011-05-11 22:34:38 +00004601 return true;
4602
4603 return false;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004604}
4605
Sean Hunt7f410192011-05-14 05:23:24 +00004606bool Sema::ShouldDeleteCopyAssignmentOperator(CXXMethodDecl *MD) {
4607 CXXRecordDecl *RD = MD->getParent();
4608 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaracdb80762011-07-11 08:52:40 +00004609 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Sean Hunt7f410192011-05-14 05:23:24 +00004610 return false;
4611
Douglas Gregor215e4e12012-02-12 17:34:23 +00004612 // C++11 [expr.lambda.prim]p19:
4613 // The closure type associated with a lambda-expression has a
4614 // [...] deleted copy assignment operator.
4615 if (RD->isLambda())
4616 return true;
4617
Sean Hunt71a682f2011-05-18 03:41:58 +00004618 SourceLocation Loc = MD->getLocation();
4619
Sean Hunt7f410192011-05-14 05:23:24 +00004620 // Do access control from the constructor
4621 ContextRAII MethodContext(*this, MD);
4622
4623 bool Union = RD->isUnion();
4624
Sean Hunt661c67a2011-06-21 23:42:56 +00004625 unsigned ArgQuals =
4626 MD->getParamDecl(0)->getType()->getPointeeType().isConstQualified() ?
4627 Qualifiers::Const : 0;
Sean Hunt7f410192011-05-14 05:23:24 +00004628
4629 // We do this because we should never actually use an anonymous
4630 // union's constructor.
4631 if (Union && RD->isAnonymousStructOrUnion())
4632 return false;
4633
Sean Hunt7f410192011-05-14 05:23:24 +00004634 // FIXME: We should put some diagnostic logic right into this function.
4635
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004636 // C++0x [class.copy]/20
Sean Hunt7f410192011-05-14 05:23:24 +00004637 // A defaulted [copy] assignment operator for class X is defined as deleted
4638 // if X has:
4639
4640 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4641 BE = RD->bases_end();
4642 BI != BE; ++BI) {
4643 // We'll handle this one later
4644 if (BI->isVirtual())
4645 continue;
4646
4647 QualType BaseType = BI->getType();
4648 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4649 assert(BaseDecl && "base isn't a CXXRecordDecl");
4650
4651 // -- a [direct base class] B that cannot be [copied] because overload
4652 // resolution, as applied to B's [copy] assignment operator, results in
Sean Hunt2b188082011-05-14 05:23:28 +00004653 // an ambiguity or a function that is deleted or inaccessible from the
Sean Hunt7f410192011-05-14 05:23:24 +00004654 // assignment operator
Sean Hunt661c67a2011-06-21 23:42:56 +00004655 CXXMethodDecl *CopyOper = LookupCopyingAssignment(BaseDecl, ArgQuals, false,
4656 0);
4657 if (!CopyOper || CopyOper->isDeleted())
4658 return true;
4659 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Sean Hunt7f410192011-05-14 05:23:24 +00004660 return true;
4661 }
4662
4663 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4664 BE = RD->vbases_end();
4665 BI != BE; ++BI) {
4666 QualType BaseType = BI->getType();
4667 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4668 assert(BaseDecl && "base isn't a CXXRecordDecl");
4669
Sean Hunt7f410192011-05-14 05:23:24 +00004670 // -- a [virtual base class] B that cannot be [copied] because overload
Sean Hunt2b188082011-05-14 05:23:28 +00004671 // resolution, as applied to B's [copy] assignment operator, results in
4672 // an ambiguity or a function that is deleted or inaccessible from the
4673 // assignment operator
Sean Hunt661c67a2011-06-21 23:42:56 +00004674 CXXMethodDecl *CopyOper = LookupCopyingAssignment(BaseDecl, ArgQuals, false,
4675 0);
4676 if (!CopyOper || CopyOper->isDeleted())
4677 return true;
4678 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Sean Hunt7f410192011-05-14 05:23:24 +00004679 return true;
Sean Hunt7f410192011-05-14 05:23:24 +00004680 }
4681
4682 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4683 FE = RD->field_end();
4684 FI != FE; ++FI) {
Douglas Gregord61db332011-10-10 17:22:13 +00004685 if (FI->isUnnamedBitfield())
4686 continue;
4687
Sean Hunt7f410192011-05-14 05:23:24 +00004688 QualType FieldType = Context.getBaseElementType(FI->getType());
4689
4690 // -- a non-static data member of reference type
4691 if (FieldType->isReferenceType())
4692 return true;
4693
4694 // -- a non-static data member of const non-class type (or array thereof)
4695 if (FieldType.isConstQualified() && !FieldType->isRecordType())
4696 return true;
4697
4698 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4699
4700 if (FieldRecord) {
4701 // This is an anonymous union
4702 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4703 // Anonymous unions inside unions do not variant members create
4704 if (!Union) {
4705 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4706 UE = FieldRecord->field_end();
4707 UI != UE; ++UI) {
4708 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4709 CXXRecordDecl *UnionFieldRecord =
4710 UnionFieldType->getAsCXXRecordDecl();
4711
4712 // -- a variant member with a non-trivial [copy] assignment operator
4713 // and X is a union-like class
4714 if (UnionFieldRecord &&
4715 !UnionFieldRecord->hasTrivialCopyAssignment())
4716 return true;
4717 }
4718 }
4719
4720 // Don't try to initalize an anonymous union
4721 continue;
4722 // -- a variant member with a non-trivial [copy] assignment operator
4723 // and X is a union-like class
4724 } else if (Union && !FieldRecord->hasTrivialCopyAssignment()) {
4725 return true;
4726 }
Sean Hunt7f410192011-05-14 05:23:24 +00004727
Sean Hunt661c67a2011-06-21 23:42:56 +00004728 CXXMethodDecl *CopyOper = LookupCopyingAssignment(FieldRecord, ArgQuals,
4729 false, 0);
4730 if (!CopyOper || CopyOper->isDeleted())
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004731 return true;
Sean Hunt661c67a2011-06-21 23:42:56 +00004732 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004733 return true;
4734 }
4735 }
4736
4737 return false;
4738}
4739
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004740bool Sema::ShouldDeleteMoveAssignmentOperator(CXXMethodDecl *MD) {
4741 CXXRecordDecl *RD = MD->getParent();
4742 assert(!RD->isDependentType() && "do deletion after instantiation");
4743 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
4744 return false;
4745
4746 SourceLocation Loc = MD->getLocation();
4747
4748 // Do access control from the constructor
4749 ContextRAII MethodContext(*this, MD);
4750
4751 bool Union = RD->isUnion();
4752
4753 // We do this because we should never actually use an anonymous
4754 // union's constructor.
4755 if (Union && RD->isAnonymousStructOrUnion())
4756 return false;
4757
4758 // C++0x [class.copy]/20
4759 // A defaulted [move] assignment operator for class X is defined as deleted
4760 // if X has:
4761
4762 // -- for the move constructor, [...] any direct or indirect virtual base
4763 // class.
4764 if (RD->getNumVBases() != 0)
4765 return true;
4766
4767 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4768 BE = RD->bases_end();
4769 BI != BE; ++BI) {
4770
4771 QualType BaseType = BI->getType();
4772 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4773 assert(BaseDecl && "base isn't a CXXRecordDecl");
4774
4775 // -- a [direct base class] B that cannot be [moved] because overload
4776 // resolution, as applied to B's [move] assignment operator, results in
4777 // an ambiguity or a function that is deleted or inaccessible from the
4778 // assignment operator
4779 CXXMethodDecl *MoveOper = LookupMovingAssignment(BaseDecl, false, 0);
4780 if (!MoveOper || MoveOper->isDeleted())
4781 return true;
4782 if (CheckDirectMemberAccess(Loc, MoveOper, PDiag()) != AR_accessible)
4783 return true;
4784
4785 // -- for the move assignment operator, a [direct base class] with a type
4786 // that does not have a move assignment operator and is not trivially
4787 // copyable.
4788 if (!MoveOper->isMoveAssignmentOperator() &&
4789 !BaseDecl->isTriviallyCopyable())
4790 return true;
4791 }
4792
4793 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4794 FE = RD->field_end();
4795 FI != FE; ++FI) {
Douglas Gregord61db332011-10-10 17:22:13 +00004796 if (FI->isUnnamedBitfield())
4797 continue;
4798
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004799 QualType FieldType = Context.getBaseElementType(FI->getType());
4800
4801 // -- a non-static data member of reference type
4802 if (FieldType->isReferenceType())
4803 return true;
4804
4805 // -- a non-static data member of const non-class type (or array thereof)
4806 if (FieldType.isConstQualified() && !FieldType->isRecordType())
4807 return true;
4808
4809 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4810
4811 if (FieldRecord) {
4812 // This is an anonymous union
4813 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4814 // Anonymous unions inside unions do not variant members create
4815 if (!Union) {
4816 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4817 UE = FieldRecord->field_end();
4818 UI != UE; ++UI) {
4819 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4820 CXXRecordDecl *UnionFieldRecord =
4821 UnionFieldType->getAsCXXRecordDecl();
4822
4823 // -- a variant member with a non-trivial [move] assignment operator
4824 // and X is a union-like class
4825 if (UnionFieldRecord &&
4826 !UnionFieldRecord->hasTrivialMoveAssignment())
4827 return true;
4828 }
4829 }
4830
4831 // Don't try to initalize an anonymous union
4832 continue;
4833 // -- a variant member with a non-trivial [move] assignment operator
4834 // and X is a union-like class
4835 } else if (Union && !FieldRecord->hasTrivialMoveAssignment()) {
4836 return true;
4837 }
4838
4839 CXXMethodDecl *MoveOper = LookupMovingAssignment(FieldRecord, false, 0);
4840 if (!MoveOper || MoveOper->isDeleted())
4841 return true;
4842 if (CheckDirectMemberAccess(Loc, MoveOper, PDiag()) != AR_accessible)
4843 return true;
4844
4845 // -- for the move assignment operator, a [non-static data member] with a
4846 // type that does not have a move assignment operator and is not
4847 // trivially copyable.
4848 if (!MoveOper->isMoveAssignmentOperator() &&
4849 !FieldRecord->isTriviallyCopyable())
4850 return true;
Sean Hunt2b188082011-05-14 05:23:28 +00004851 }
Sean Hunt7f410192011-05-14 05:23:24 +00004852 }
4853
4854 return false;
4855}
4856
Sean Huntcb45a0f2011-05-12 22:46:25 +00004857bool Sema::ShouldDeleteDestructor(CXXDestructorDecl *DD) {
4858 CXXRecordDecl *RD = DD->getParent();
4859 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaracdb80762011-07-11 08:52:40 +00004860 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Sean Huntcb45a0f2011-05-12 22:46:25 +00004861 return false;
4862
Sean Hunt71a682f2011-05-18 03:41:58 +00004863 SourceLocation Loc = DD->getLocation();
4864
Sean Huntcb45a0f2011-05-12 22:46:25 +00004865 // Do access control from the destructor
4866 ContextRAII CtorContext(*this, DD);
4867
4868 bool Union = RD->isUnion();
4869
Sean Hunt49634cf2011-05-13 06:10:58 +00004870 // We do this because we should never actually use an anonymous
4871 // union's destructor.
4872 if (Union && RD->isAnonymousStructOrUnion())
4873 return false;
4874
Sean Huntcb45a0f2011-05-12 22:46:25 +00004875 // C++0x [class.dtor]p5
4876 // A defaulted destructor for a class X is defined as deleted if:
4877 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4878 BE = RD->bases_end();
4879 BI != BE; ++BI) {
4880 // We'll handle this one later
4881 if (BI->isVirtual())
4882 continue;
4883
4884 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4885 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4886 assert(BaseDtor && "base has no destructor");
4887
4888 // -- any direct or virtual base class has a deleted destructor or
4889 // a destructor that is inaccessible from the defaulted destructor
4890 if (BaseDtor->isDeleted())
4891 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00004892 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Huntcb45a0f2011-05-12 22:46:25 +00004893 AR_accessible)
4894 return true;
4895 }
4896
4897 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4898 BE = RD->vbases_end();
4899 BI != BE; ++BI) {
4900 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4901 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4902 assert(BaseDtor && "base has no destructor");
4903
4904 // -- any direct or virtual base class has a deleted destructor or
4905 // a destructor that is inaccessible from the defaulted destructor
4906 if (BaseDtor->isDeleted())
4907 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00004908 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Huntcb45a0f2011-05-12 22:46:25 +00004909 AR_accessible)
4910 return true;
4911 }
4912
4913 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4914 FE = RD->field_end();
4915 FI != FE; ++FI) {
4916 QualType FieldType = Context.getBaseElementType(FI->getType());
4917 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4918 if (FieldRecord) {
4919 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4920 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4921 UE = FieldRecord->field_end();
4922 UI != UE; ++UI) {
4923 QualType UnionFieldType = Context.getBaseElementType(FI->getType());
4924 CXXRecordDecl *UnionFieldRecord =
4925 UnionFieldType->getAsCXXRecordDecl();
4926
4927 // -- X is a union-like class that has a variant member with a non-
4928 // trivial destructor.
4929 if (UnionFieldRecord && !UnionFieldRecord->hasTrivialDestructor())
4930 return true;
4931 }
4932 // Technically we are supposed to do this next check unconditionally.
4933 // But that makes absolutely no sense.
4934 } else {
4935 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
4936
4937 // -- any of the non-static data members has class type M (or array
4938 // thereof) and M has a deleted destructor or a destructor that is
4939 // inaccessible from the defaulted destructor
4940 if (FieldDtor->isDeleted())
4941 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00004942 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
Sean Huntcb45a0f2011-05-12 22:46:25 +00004943 AR_accessible)
4944 return true;
4945
4946 // -- X is a union-like class that has a variant member with a non-
4947 // trivial destructor.
4948 if (Union && !FieldDtor->isTrivial())
4949 return true;
4950 }
4951 }
4952 }
4953
4954 if (DD->isVirtual()) {
4955 FunctionDecl *OperatorDelete = 0;
4956 DeclarationName Name =
4957 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Sean Hunt71a682f2011-05-18 03:41:58 +00004958 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete,
Sean Huntcb45a0f2011-05-12 22:46:25 +00004959 false))
4960 return true;
4961 }
4962
4963
4964 return false;
4965}
4966
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004967/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramerc54061a2011-03-04 13:12:48 +00004968namespace {
4969 struct FindHiddenVirtualMethodData {
4970 Sema *S;
4971 CXXMethodDecl *Method;
4972 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004973 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramerc54061a2011-03-04 13:12:48 +00004974 };
4975}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004976
4977/// \brief Member lookup function that determines whether a given C++
4978/// method overloads virtual methods in a base class without overriding any,
4979/// to be used with CXXRecordDecl::lookupInBases().
4980static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
4981 CXXBasePath &Path,
4982 void *UserData) {
4983 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
4984
4985 FindHiddenVirtualMethodData &Data
4986 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
4987
4988 DeclarationName Name = Data.Method->getDeclName();
4989 assert(Name.getNameKind() == DeclarationName::Identifier);
4990
4991 bool foundSameNameMethod = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004992 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004993 for (Path.Decls = BaseRecord->lookup(Name);
4994 Path.Decls.first != Path.Decls.second;
4995 ++Path.Decls.first) {
4996 NamedDecl *D = *Path.Decls.first;
4997 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00004998 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004999 foundSameNameMethod = true;
5000 // Interested only in hidden virtual methods.
5001 if (!MD->isVirtual())
5002 continue;
5003 // If the method we are checking overrides a method from its base
5004 // don't warn about the other overloaded methods.
5005 if (!Data.S->IsOverload(Data.Method, MD, false))
5006 return true;
5007 // Collect the overload only if its hidden.
5008 if (!Data.OverridenAndUsingBaseMethods.count(MD))
5009 overloadedMethods.push_back(MD);
5010 }
5011 }
5012
5013 if (foundSameNameMethod)
5014 Data.OverloadedMethods.append(overloadedMethods.begin(),
5015 overloadedMethods.end());
5016 return foundSameNameMethod;
5017}
5018
5019/// \brief See if a method overloads virtual methods in a base class without
5020/// overriding any.
5021void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
5022 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
David Blaikied6471f72011-09-25 23:23:43 +00005023 MD->getLocation()) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005024 return;
5025 if (MD->getDeclName().getNameKind() != DeclarationName::Identifier)
5026 return;
5027
5028 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
5029 /*bool RecordPaths=*/false,
5030 /*bool DetectVirtual=*/false);
5031 FindHiddenVirtualMethodData Data;
5032 Data.Method = MD;
5033 Data.S = this;
5034
5035 // Keep the base methods that were overriden or introduced in the subclass
5036 // by 'using' in a set. A base method not in this set is hidden.
5037 for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
5038 res.first != res.second; ++res.first) {
5039 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first))
5040 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5041 E = MD->end_overridden_methods();
5042 I != E; ++I)
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00005043 Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005044 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
5045 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl()))
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00005046 Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005047 }
5048
5049 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
5050 !Data.OverloadedMethods.empty()) {
5051 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
5052 << MD << (Data.OverloadedMethods.size() > 1);
5053
5054 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
5055 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
5056 Diag(overloadedMD->getLocation(),
5057 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
5058 }
5059 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005060}
5061
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005062void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00005063 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005064 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00005065 SourceLocation RBrac,
5066 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005067 if (!TagDecl)
5068 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005069
Douglas Gregor42af25f2009-05-11 19:58:34 +00005070 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005071
David Blaikie77b6de02011-09-22 02:58:26 +00005072 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCalld226f652010-08-21 09:40:31 +00005073 // strict aliasing violation!
5074 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie77b6de02011-09-22 02:58:26 +00005075 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00005076
Douglas Gregor23c94db2010-07-02 17:43:08 +00005077 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00005078 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005079}
5080
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005081/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5082/// special functions, such as the default constructor, copy
5083/// constructor, or destructor, to the given C++ class (C++
5084/// [special]p1). This routine can only be executed just before the
5085/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00005086void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00005087 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00005088 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005089
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005090 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregor22584312010-07-02 23:41:54 +00005091 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005092
Richard Smithb701d3d2011-12-24 21:56:24 +00005093 if (getLangOptions().CPlusPlus0x && ClassDecl->needsImplicitMoveConstructor())
5094 ++ASTContext::NumImplicitMoveConstructors;
5095
Douglas Gregora376d102010-07-02 21:50:04 +00005096 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
5097 ++ASTContext::NumImplicitCopyAssignmentOperators;
5098
5099 // If we have a dynamic class, then the copy assignment operator may be
5100 // virtual, so we have to declare it immediately. This ensures that, e.g.,
5101 // it shows up in the right place in the vtable and that we diagnose
5102 // problems with the implicit exception specification.
5103 if (ClassDecl->isDynamicClass())
5104 DeclareImplicitCopyAssignment(ClassDecl);
5105 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00005106
Richard Smithb701d3d2011-12-24 21:56:24 +00005107 if (getLangOptions().CPlusPlus0x && ClassDecl->needsImplicitMoveAssignment()){
5108 ++ASTContext::NumImplicitMoveAssignmentOperators;
5109
5110 // Likewise for the move assignment operator.
5111 if (ClassDecl->isDynamicClass())
5112 DeclareImplicitMoveAssignment(ClassDecl);
5113 }
5114
Douglas Gregor4923aa22010-07-02 20:37:36 +00005115 if (!ClassDecl->hasUserDeclaredDestructor()) {
5116 ++ASTContext::NumImplicitDestructors;
5117
5118 // If we have a dynamic class, then the destructor may be virtual, so we
5119 // have to declare the destructor immediately. This ensures that, e.g., it
5120 // shows up in the right place in the vtable and that we diagnose problems
5121 // with the implicit exception specification.
5122 if (ClassDecl->isDynamicClass())
5123 DeclareImplicitDestructor(ClassDecl);
5124 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005125}
5126
Francois Pichet8387e2a2011-04-22 22:18:13 +00005127void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
5128 if (!D)
5129 return;
5130
5131 int NumParamList = D->getNumTemplateParameterLists();
5132 for (int i = 0; i < NumParamList; i++) {
5133 TemplateParameterList* Params = D->getTemplateParameterList(i);
5134 for (TemplateParameterList::iterator Param = Params->begin(),
5135 ParamEnd = Params->end();
5136 Param != ParamEnd; ++Param) {
5137 NamedDecl *Named = cast<NamedDecl>(*Param);
5138 if (Named->getDeclName()) {
5139 S->AddDecl(Named);
5140 IdResolver.AddDecl(Named);
5141 }
5142 }
5143 }
5144}
5145
John McCalld226f652010-08-21 09:40:31 +00005146void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00005147 if (!D)
5148 return;
5149
5150 TemplateParameterList *Params = 0;
5151 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
5152 Params = Template->getTemplateParameters();
5153 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
5154 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
5155 Params = PartialSpec->getTemplateParameters();
5156 else
Douglas Gregor6569d682009-05-27 23:11:45 +00005157 return;
5158
Douglas Gregor6569d682009-05-27 23:11:45 +00005159 for (TemplateParameterList::iterator Param = Params->begin(),
5160 ParamEnd = Params->end();
5161 Param != ParamEnd; ++Param) {
5162 NamedDecl *Named = cast<NamedDecl>(*Param);
5163 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00005164 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00005165 IdResolver.AddDecl(Named);
5166 }
5167 }
5168}
5169
John McCalld226f652010-08-21 09:40:31 +00005170void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005171 if (!RecordD) return;
5172 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00005173 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00005174 PushDeclContext(S, Record);
5175}
5176
John McCalld226f652010-08-21 09:40:31 +00005177void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005178 if (!RecordD) return;
5179 PopDeclContext();
5180}
5181
Douglas Gregor72b505b2008-12-16 21:30:33 +00005182/// ActOnStartDelayedCXXMethodDeclaration - We have completed
5183/// parsing a top-level (non-nested) C++ class, and we are now
5184/// parsing those parts of the given Method declaration that could
5185/// not be parsed earlier (C++ [class.mem]p2), such as default
5186/// arguments. This action should enter the scope of the given
5187/// Method declaration as if we had just parsed the qualified method
5188/// name. However, it should not bring the parameters into scope;
5189/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00005190void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005191}
5192
5193/// ActOnDelayedCXXMethodParameter - We've already started a delayed
5194/// C++ method declaration. We're (re-)introducing the given
5195/// function parameter into scope for use in parsing later parts of
5196/// the method declaration. For example, we could see an
5197/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00005198void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005199 if (!ParamD)
5200 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005201
John McCalld226f652010-08-21 09:40:31 +00005202 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00005203
5204 // If this parameter has an unparsed default argument, clear it out
5205 // to make way for the parsed default argument.
5206 if (Param->hasUnparsedDefaultArg())
5207 Param->setDefaultArg(0);
5208
John McCalld226f652010-08-21 09:40:31 +00005209 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005210 if (Param->getDeclName())
5211 IdResolver.AddDecl(Param);
5212}
5213
5214/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
5215/// processing the delayed method declaration for Method. The method
5216/// declaration is now considered finished. There may be a separate
5217/// ActOnStartOfFunctionDef action later (not necessarily
5218/// immediately!) for this method, if it was also defined inside the
5219/// class body.
John McCalld226f652010-08-21 09:40:31 +00005220void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005221 if (!MethodD)
5222 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005223
Douglas Gregorefd5bda2009-08-24 11:57:43 +00005224 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00005225
John McCalld226f652010-08-21 09:40:31 +00005226 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005227
5228 // Now that we have our default arguments, check the constructor
5229 // again. It could produce additional diagnostics or affect whether
5230 // the class has implicitly-declared destructors, among other
5231 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00005232 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
5233 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005234
5235 // Check the default arguments, which we may have added.
5236 if (!Method->isInvalidDecl())
5237 CheckCXXDefaultArguments(Method);
5238}
5239
Douglas Gregor42a552f2008-11-05 20:51:48 +00005240/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00005241/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00005242/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005243/// emit diagnostics and set the invalid bit to true. In any case, the type
5244/// will be updated to reflect a well-formed type for the constructor and
5245/// returned.
5246QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005247 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005248 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005249
5250 // C++ [class.ctor]p3:
5251 // A constructor shall not be virtual (10.3) or static (9.4). A
5252 // constructor can be invoked for a const, volatile or const
5253 // volatile object. A constructor shall not be declared const,
5254 // volatile, or const volatile (9.3.2).
5255 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00005256 if (!D.isInvalidType())
5257 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5258 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
5259 << SourceRange(D.getIdentifierLoc());
5260 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005261 }
John McCalld931b082010-08-26 03:08:43 +00005262 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005263 if (!D.isInvalidType())
5264 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5265 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5266 << SourceRange(D.getIdentifierLoc());
5267 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005268 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005269 }
Mike Stump1eb44332009-09-09 15:08:12 +00005270
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005271 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005272 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00005273 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005274 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5275 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005276 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005277 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5278 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005279 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005280 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5281 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00005282 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005283 }
Mike Stump1eb44332009-09-09 15:08:12 +00005284
Douglas Gregorc938c162011-01-26 05:01:58 +00005285 // C++0x [class.ctor]p4:
5286 // A constructor shall not be declared with a ref-qualifier.
5287 if (FTI.hasRefQualifier()) {
5288 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
5289 << FTI.RefQualifierIsLValueRef
5290 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5291 D.setInvalidType();
5292 }
5293
Douglas Gregor42a552f2008-11-05 20:51:48 +00005294 // Rebuild the function type "R" without any type qualifiers (in
5295 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00005296 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00005297 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005298 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
5299 return R;
5300
5301 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5302 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005303 EPI.RefQualifier = RQ_None;
5304
Chris Lattner65401802009-04-25 08:28:21 +00005305 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00005306 Proto->getNumArgs(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005307}
5308
Douglas Gregor72b505b2008-12-16 21:30:33 +00005309/// CheckConstructor - Checks a fully-formed constructor for
5310/// well-formedness, issuing any diagnostics required. Returns true if
5311/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00005312void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00005313 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00005314 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
5315 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00005316 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005317
5318 // C++ [class.copy]p3:
5319 // A declaration of a constructor for a class X is ill-formed if
5320 // its first parameter is of type (optionally cv-qualified) X and
5321 // either there are no other parameters or else all other
5322 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00005323 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00005324 ((Constructor->getNumParams() == 1) ||
5325 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00005326 Constructor->getParamDecl(1)->hasDefaultArg())) &&
5327 Constructor->getTemplateSpecializationKind()
5328 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005329 QualType ParamType = Constructor->getParamDecl(0)->getType();
5330 QualType ClassTy = Context.getTagDeclType(ClassDecl);
5331 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00005332 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005333 const char *ConstRef
5334 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
5335 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00005336 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005337 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00005338
5339 // FIXME: Rather that making the constructor invalid, we should endeavor
5340 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00005341 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005342 }
5343 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00005344}
5345
John McCall15442822010-08-04 01:04:25 +00005346/// CheckDestructor - Checks a fully-formed destructor definition for
5347/// well-formedness, issuing any diagnostics required. Returns true
5348/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005349bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00005350 CXXRecordDecl *RD = Destructor->getParent();
5351
5352 if (Destructor->isVirtual()) {
5353 SourceLocation Loc;
5354
5355 if (!Destructor->isImplicit())
5356 Loc = Destructor->getLocation();
5357 else
5358 Loc = RD->getLocation();
5359
5360 // If we have a virtual destructor, look up the deallocation function
5361 FunctionDecl *OperatorDelete = 0;
5362 DeclarationName Name =
5363 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005364 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00005365 return true;
John McCall5efd91a2010-07-03 18:33:00 +00005366
Eli Friedman5f2987c2012-02-02 03:46:19 +00005367 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00005368
5369 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00005370 }
Anders Carlsson37909802009-11-30 21:24:50 +00005371
5372 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00005373}
5374
Mike Stump1eb44332009-09-09 15:08:12 +00005375static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005376FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
5377 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5378 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00005379 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005380}
5381
Douglas Gregor42a552f2008-11-05 20:51:48 +00005382/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
5383/// the well-formednes of the destructor declarator @p D with type @p
5384/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005385/// emit diagnostics and set the declarator to invalid. Even if this happens,
5386/// will be updated to reflect a well-formed type for the destructor and
5387/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00005388QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005389 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005390 // C++ [class.dtor]p1:
5391 // [...] A typedef-name that names a class is a class-name
5392 // (7.1.3); however, a typedef-name that names a class shall not
5393 // be used as the identifier in the declarator for a destructor
5394 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005395 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smith162e1c12011-04-15 14:24:37 +00005396 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner65401802009-04-25 08:28:21 +00005397 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smith162e1c12011-04-15 14:24:37 +00005398 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00005399 else if (const TemplateSpecializationType *TST =
5400 DeclaratorType->getAs<TemplateSpecializationType>())
5401 if (TST->isTypeAlias())
5402 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5403 << DeclaratorType << 1;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005404
5405 // C++ [class.dtor]p2:
5406 // A destructor is used to destroy objects of its class type. A
5407 // destructor takes no parameters, and no return type can be
5408 // specified for it (not even void). The address of a destructor
5409 // shall not be taken. A destructor shall not be static. A
5410 // destructor can be invoked for a const, volatile or const
5411 // volatile object. A destructor shall not be declared const,
5412 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00005413 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005414 if (!D.isInvalidType())
5415 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
5416 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00005417 << SourceRange(D.getIdentifierLoc())
5418 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5419
John McCalld931b082010-08-26 03:08:43 +00005420 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005421 }
Chris Lattner65401802009-04-25 08:28:21 +00005422 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005423 // Destructors don't have return types, but the parser will
5424 // happily parse something like:
5425 //
5426 // class X {
5427 // float ~X();
5428 // };
5429 //
5430 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005431 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
5432 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5433 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00005434 }
Mike Stump1eb44332009-09-09 15:08:12 +00005435
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005436 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005437 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00005438 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005439 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5440 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005441 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005442 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5443 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005444 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005445 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5446 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00005447 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005448 }
5449
Douglas Gregorc938c162011-01-26 05:01:58 +00005450 // C++0x [class.dtor]p2:
5451 // A destructor shall not be declared with a ref-qualifier.
5452 if (FTI.hasRefQualifier()) {
5453 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
5454 << FTI.RefQualifierIsLValueRef
5455 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5456 D.setInvalidType();
5457 }
5458
Douglas Gregor42a552f2008-11-05 20:51:48 +00005459 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005460 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005461 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
5462
5463 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00005464 FTI.freeArgs();
5465 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005466 }
5467
Mike Stump1eb44332009-09-09 15:08:12 +00005468 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00005469 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005470 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00005471 D.setInvalidType();
5472 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00005473
5474 // Rebuild the function type "R" without any type qualifiers or
5475 // parameters (in case any of the errors above fired) and with
5476 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00005477 // types.
John McCalle23cf432010-12-14 08:05:40 +00005478 if (!D.isInvalidType())
5479 return R;
5480
Douglas Gregord92ec472010-07-01 05:10:53 +00005481 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005482 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5483 EPI.Variadic = false;
5484 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005485 EPI.RefQualifier = RQ_None;
John McCalle23cf432010-12-14 08:05:40 +00005486 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005487}
5488
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005489/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
5490/// well-formednes of the conversion function declarator @p D with
5491/// type @p R. If there are any errors in the declarator, this routine
5492/// will emit diagnostics and return true. Otherwise, it will return
5493/// false. Either way, the type @p R will be updated to reflect a
5494/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00005495void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00005496 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005497 // C++ [class.conv.fct]p1:
5498 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00005499 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00005500 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00005501 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00005502 if (!D.isInvalidType())
5503 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
5504 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5505 << SourceRange(D.getIdentifierLoc());
5506 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005507 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005508 }
John McCalla3f81372010-04-13 00:04:31 +00005509
5510 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
5511
Chris Lattner6e475012009-04-25 08:35:12 +00005512 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005513 // Conversion functions don't have return types, but the parser will
5514 // happily parse something like:
5515 //
5516 // class X {
5517 // float operator bool();
5518 // };
5519 //
5520 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005521 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
5522 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5523 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00005524 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005525 }
5526
John McCalla3f81372010-04-13 00:04:31 +00005527 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5528
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005529 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00005530 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005531 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
5532
5533 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005534 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00005535 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00005536 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005537 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00005538 D.setInvalidType();
5539 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005540
John McCalla3f81372010-04-13 00:04:31 +00005541 // Diagnose "&operator bool()" and other such nonsense. This
5542 // is actually a gcc extension which we don't support.
5543 if (Proto->getResultType() != ConvType) {
5544 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
5545 << Proto->getResultType();
5546 D.setInvalidType();
5547 ConvType = Proto->getResultType();
5548 }
5549
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005550 // C++ [class.conv.fct]p4:
5551 // The conversion-type-id shall not represent a function type nor
5552 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005553 if (ConvType->isArrayType()) {
5554 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
5555 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005556 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005557 } else if (ConvType->isFunctionType()) {
5558 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
5559 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005560 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005561 }
5562
5563 // Rebuild the function type "R" without any parameters (in case any
5564 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00005565 // return type.
John McCalle23cf432010-12-14 08:05:40 +00005566 if (D.isInvalidType())
5567 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005568
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005569 // C++0x explicit conversion operators.
Richard Smithebaf0e62011-10-18 20:49:44 +00005570 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump1eb44332009-09-09 15:08:12 +00005571 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smithebaf0e62011-10-18 20:49:44 +00005572 getLangOptions().CPlusPlus0x ?
5573 diag::warn_cxx98_compat_explicit_conversion_functions :
5574 diag::ext_explicit_conversion_functions)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005575 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005576}
5577
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005578/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
5579/// the declaration of the given C++ conversion function. This routine
5580/// is responsible for recording the conversion function in the C++
5581/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00005582Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005583 assert(Conversion && "Expected to receive a conversion function declaration");
5584
Douglas Gregor9d350972008-12-12 08:25:50 +00005585 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005586
5587 // Make sure we aren't redeclaring the conversion function.
5588 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005589
5590 // C++ [class.conv.fct]p1:
5591 // [...] A conversion function is never used to convert a
5592 // (possibly cv-qualified) object to the (possibly cv-qualified)
5593 // same object type (or a reference to it), to a (possibly
5594 // cv-qualified) base class of that type (or a reference to it),
5595 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00005596 // FIXME: Suppress this warning if the conversion function ends up being a
5597 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00005598 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005599 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00005600 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005601 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005602 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
5603 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00005604 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005605 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005606 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
5607 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00005608 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005609 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005610 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00005611 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005612 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005613 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00005614 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005615 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005616 }
5617
Douglas Gregore80622f2010-09-29 04:25:11 +00005618 if (FunctionTemplateDecl *ConversionTemplate
5619 = Conversion->getDescribedFunctionTemplate())
5620 return ConversionTemplate;
5621
John McCalld226f652010-08-21 09:40:31 +00005622 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005623}
5624
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005625//===----------------------------------------------------------------------===//
5626// Namespace Handling
5627//===----------------------------------------------------------------------===//
5628
John McCallea318642010-08-26 09:15:37 +00005629
5630
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005631/// ActOnStartNamespaceDef - This is called at the start of a namespace
5632/// definition.
John McCalld226f652010-08-21 09:40:31 +00005633Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00005634 SourceLocation InlineLoc,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005635 SourceLocation NamespaceLoc,
John McCallea318642010-08-26 09:15:37 +00005636 SourceLocation IdentLoc,
5637 IdentifierInfo *II,
5638 SourceLocation LBrace,
5639 AttributeList *AttrList) {
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005640 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
5641 // For anonymous namespace, take the location of the left brace.
5642 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005643 bool IsInline = InlineLoc.isValid();
Douglas Gregor67310742012-01-10 22:14:10 +00005644 bool IsInvalid = false;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005645 bool IsStd = false;
5646 bool AddToKnown = false;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005647 Scope *DeclRegionScope = NamespcScope->getParent();
5648
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005649 NamespaceDecl *PrevNS = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005650 if (II) {
5651 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00005652 // The identifier in an original-namespace-definition shall not
5653 // have been previously defined in the declarative region in
5654 // which the original-namespace-definition appears. The
5655 // identifier in an original-namespace-definition is the name of
5656 // the namespace. Subsequently in that declarative region, it is
5657 // treated as an original-namespace-name.
5658 //
5659 // Since namespace names are unique in their scope, and we don't
Douglas Gregor010157f2011-05-06 23:28:47 +00005660 // look through using directives, just look for any ordinary names.
5661
5662 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005663 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
5664 Decl::IDNS_Namespace;
Douglas Gregor010157f2011-05-06 23:28:47 +00005665 NamedDecl *PrevDecl = 0;
5666 for (DeclContext::lookup_result R
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005667 = CurContext->getRedeclContext()->lookup(II);
Douglas Gregor010157f2011-05-06 23:28:47 +00005668 R.first != R.second; ++R.first) {
5669 if ((*R.first)->getIdentifierNamespace() & IDNS) {
5670 PrevDecl = *R.first;
5671 break;
5672 }
5673 }
5674
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005675 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
5676
5677 if (PrevNS) {
Douglas Gregor44b43212008-12-11 16:49:14 +00005678 // This is an extended namespace definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005679 if (IsInline != PrevNS->isInline()) {
Sebastian Redl4e4d5702010-08-31 00:36:36 +00005680 // inline-ness must match
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005681 if (PrevNS->isInline()) {
Douglas Gregorb7ec9062011-05-20 15:48:31 +00005682 // The user probably just forgot the 'inline', so suggest that it
5683 // be added back.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005684 Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
Douglas Gregorb7ec9062011-05-20 15:48:31 +00005685 << FixItHint::CreateInsertion(NamespaceLoc, "inline ");
5686 } else {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005687 Diag(Loc, diag::err_inline_namespace_mismatch)
5688 << IsInline;
Douglas Gregorb7ec9062011-05-20 15:48:31 +00005689 }
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005690 Diag(PrevNS->getLocation(), diag::note_previous_definition);
5691
5692 IsInline = PrevNS->isInline();
5693 }
Douglas Gregor44b43212008-12-11 16:49:14 +00005694 } else if (PrevDecl) {
5695 // This is an invalid name redefinition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005696 Diag(Loc, diag::err_redefinition_different_kind)
5697 << II;
Douglas Gregor44b43212008-12-11 16:49:14 +00005698 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00005699 IsInvalid = true;
Douglas Gregor44b43212008-12-11 16:49:14 +00005700 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005701 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00005702 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00005703 // This is the first "real" definition of the namespace "std", so update
5704 // our cache of the "std" namespace to point at this definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005705 PrevNS = getStdNamespace();
5706 IsStd = true;
5707 AddToKnown = !IsInline;
5708 } else {
5709 // We've seen this namespace for the first time.
5710 AddToKnown = !IsInline;
Mike Stump1eb44332009-09-09 15:08:12 +00005711 }
Douglas Gregor44b43212008-12-11 16:49:14 +00005712 } else {
John McCall9aeed322009-10-01 00:25:31 +00005713 // Anonymous namespaces.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005714
5715 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl7a126a42010-08-31 00:36:30 +00005716 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00005717 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005718 PrevNS = TU->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00005719 } else {
5720 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005721 PrevNS = ND->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00005722 }
5723
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005724 if (PrevNS && IsInline != PrevNS->isInline()) {
5725 // inline-ness must match
5726 Diag(Loc, diag::err_inline_namespace_mismatch)
5727 << IsInline;
5728 Diag(PrevNS->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00005729
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005730 // Recover by ignoring the new namespace's inline status.
5731 IsInline = PrevNS->isInline();
5732 }
5733 }
5734
5735 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
5736 StartLoc, Loc, II, PrevNS);
Douglas Gregor67310742012-01-10 22:14:10 +00005737 if (IsInvalid)
5738 Namespc->setInvalidDecl();
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005739
5740 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00005741
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005742 // FIXME: Should we be merging attributes?
5743 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00005744 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005745
5746 if (IsStd)
5747 StdNamespace = Namespc;
5748 if (AddToKnown)
5749 KnownNamespaces[Namespc] = false;
5750
5751 if (II) {
5752 PushOnScopeChains(Namespc, DeclRegionScope);
5753 } else {
5754 // Link the anonymous namespace into its parent.
5755 DeclContext *Parent = CurContext->getRedeclContext();
5756 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
5757 TU->setAnonymousNamespace(Namespc);
5758 } else {
5759 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall5fdd7642009-12-16 02:06:49 +00005760 }
John McCall9aeed322009-10-01 00:25:31 +00005761
Douglas Gregora4181472010-03-24 00:46:35 +00005762 CurContext->addDecl(Namespc);
5763
John McCall9aeed322009-10-01 00:25:31 +00005764 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
5765 // behaves as if it were replaced by
5766 // namespace unique { /* empty body */ }
5767 // using namespace unique;
5768 // namespace unique { namespace-body }
5769 // where all occurrences of 'unique' in a translation unit are
5770 // replaced by the same identifier and this identifier differs
5771 // from all other identifiers in the entire program.
5772
5773 // We just create the namespace with an empty name and then add an
5774 // implicit using declaration, just like the standard suggests.
5775 //
5776 // CodeGen enforces the "universally unique" aspect by giving all
5777 // declarations semantically contained within an anonymous
5778 // namespace internal linkage.
5779
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005780 if (!PrevNS) {
John McCall5fdd7642009-12-16 02:06:49 +00005781 UsingDirectiveDecl* UD
5782 = UsingDirectiveDecl::Create(Context, CurContext,
5783 /* 'using' */ LBrace,
5784 /* 'namespace' */ SourceLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00005785 /* qualifier */ NestedNameSpecifierLoc(),
John McCall5fdd7642009-12-16 02:06:49 +00005786 /* identifier */ SourceLocation(),
5787 Namespc,
5788 /* Ancestor */ CurContext);
5789 UD->setImplicit();
5790 CurContext->addDecl(UD);
5791 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005792 }
5793
5794 // Although we could have an invalid decl (i.e. the namespace name is a
5795 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00005796 // FIXME: We should be able to push Namespc here, so that the each DeclContext
5797 // for the namespace has the declarations that showed up in that particular
5798 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00005799 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00005800 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005801}
5802
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005803/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
5804/// is a namespace alias, returns the namespace it points to.
5805static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
5806 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
5807 return AD->getNamespace();
5808 return dyn_cast_or_null<NamespaceDecl>(D);
5809}
5810
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005811/// ActOnFinishNamespaceDef - This callback is called after a namespace is
5812/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00005813void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005814 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
5815 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005816 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005817 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00005818 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00005819 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005820}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005821
John McCall384aff82010-08-25 07:42:41 +00005822CXXRecordDecl *Sema::getStdBadAlloc() const {
5823 return cast_or_null<CXXRecordDecl>(
5824 StdBadAlloc.get(Context.getExternalSource()));
5825}
5826
5827NamespaceDecl *Sema::getStdNamespace() const {
5828 return cast_or_null<NamespaceDecl>(
5829 StdNamespace.get(Context.getExternalSource()));
5830}
5831
Douglas Gregor66992202010-06-29 17:53:46 +00005832/// \brief Retrieve the special "std" namespace, which may require us to
5833/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00005834NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00005835 if (!StdNamespace) {
5836 // The "std" namespace has not yet been defined, so build one implicitly.
5837 StdNamespace = NamespaceDecl::Create(Context,
5838 Context.getTranslationUnitDecl(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005839 /*Inline=*/false,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005840 SourceLocation(), SourceLocation(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005841 &PP.getIdentifierTable().get("std"),
5842 /*PrevDecl=*/0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00005843 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00005844 }
5845
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00005846 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00005847}
5848
Sebastian Redl395e04d2012-01-17 22:49:33 +00005849bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
5850 assert(getLangOptions().CPlusPlus &&
5851 "Looking for std::initializer_list outside of C++.");
5852
5853 // We're looking for implicit instantiations of
5854 // template <typename E> class std::initializer_list.
5855
5856 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
5857 return false;
5858
Sebastian Redl84760e32012-01-17 22:49:58 +00005859 ClassTemplateDecl *Template = 0;
5860 const TemplateArgument *Arguments = 0;
Sebastian Redl395e04d2012-01-17 22:49:33 +00005861
Sebastian Redl84760e32012-01-17 22:49:58 +00005862 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl395e04d2012-01-17 22:49:33 +00005863
Sebastian Redl84760e32012-01-17 22:49:58 +00005864 ClassTemplateSpecializationDecl *Specialization =
5865 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
5866 if (!Specialization)
5867 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00005868
Sebastian Redl84760e32012-01-17 22:49:58 +00005869 Template = Specialization->getSpecializedTemplate();
5870 Arguments = Specialization->getTemplateArgs().data();
5871 } else if (const TemplateSpecializationType *TST =
5872 Ty->getAs<TemplateSpecializationType>()) {
5873 Template = dyn_cast_or_null<ClassTemplateDecl>(
5874 TST->getTemplateName().getAsTemplateDecl());
5875 Arguments = TST->getArgs();
5876 }
5877 if (!Template)
5878 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00005879
5880 if (!StdInitializerList) {
5881 // Haven't recognized std::initializer_list yet, maybe this is it.
5882 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
5883 if (TemplateClass->getIdentifier() !=
5884 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redlb832f6d2012-01-23 22:09:39 +00005885 !getStdNamespace()->InEnclosingNamespaceSetOf(
5886 TemplateClass->getDeclContext()))
Sebastian Redl395e04d2012-01-17 22:49:33 +00005887 return false;
5888 // This is a template called std::initializer_list, but is it the right
5889 // template?
5890 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00005891 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl395e04d2012-01-17 22:49:33 +00005892 return false;
5893 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
5894 return false;
5895
5896 // It's the right template.
5897 StdInitializerList = Template;
5898 }
5899
5900 if (Template != StdInitializerList)
5901 return false;
5902
5903 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl84760e32012-01-17 22:49:58 +00005904 if (Element)
5905 *Element = Arguments[0].getAsType();
Sebastian Redl395e04d2012-01-17 22:49:33 +00005906 return true;
5907}
5908
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00005909static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
5910 NamespaceDecl *Std = S.getStdNamespace();
5911 if (!Std) {
5912 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
5913 return 0;
5914 }
5915
5916 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
5917 Loc, Sema::LookupOrdinaryName);
5918 if (!S.LookupQualifiedName(Result, Std)) {
5919 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
5920 return 0;
5921 }
5922 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
5923 if (!Template) {
5924 Result.suppressDiagnostics();
5925 // We found something weird. Complain about the first thing we found.
5926 NamedDecl *Found = *Result.begin();
5927 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
5928 return 0;
5929 }
5930
5931 // We found some template called std::initializer_list. Now verify that it's
5932 // correct.
5933 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00005934 if (Params->getMinRequiredArguments() != 1 ||
5935 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00005936 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
5937 return 0;
5938 }
5939
5940 return Template;
5941}
5942
5943QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
5944 if (!StdInitializerList) {
5945 StdInitializerList = LookupStdInitializerList(*this, Loc);
5946 if (!StdInitializerList)
5947 return QualType();
5948 }
5949
5950 TemplateArgumentListInfo Args(Loc, Loc);
5951 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
5952 Context.getTrivialTypeSourceInfo(Element,
5953 Loc)));
5954 return Context.getCanonicalType(
5955 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
5956}
5957
Sebastian Redl98d36062012-01-17 22:50:14 +00005958bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
5959 // C++ [dcl.init.list]p2:
5960 // A constructor is an initializer-list constructor if its first parameter
5961 // is of type std::initializer_list<E> or reference to possibly cv-qualified
5962 // std::initializer_list<E> for some type E, and either there are no other
5963 // parameters or else all other parameters have default arguments.
5964 if (Ctor->getNumParams() < 1 ||
5965 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
5966 return false;
5967
5968 QualType ArgType = Ctor->getParamDecl(0)->getType();
5969 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
5970 ArgType = RT->getPointeeType().getUnqualifiedType();
5971
5972 return isStdInitializerList(ArgType, 0);
5973}
5974
Douglas Gregor9172aa62011-03-26 22:25:30 +00005975/// \brief Determine whether a using statement is in a context where it will be
5976/// apply in all contexts.
5977static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
5978 switch (CurContext->getDeclKind()) {
5979 case Decl::TranslationUnit:
5980 return true;
5981 case Decl::LinkageSpec:
5982 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
5983 default:
5984 return false;
5985 }
5986}
5987
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005988namespace {
5989
5990// Callback to only accept typo corrections that are namespaces.
5991class NamespaceValidatorCCC : public CorrectionCandidateCallback {
5992 public:
5993 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
5994 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
5995 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
5996 }
5997 return false;
5998 }
5999};
6000
6001}
6002
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006003static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
6004 CXXScopeSpec &SS,
6005 SourceLocation IdentLoc,
6006 IdentifierInfo *Ident) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006007 NamespaceValidatorCCC Validator;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006008 R.clear();
6009 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006010 R.getLookupKind(), Sc, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00006011 Validator)) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006012 std::string CorrectedStr(Corrected.getAsString(S.getLangOptions()));
6013 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOptions()));
6014 if (DeclContext *DC = S.computeDeclContext(SS, false))
6015 S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
6016 << Ident << DC << CorrectedQuotedStr << SS.getRange()
6017 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
6018 else
6019 S.Diag(IdentLoc, diag::err_using_directive_suggest)
6020 << Ident << CorrectedQuotedStr
6021 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006022
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006023 S.Diag(Corrected.getCorrectionDecl()->getLocation(),
6024 diag::note_namespace_defined_here) << CorrectedQuotedStr;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006025
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006026 Ident = Corrected.getCorrectionAsIdentifierInfo();
6027 R.addDecl(Corrected.getCorrectionDecl());
6028 return true;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006029 }
6030 return false;
6031}
6032
John McCalld226f652010-08-21 09:40:31 +00006033Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006034 SourceLocation UsingLoc,
6035 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006036 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006037 SourceLocation IdentLoc,
6038 IdentifierInfo *NamespcName,
6039 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00006040 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6041 assert(NamespcName && "Invalid NamespcName.");
6042 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00006043
6044 // This can only happen along a recovery path.
6045 while (S->getFlags() & Scope::TemplateParamScope)
6046 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006047 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00006048
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006049 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00006050 NestedNameSpecifier *Qualifier = 0;
6051 if (SS.isSet())
6052 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
6053
Douglas Gregoreb11cd02009-01-14 22:20:51 +00006054 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00006055 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
6056 LookupParsedName(R, S, &SS);
6057 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00006058 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00006059
Douglas Gregor66992202010-06-29 17:53:46 +00006060 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006061 R.clear();
Douglas Gregor66992202010-06-29 17:53:46 +00006062 // Allow "using namespace std;" or "using namespace ::std;" even if
6063 // "std" hasn't been defined yet, for GCC compatibility.
6064 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
6065 NamespcName->isStr("std")) {
6066 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006067 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00006068 R.resolveKind();
6069 }
6070 // Otherwise, attempt typo correction.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006071 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00006072 }
6073
John McCallf36e02d2009-10-09 21:13:30 +00006074 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006075 NamedDecl *Named = R.getFoundDecl();
6076 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
6077 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006078 // C++ [namespace.udir]p1:
6079 // A using-directive specifies that the names in the nominated
6080 // namespace can be used in the scope in which the
6081 // using-directive appears after the using-directive. During
6082 // unqualified name lookup (3.4.1), the names appear as if they
6083 // were declared in the nearest enclosing namespace which
6084 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00006085 // namespace. [Note: in this context, "contains" means "contains
6086 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006087
6088 // Find enclosing context containing both using-directive and
6089 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006090 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006091 DeclContext *CommonAncestor = cast<DeclContext>(NS);
6092 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
6093 CommonAncestor = CommonAncestor->getParent();
6094
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006095 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregordb992412011-02-25 16:33:46 +00006096 SS.getWithLocInContext(Context),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006097 IdentLoc, Named, CommonAncestor);
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006098
Douglas Gregor9172aa62011-03-26 22:25:30 +00006099 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Chandler Carruth40278532011-07-25 16:49:02 +00006100 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006101 Diag(IdentLoc, diag::warn_using_directive_in_header);
6102 }
6103
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006104 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006105 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00006106 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00006107 }
6108
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006109 // FIXME: We ignore attributes for now.
John McCalld226f652010-08-21 09:40:31 +00006110 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006111}
6112
6113void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
6114 // If scope has associated entity, then using directive is at namespace
6115 // or translation unit scope. We add UsingDirectiveDecls, into
6116 // it's lookup structure.
6117 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006118 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006119 else
6120 // Otherwise it is block-sope. using-directives will affect lookup
6121 // only to the end of scope.
John McCalld226f652010-08-21 09:40:31 +00006122 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006123}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006124
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006125
John McCalld226f652010-08-21 09:40:31 +00006126Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00006127 AccessSpecifier AS,
6128 bool HasUsingKeyword,
6129 SourceLocation UsingLoc,
6130 CXXScopeSpec &SS,
6131 UnqualifiedId &Name,
6132 AttributeList *AttrList,
6133 bool IsTypeName,
6134 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006135 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00006136
Douglas Gregor12c118a2009-11-04 16:30:06 +00006137 switch (Name.getKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00006138 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006139 case UnqualifiedId::IK_Identifier:
6140 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00006141 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006142 case UnqualifiedId::IK_ConversionFunctionId:
6143 break;
6144
6145 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00006146 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall604e7f12009-12-08 07:46:18 +00006147 // C++0x inherited constructors.
Richard Smithebaf0e62011-10-18 20:49:44 +00006148 Diag(Name.getSourceRange().getBegin(),
6149 getLangOptions().CPlusPlus0x ?
6150 diag::warn_cxx98_compat_using_decl_constructor :
6151 diag::err_using_decl_constructor)
6152 << SS.getRange();
6153
John McCall604e7f12009-12-08 07:46:18 +00006154 if (getLangOptions().CPlusPlus0x) break;
6155
John McCalld226f652010-08-21 09:40:31 +00006156 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006157
6158 case UnqualifiedId::IK_DestructorName:
6159 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
6160 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00006161 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006162
6163 case UnqualifiedId::IK_TemplateId:
6164 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
6165 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00006166 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006167 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006168
6169 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
6170 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00006171 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00006172 return 0;
John McCall604e7f12009-12-08 07:46:18 +00006173
John McCall60fa3cf2009-12-11 02:10:03 +00006174 // Warn about using declarations.
6175 // TODO: store that the declaration was written without 'using' and
6176 // talk about access decls instead of using decls in the
6177 // diagnostics.
6178 if (!HasUsingKeyword) {
6179 UsingLoc = Name.getSourceRange().getBegin();
6180
6181 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00006182 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00006183 }
6184
Douglas Gregor56c04582010-12-16 00:46:58 +00006185 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
6186 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
6187 return 0;
6188
John McCall9488ea12009-11-17 05:59:44 +00006189 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006190 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006191 /* IsInstantiation */ false,
6192 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00006193 if (UD)
6194 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00006195
John McCalld226f652010-08-21 09:40:31 +00006196 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00006197}
6198
Douglas Gregor09acc982010-07-07 23:08:52 +00006199/// \brief Determine whether a using declaration considers the given
6200/// declarations as "equivalent", e.g., if they are redeclarations of
6201/// the same entity or are both typedefs of the same type.
6202static bool
6203IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
6204 bool &SuppressRedeclaration) {
6205 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
6206 SuppressRedeclaration = false;
6207 return true;
6208 }
6209
Richard Smith162e1c12011-04-15 14:24:37 +00006210 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
6211 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor09acc982010-07-07 23:08:52 +00006212 SuppressRedeclaration = true;
6213 return Context.hasSameType(TD1->getUnderlyingType(),
6214 TD2->getUnderlyingType());
6215 }
6216
6217 return false;
6218}
6219
6220
John McCall9f54ad42009-12-10 09:41:52 +00006221/// Determines whether to create a using shadow decl for a particular
6222/// decl, given the set of decls existing prior to this using lookup.
6223bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
6224 const LookupResult &Previous) {
6225 // Diagnose finding a decl which is not from a base class of the
6226 // current class. We do this now because there are cases where this
6227 // function will silently decide not to build a shadow decl, which
6228 // will pre-empt further diagnostics.
6229 //
6230 // We don't need to do this in C++0x because we do the check once on
6231 // the qualifier.
6232 //
6233 // FIXME: diagnose the following if we care enough:
6234 // struct A { int foo; };
6235 // struct B : A { using A::foo; };
6236 // template <class T> struct C : A {};
6237 // template <class T> struct D : C<T> { using B::foo; } // <---
6238 // This is invalid (during instantiation) in C++03 because B::foo
6239 // resolves to the using decl in B, which is not a base class of D<T>.
6240 // We can't diagnose it immediately because C<T> is an unknown
6241 // specialization. The UsingShadowDecl in D<T> then points directly
6242 // to A::foo, which will look well-formed when we instantiate.
6243 // The right solution is to not collapse the shadow-decl chain.
6244 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
6245 DeclContext *OrigDC = Orig->getDeclContext();
6246
6247 // Handle enums and anonymous structs.
6248 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
6249 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
6250 while (OrigRec->isAnonymousStructOrUnion())
6251 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
6252
6253 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
6254 if (OrigDC == CurContext) {
6255 Diag(Using->getLocation(),
6256 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006257 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006258 Diag(Orig->getLocation(), diag::note_using_decl_target);
6259 return true;
6260 }
6261
Douglas Gregordc355712011-02-25 00:36:19 +00006262 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall9f54ad42009-12-10 09:41:52 +00006263 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006264 << Using->getQualifier()
John McCall9f54ad42009-12-10 09:41:52 +00006265 << cast<CXXRecordDecl>(CurContext)
Douglas Gregordc355712011-02-25 00:36:19 +00006266 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006267 Diag(Orig->getLocation(), diag::note_using_decl_target);
6268 return true;
6269 }
6270 }
6271
6272 if (Previous.empty()) return false;
6273
6274 NamedDecl *Target = Orig;
6275 if (isa<UsingShadowDecl>(Target))
6276 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6277
John McCalld7533ec2009-12-11 02:33:26 +00006278 // If the target happens to be one of the previous declarations, we
6279 // don't have a conflict.
6280 //
6281 // FIXME: but we might be increasing its access, in which case we
6282 // should redeclare it.
6283 NamedDecl *NonTag = 0, *Tag = 0;
6284 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6285 I != E; ++I) {
6286 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00006287 bool Result;
6288 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
6289 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00006290
6291 (isa<TagDecl>(D) ? Tag : NonTag) = D;
6292 }
6293
John McCall9f54ad42009-12-10 09:41:52 +00006294 if (Target->isFunctionOrFunctionTemplate()) {
6295 FunctionDecl *FD;
6296 if (isa<FunctionTemplateDecl>(Target))
6297 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
6298 else
6299 FD = cast<FunctionDecl>(Target);
6300
6301 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00006302 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00006303 case Ovl_Overload:
6304 return false;
6305
6306 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00006307 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006308 break;
6309
6310 // We found a decl with the exact signature.
6311 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00006312 // If we're in a record, we want to hide the target, so we
6313 // return true (without a diagnostic) to tell the caller not to
6314 // build a shadow decl.
6315 if (CurContext->isRecord())
6316 return true;
6317
6318 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00006319 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006320 break;
6321 }
6322
6323 Diag(Target->getLocation(), diag::note_using_decl_target);
6324 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
6325 return true;
6326 }
6327
6328 // Target is not a function.
6329
John McCall9f54ad42009-12-10 09:41:52 +00006330 if (isa<TagDecl>(Target)) {
6331 // No conflict between a tag and a non-tag.
6332 if (!Tag) return false;
6333
John McCall41ce66f2009-12-10 19:51:03 +00006334 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006335 Diag(Target->getLocation(), diag::note_using_decl_target);
6336 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
6337 return true;
6338 }
6339
6340 // No conflict between a tag and a non-tag.
6341 if (!NonTag) return false;
6342
John McCall41ce66f2009-12-10 19:51:03 +00006343 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006344 Diag(Target->getLocation(), diag::note_using_decl_target);
6345 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
6346 return true;
6347}
6348
John McCall9488ea12009-11-17 05:59:44 +00006349/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00006350UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00006351 UsingDecl *UD,
6352 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00006353
6354 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00006355 NamedDecl *Target = Orig;
6356 if (isa<UsingShadowDecl>(Target)) {
6357 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6358 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00006359 }
6360
6361 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00006362 = UsingShadowDecl::Create(Context, CurContext,
6363 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00006364 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00006365
6366 Shadow->setAccess(UD->getAccess());
6367 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
6368 Shadow->setInvalidDecl();
6369
John McCall9488ea12009-11-17 05:59:44 +00006370 if (S)
John McCall604e7f12009-12-08 07:46:18 +00006371 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00006372 else
John McCall604e7f12009-12-08 07:46:18 +00006373 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00006374
John McCall604e7f12009-12-08 07:46:18 +00006375
John McCall9f54ad42009-12-10 09:41:52 +00006376 return Shadow;
6377}
John McCall604e7f12009-12-08 07:46:18 +00006378
John McCall9f54ad42009-12-10 09:41:52 +00006379/// Hides a using shadow declaration. This is required by the current
6380/// using-decl implementation when a resolvable using declaration in a
6381/// class is followed by a declaration which would hide or override
6382/// one or more of the using decl's targets; for example:
6383///
6384/// struct Base { void foo(int); };
6385/// struct Derived : Base {
6386/// using Base::foo;
6387/// void foo(int);
6388/// };
6389///
6390/// The governing language is C++03 [namespace.udecl]p12:
6391///
6392/// When a using-declaration brings names from a base class into a
6393/// derived class scope, member functions in the derived class
6394/// override and/or hide member functions with the same name and
6395/// parameter types in a base class (rather than conflicting).
6396///
6397/// There are two ways to implement this:
6398/// (1) optimistically create shadow decls when they're not hidden
6399/// by existing declarations, or
6400/// (2) don't create any shadow decls (or at least don't make them
6401/// visible) until we've fully parsed/instantiated the class.
6402/// The problem with (1) is that we might have to retroactively remove
6403/// a shadow decl, which requires several O(n) operations because the
6404/// decl structures are (very reasonably) not designed for removal.
6405/// (2) avoids this but is very fiddly and phase-dependent.
6406void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00006407 if (Shadow->getDeclName().getNameKind() ==
6408 DeclarationName::CXXConversionFunctionName)
6409 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
6410
John McCall9f54ad42009-12-10 09:41:52 +00006411 // Remove it from the DeclContext...
6412 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006413
John McCall9f54ad42009-12-10 09:41:52 +00006414 // ...and the scope, if applicable...
6415 if (S) {
John McCalld226f652010-08-21 09:40:31 +00006416 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00006417 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006418 }
6419
John McCall9f54ad42009-12-10 09:41:52 +00006420 // ...and the using decl.
6421 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
6422
6423 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00006424 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00006425}
6426
John McCall7ba107a2009-11-18 02:36:19 +00006427/// Builds a using declaration.
6428///
6429/// \param IsInstantiation - Whether this call arises from an
6430/// instantiation of an unresolved using declaration. We treat
6431/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00006432NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
6433 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006434 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006435 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00006436 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006437 bool IsInstantiation,
6438 bool IsTypeName,
6439 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00006440 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006441 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00006442 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00006443
Anders Carlsson550b14b2009-08-28 05:49:21 +00006444 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00006445
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006446 if (SS.isEmpty()) {
6447 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00006448 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006449 }
Mike Stump1eb44332009-09-09 15:08:12 +00006450
John McCall9f54ad42009-12-10 09:41:52 +00006451 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006452 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00006453 ForRedeclaration);
6454 Previous.setHideTags(false);
6455 if (S) {
6456 LookupName(Previous, S);
6457
6458 // It is really dumb that we have to do this.
6459 LookupResult::Filter F = Previous.makeFilter();
6460 while (F.hasNext()) {
6461 NamedDecl *D = F.next();
6462 if (!isDeclInScope(D, CurContext, S))
6463 F.erase();
6464 }
6465 F.done();
6466 } else {
6467 assert(IsInstantiation && "no scope in non-instantiation");
6468 assert(CurContext->isRecord() && "scope not record in instantiation");
6469 LookupQualifiedName(Previous, CurContext);
6470 }
6471
John McCall9f54ad42009-12-10 09:41:52 +00006472 // Check for invalid redeclarations.
6473 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
6474 return 0;
6475
6476 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00006477 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
6478 return 0;
6479
John McCallaf8e6ed2009-11-12 03:15:40 +00006480 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00006481 NamedDecl *D;
Douglas Gregordc355712011-02-25 00:36:19 +00006482 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallaf8e6ed2009-11-12 03:15:40 +00006483 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00006484 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00006485 // FIXME: not all declaration name kinds are legal here
6486 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
6487 UsingLoc, TypenameLoc,
Douglas Gregordc355712011-02-25 00:36:19 +00006488 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006489 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00006490 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00006491 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
6492 QualifierLoc, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00006493 }
John McCalled976492009-12-04 22:46:56 +00006494 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00006495 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
6496 NameInfo, IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00006497 }
John McCalled976492009-12-04 22:46:56 +00006498 D->setAccess(AS);
6499 CurContext->addDecl(D);
6500
6501 if (!LookupContext) return D;
6502 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00006503
John McCall77bb1aa2010-05-01 00:40:08 +00006504 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00006505 UD->setInvalidDecl();
6506 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006507 }
6508
Sebastian Redlf677ea32011-02-05 19:23:19 +00006509 // Constructor inheriting using decls get special treatment.
6510 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Sebastian Redlcaa35e42011-03-12 13:44:32 +00006511 if (CheckInheritedConstructorUsingDecl(UD))
6512 UD->setInvalidDecl();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006513 return UD;
6514 }
6515
6516 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00006517
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006518 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00006519
John McCall604e7f12009-12-08 07:46:18 +00006520 // Unlike most lookups, we don't always want to hide tag
6521 // declarations: tag names are visible through the using declaration
6522 // even if hidden by ordinary names, *except* in a dependent context
6523 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00006524 if (!IsInstantiation)
6525 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00006526
John McCalla24dc2e2009-11-17 02:14:36 +00006527 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00006528
John McCallf36e02d2009-10-09 21:13:30 +00006529 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00006530 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006531 << NameInfo.getName() << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00006532 UD->setInvalidDecl();
6533 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006534 }
6535
John McCalled976492009-12-04 22:46:56 +00006536 if (R.isAmbiguous()) {
6537 UD->setInvalidDecl();
6538 return UD;
6539 }
Mike Stump1eb44332009-09-09 15:08:12 +00006540
John McCall7ba107a2009-11-18 02:36:19 +00006541 if (IsTypeName) {
6542 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00006543 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00006544 Diag(IdentLoc, diag::err_using_typename_non_type);
6545 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
6546 Diag((*I)->getUnderlyingDecl()->getLocation(),
6547 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006548 UD->setInvalidDecl();
6549 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00006550 }
6551 } else {
6552 // If we asked for a non-typename and we got a type, error out,
6553 // but only if this is an instantiation of an unresolved using
6554 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00006555 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00006556 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
6557 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006558 UD->setInvalidDecl();
6559 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00006560 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006561 }
6562
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006563 // C++0x N2914 [namespace.udecl]p6:
6564 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00006565 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006566 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
6567 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00006568 UD->setInvalidDecl();
6569 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006570 }
Mike Stump1eb44332009-09-09 15:08:12 +00006571
John McCall9f54ad42009-12-10 09:41:52 +00006572 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
6573 if (!CheckUsingShadowDecl(UD, *I, Previous))
6574 BuildUsingShadowDecl(S, UD, *I);
6575 }
John McCall9488ea12009-11-17 05:59:44 +00006576
6577 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006578}
6579
Sebastian Redlf677ea32011-02-05 19:23:19 +00006580/// Additional checks for a using declaration referring to a constructor name.
6581bool Sema::CheckInheritedConstructorUsingDecl(UsingDecl *UD) {
6582 if (UD->isTypeName()) {
6583 // FIXME: Cannot specify typename when specifying constructor
6584 return true;
6585 }
6586
Douglas Gregordc355712011-02-25 00:36:19 +00006587 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006588 assert(SourceType &&
6589 "Using decl naming constructor doesn't have type in scope spec.");
6590 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
6591
6592 // Check whether the named type is a direct base class.
6593 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
6594 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
6595 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
6596 BaseIt != BaseE; ++BaseIt) {
6597 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
6598 if (CanonicalSourceType == BaseType)
6599 break;
6600 }
6601
6602 if (BaseIt == BaseE) {
6603 // Did not find SourceType in the bases.
6604 Diag(UD->getUsingLocation(),
6605 diag::err_using_decl_constructor_not_in_direct_base)
6606 << UD->getNameInfo().getSourceRange()
6607 << QualType(SourceType, 0) << TargetClass;
6608 return true;
6609 }
6610
6611 BaseIt->setInheritConstructors();
6612
6613 return false;
6614}
6615
John McCall9f54ad42009-12-10 09:41:52 +00006616/// Checks that the given using declaration is not an invalid
6617/// redeclaration. Note that this is checking only for the using decl
6618/// itself, not for any ill-formedness among the UsingShadowDecls.
6619bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
6620 bool isTypeName,
6621 const CXXScopeSpec &SS,
6622 SourceLocation NameLoc,
6623 const LookupResult &Prev) {
6624 // C++03 [namespace.udecl]p8:
6625 // C++0x [namespace.udecl]p10:
6626 // A using-declaration is a declaration and can therefore be used
6627 // repeatedly where (and only where) multiple declarations are
6628 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00006629 //
John McCall8a726212010-11-29 18:01:58 +00006630 // That's in non-member contexts.
6631 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00006632 return false;
6633
6634 NestedNameSpecifier *Qual
6635 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
6636
6637 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
6638 NamedDecl *D = *I;
6639
6640 bool DTypename;
6641 NestedNameSpecifier *DQual;
6642 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
6643 DTypename = UD->isTypeName();
Douglas Gregordc355712011-02-25 00:36:19 +00006644 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006645 } else if (UnresolvedUsingValueDecl *UD
6646 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
6647 DTypename = false;
Douglas Gregordc355712011-02-25 00:36:19 +00006648 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006649 } else if (UnresolvedUsingTypenameDecl *UD
6650 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
6651 DTypename = true;
Douglas Gregordc355712011-02-25 00:36:19 +00006652 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006653 } else continue;
6654
6655 // using decls differ if one says 'typename' and the other doesn't.
6656 // FIXME: non-dependent using decls?
6657 if (isTypeName != DTypename) continue;
6658
6659 // using decls differ if they name different scopes (but note that
6660 // template instantiation can cause this check to trigger when it
6661 // didn't before instantiation).
6662 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
6663 Context.getCanonicalNestedNameSpecifier(DQual))
6664 continue;
6665
6666 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00006667 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00006668 return true;
6669 }
6670
6671 return false;
6672}
6673
John McCall604e7f12009-12-08 07:46:18 +00006674
John McCalled976492009-12-04 22:46:56 +00006675/// Checks that the given nested-name qualifier used in a using decl
6676/// in the current context is appropriately related to the current
6677/// scope. If an error is found, diagnoses it and returns true.
6678bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
6679 const CXXScopeSpec &SS,
6680 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00006681 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00006682
John McCall604e7f12009-12-08 07:46:18 +00006683 if (!CurContext->isRecord()) {
6684 // C++03 [namespace.udecl]p3:
6685 // C++0x [namespace.udecl]p8:
6686 // A using-declaration for a class member shall be a member-declaration.
6687
6688 // If we weren't able to compute a valid scope, it must be a
6689 // dependent class scope.
6690 if (!NamedContext || NamedContext->isRecord()) {
6691 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
6692 << SS.getRange();
6693 return true;
6694 }
6695
6696 // Otherwise, everything is known to be fine.
6697 return false;
6698 }
6699
6700 // The current scope is a record.
6701
6702 // If the named context is dependent, we can't decide much.
6703 if (!NamedContext) {
6704 // FIXME: in C++0x, we can diagnose if we can prove that the
6705 // nested-name-specifier does not refer to a base class, which is
6706 // still possible in some cases.
6707
6708 // Otherwise we have to conservatively report that things might be
6709 // okay.
6710 return false;
6711 }
6712
6713 if (!NamedContext->isRecord()) {
6714 // Ideally this would point at the last name in the specifier,
6715 // but we don't have that level of source info.
6716 Diag(SS.getRange().getBegin(),
6717 diag::err_using_decl_nested_name_specifier_is_not_class)
6718 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
6719 return true;
6720 }
6721
Douglas Gregor6fb07292010-12-21 07:41:49 +00006722 if (!NamedContext->isDependentContext() &&
6723 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
6724 return true;
6725
John McCall604e7f12009-12-08 07:46:18 +00006726 if (getLangOptions().CPlusPlus0x) {
6727 // C++0x [namespace.udecl]p3:
6728 // In a using-declaration used as a member-declaration, the
6729 // nested-name-specifier shall name a base class of the class
6730 // being defined.
6731
6732 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
6733 cast<CXXRecordDecl>(NamedContext))) {
6734 if (CurContext == NamedContext) {
6735 Diag(NameLoc,
6736 diag::err_using_decl_nested_name_specifier_is_current_class)
6737 << SS.getRange();
6738 return true;
6739 }
6740
6741 Diag(SS.getRange().getBegin(),
6742 diag::err_using_decl_nested_name_specifier_is_not_base_class)
6743 << (NestedNameSpecifier*) SS.getScopeRep()
6744 << cast<CXXRecordDecl>(CurContext)
6745 << SS.getRange();
6746 return true;
6747 }
6748
6749 return false;
6750 }
6751
6752 // C++03 [namespace.udecl]p4:
6753 // A using-declaration used as a member-declaration shall refer
6754 // to a member of a base class of the class being defined [etc.].
6755
6756 // Salient point: SS doesn't have to name a base class as long as
6757 // lookup only finds members from base classes. Therefore we can
6758 // diagnose here only if we can prove that that can't happen,
6759 // i.e. if the class hierarchies provably don't intersect.
6760
6761 // TODO: it would be nice if "definitely valid" results were cached
6762 // in the UsingDecl and UsingShadowDecl so that these checks didn't
6763 // need to be repeated.
6764
6765 struct UserData {
6766 llvm::DenseSet<const CXXRecordDecl*> Bases;
6767
6768 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
6769 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6770 Data->Bases.insert(Base);
6771 return true;
6772 }
6773
6774 bool hasDependentBases(const CXXRecordDecl *Class) {
6775 return !Class->forallBases(collect, this);
6776 }
6777
6778 /// Returns true if the base is dependent or is one of the
6779 /// accumulated base classes.
6780 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
6781 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6782 return !Data->Bases.count(Base);
6783 }
6784
6785 bool mightShareBases(const CXXRecordDecl *Class) {
6786 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
6787 }
6788 };
6789
6790 UserData Data;
6791
6792 // Returns false if we find a dependent base.
6793 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
6794 return false;
6795
6796 // Returns false if the class has a dependent base or if it or one
6797 // of its bases is present in the base set of the current context.
6798 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
6799 return false;
6800
6801 Diag(SS.getRange().getBegin(),
6802 diag::err_using_decl_nested_name_specifier_is_not_base_class)
6803 << (NestedNameSpecifier*) SS.getScopeRep()
6804 << cast<CXXRecordDecl>(CurContext)
6805 << SS.getRange();
6806
6807 return true;
John McCalled976492009-12-04 22:46:56 +00006808}
6809
Richard Smith162e1c12011-04-15 14:24:37 +00006810Decl *Sema::ActOnAliasDeclaration(Scope *S,
6811 AccessSpecifier AS,
Richard Smith3e4c6c42011-05-05 21:57:07 +00006812 MultiTemplateParamsArg TemplateParamLists,
Richard Smith162e1c12011-04-15 14:24:37 +00006813 SourceLocation UsingLoc,
6814 UnqualifiedId &Name,
6815 TypeResult Type) {
Richard Smith3e4c6c42011-05-05 21:57:07 +00006816 // Skip up to the relevant declaration scope.
6817 while (S->getFlags() & Scope::TemplateParamScope)
6818 S = S->getParent();
Richard Smith162e1c12011-04-15 14:24:37 +00006819 assert((S->getFlags() & Scope::DeclScope) &&
6820 "got alias-declaration outside of declaration scope");
6821
6822 if (Type.isInvalid())
6823 return 0;
6824
6825 bool Invalid = false;
6826 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
6827 TypeSourceInfo *TInfo = 0;
Nick Lewyckyb79bf1d2011-05-02 01:07:19 +00006828 GetTypeFromParser(Type.get(), &TInfo);
Richard Smith162e1c12011-04-15 14:24:37 +00006829
6830 if (DiagnoseClassNameShadow(CurContext, NameInfo))
6831 return 0;
6832
6833 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3e4c6c42011-05-05 21:57:07 +00006834 UPPC_DeclarationType)) {
Richard Smith162e1c12011-04-15 14:24:37 +00006835 Invalid = true;
Richard Smith3e4c6c42011-05-05 21:57:07 +00006836 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
6837 TInfo->getTypeLoc().getBeginLoc());
6838 }
Richard Smith162e1c12011-04-15 14:24:37 +00006839
6840 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
6841 LookupName(Previous, S);
6842
6843 // Warn about shadowing the name of a template parameter.
6844 if (Previous.isSingleResult() &&
6845 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorcb8f9512011-10-20 17:58:49 +00006846 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smith162e1c12011-04-15 14:24:37 +00006847 Previous.clear();
6848 }
6849
6850 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
6851 "name in alias declaration must be an identifier");
6852 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
6853 Name.StartLocation,
6854 Name.Identifier, TInfo);
6855
6856 NewTD->setAccess(AS);
6857
6858 if (Invalid)
6859 NewTD->setInvalidDecl();
6860
Richard Smith3e4c6c42011-05-05 21:57:07 +00006861 CheckTypedefForVariablyModifiedType(S, NewTD);
6862 Invalid |= NewTD->isInvalidDecl();
6863
Richard Smith162e1c12011-04-15 14:24:37 +00006864 bool Redeclaration = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00006865
6866 NamedDecl *NewND;
6867 if (TemplateParamLists.size()) {
6868 TypeAliasTemplateDecl *OldDecl = 0;
6869 TemplateParameterList *OldTemplateParams = 0;
6870
6871 if (TemplateParamLists.size() != 1) {
6872 Diag(UsingLoc, diag::err_alias_template_extra_headers)
6873 << SourceRange(TemplateParamLists.get()[1]->getTemplateLoc(),
6874 TemplateParamLists.get()[TemplateParamLists.size()-1]->getRAngleLoc());
6875 }
6876 TemplateParameterList *TemplateParams = TemplateParamLists.get()[0];
6877
6878 // Only consider previous declarations in the same scope.
6879 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
6880 /*ExplicitInstantiationOrSpecialization*/false);
6881 if (!Previous.empty()) {
6882 Redeclaration = true;
6883
6884 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
6885 if (!OldDecl && !Invalid) {
6886 Diag(UsingLoc, diag::err_redefinition_different_kind)
6887 << Name.Identifier;
6888
6889 NamedDecl *OldD = Previous.getRepresentativeDecl();
6890 if (OldD->getLocation().isValid())
6891 Diag(OldD->getLocation(), diag::note_previous_definition);
6892
6893 Invalid = true;
6894 }
6895
6896 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
6897 if (TemplateParameterListsAreEqual(TemplateParams,
6898 OldDecl->getTemplateParameters(),
6899 /*Complain=*/true,
6900 TPL_TemplateMatch))
6901 OldTemplateParams = OldDecl->getTemplateParameters();
6902 else
6903 Invalid = true;
6904
6905 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
6906 if (!Invalid &&
6907 !Context.hasSameType(OldTD->getUnderlyingType(),
6908 NewTD->getUnderlyingType())) {
6909 // FIXME: The C++0x standard does not clearly say this is ill-formed,
6910 // but we can't reasonably accept it.
6911 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
6912 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
6913 if (OldTD->getLocation().isValid())
6914 Diag(OldTD->getLocation(), diag::note_previous_definition);
6915 Invalid = true;
6916 }
6917 }
6918 }
6919
6920 // Merge any previous default template arguments into our parameters,
6921 // and check the parameter list.
6922 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
6923 TPC_TypeAliasTemplate))
6924 return 0;
6925
6926 TypeAliasTemplateDecl *NewDecl =
6927 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
6928 Name.Identifier, TemplateParams,
6929 NewTD);
6930
6931 NewDecl->setAccess(AS);
6932
6933 if (Invalid)
6934 NewDecl->setInvalidDecl();
6935 else if (OldDecl)
6936 NewDecl->setPreviousDeclaration(OldDecl);
6937
6938 NewND = NewDecl;
6939 } else {
6940 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
6941 NewND = NewTD;
6942 }
Richard Smith162e1c12011-04-15 14:24:37 +00006943
6944 if (!Redeclaration)
Richard Smith3e4c6c42011-05-05 21:57:07 +00006945 PushOnScopeChains(NewND, S);
Richard Smith162e1c12011-04-15 14:24:37 +00006946
Richard Smith3e4c6c42011-05-05 21:57:07 +00006947 return NewND;
Richard Smith162e1c12011-04-15 14:24:37 +00006948}
6949
John McCalld226f652010-08-21 09:40:31 +00006950Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00006951 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006952 SourceLocation AliasLoc,
6953 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006954 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00006955 SourceLocation IdentLoc,
6956 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00006957
Anders Carlsson81c85c42009-03-28 23:53:49 +00006958 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00006959 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
6960 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00006961
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006962 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00006963 NamedDecl *PrevDecl
6964 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
6965 ForRedeclaration);
6966 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
6967 PrevDecl = 0;
6968
6969 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00006970 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00006971 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00006972 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00006973 // FIXME: At some point, we'll want to create the (redundant)
6974 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00006975 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00006976 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00006977 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00006978 }
Mike Stump1eb44332009-09-09 15:08:12 +00006979
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006980 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
6981 diag::err_redefinition_different_kind;
6982 Diag(AliasLoc, DiagID) << Alias;
6983 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00006984 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006985 }
6986
John McCalla24dc2e2009-11-17 02:14:36 +00006987 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00006988 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00006989
John McCallf36e02d2009-10-09 21:13:30 +00006990 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006991 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00006992 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00006993 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00006994 }
Anders Carlsson5721c682009-03-28 06:42:02 +00006995 }
Mike Stump1eb44332009-09-09 15:08:12 +00006996
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00006997 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00006998 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00006999 Alias, SS.getWithLocInContext(Context),
John McCallf36e02d2009-10-09 21:13:30 +00007000 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00007001
John McCall3dbd3d52010-02-16 06:53:13 +00007002 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00007003 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00007004}
7005
Douglas Gregor39957dc2010-05-01 15:04:51 +00007006namespace {
7007 /// \brief Scoped object used to handle the state changes required in Sema
7008 /// to implicitly define the body of a C++ member function;
7009 class ImplicitlyDefinedFunctionScope {
7010 Sema &S;
John McCalleee1d542011-02-14 07:13:47 +00007011 Sema::ContextRAII SavedContext;
Douglas Gregor39957dc2010-05-01 15:04:51 +00007012
7013 public:
7014 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
John McCalleee1d542011-02-14 07:13:47 +00007015 : S(S), SavedContext(S, Method)
Douglas Gregor39957dc2010-05-01 15:04:51 +00007016 {
Douglas Gregor39957dc2010-05-01 15:04:51 +00007017 S.PushFunctionScope();
7018 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
7019 }
7020
7021 ~ImplicitlyDefinedFunctionScope() {
7022 S.PopExpressionEvaluationContext();
Eli Friedmanec9ea722012-01-05 03:35:19 +00007023 S.PopFunctionScopeInfo();
Douglas Gregor39957dc2010-05-01 15:04:51 +00007024 }
7025 };
7026}
7027
Sean Hunt001cad92011-05-10 00:49:42 +00007028Sema::ImplicitExceptionSpecification
7029Sema::ComputeDefaultedDefaultCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007030 // C++ [except.spec]p14:
7031 // An implicitly declared special member function (Clause 12) shall have an
7032 // exception-specification. [...]
7033 ImplicitExceptionSpecification ExceptSpec(Context);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007034 if (ClassDecl->isInvalidDecl())
7035 return ExceptSpec;
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007036
Sebastian Redl60618fa2011-03-12 11:50:43 +00007037 // Direct base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007038 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7039 BEnd = ClassDecl->bases_end();
7040 B != BEnd; ++B) {
7041 if (B->isVirtual()) // Handled below.
7042 continue;
7043
Douglas Gregor18274032010-07-03 00:47:00 +00007044 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7045 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007046 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7047 // If this is a deleted function, add it anyway. This might be conformant
7048 // with the standard. This might not. I'm not sure. It might not matter.
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 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007053
7054 // Virtual base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007055 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7056 BEnd = ClassDecl->vbases_end();
7057 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00007058 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7059 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007060 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7061 // If this is a deleted function, add it anyway. This might be conformant
7062 // with the standard. This might not. I'm not sure. It might not matter.
7063 if (Constructor)
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007064 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007065 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007066 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007067
7068 // Field constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007069 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7070 FEnd = ClassDecl->field_end();
7071 F != FEnd; ++F) {
Richard Smith7a614d82011-06-11 17:19:42 +00007072 if (F->hasInClassInitializer()) {
7073 if (Expr *E = F->getInClassInitializer())
7074 ExceptSpec.CalledExpr(E);
7075 else if (!F->isInvalidDecl())
7076 ExceptSpec.SetDelayed();
7077 } else if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00007078 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Sean Huntb320e0c2011-06-10 03:50:41 +00007079 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7080 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7081 // If this is a deleted function, add it anyway. This might be conformant
7082 // with the standard. This might not. I'm not sure. It might not matter.
7083 // In particular, the problem is that this function never gets called. It
7084 // might just be ill-formed because this function attempts to refer to
7085 // a deleted function here.
7086 if (Constructor)
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007087 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007088 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007089 }
John McCalle23cf432010-12-14 08:05:40 +00007090
Sean Hunt001cad92011-05-10 00:49:42 +00007091 return ExceptSpec;
7092}
7093
7094CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
7095 CXXRecordDecl *ClassDecl) {
7096 // C++ [class.ctor]p5:
7097 // A default constructor for a class X is a constructor of class X
7098 // that can be called without an argument. If there is no
7099 // user-declared constructor for class X, a default constructor is
7100 // implicitly declared. An implicitly-declared default constructor
7101 // is an inline public member of its class.
7102 assert(!ClassDecl->hasUserDeclaredConstructor() &&
7103 "Should not build implicit default constructor!");
7104
7105 ImplicitExceptionSpecification Spec =
7106 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
7107 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Sebastian Redl8b5b4092011-03-06 10:52:04 +00007108
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007109 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00007110 CanQualType ClassType
7111 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007112 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007113 DeclarationName Name
7114 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007115 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith61802452011-12-22 02:22:31 +00007116 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
7117 Context, ClassDecl, ClassLoc, NameInfo,
7118 Context.getFunctionType(Context.VoidTy, 0, 0, EPI), /*TInfo=*/0,
7119 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
7120 /*isConstexpr=*/ClassDecl->defaultedDefaultConstructorIsConstexpr() &&
7121 getLangOptions().CPlusPlus0x);
Douglas Gregor32df23e2010-07-01 22:02:46 +00007122 DefaultCon->setAccess(AS_public);
Sean Hunt1e238652011-05-12 03:51:51 +00007123 DefaultCon->setDefaulted();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007124 DefaultCon->setImplicit();
Sean Hunt023df372011-05-09 18:22:59 +00007125 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
Douglas Gregor18274032010-07-03 00:47:00 +00007126
7127 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00007128 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
7129
Douglas Gregor23c94db2010-07-02 17:43:08 +00007130 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00007131 PushOnScopeChains(DefaultCon, S, false);
7132 ClassDecl->addDecl(DefaultCon);
Sean Hunt71a682f2011-05-18 03:41:58 +00007133
Sean Hunte16da072011-10-10 06:18:57 +00007134 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Sean Hunt71a682f2011-05-18 03:41:58 +00007135 DefaultCon->setDeletedAsWritten();
Douglas Gregor18274032010-07-03 00:47:00 +00007136
Douglas Gregor32df23e2010-07-01 22:02:46 +00007137 return DefaultCon;
7138}
7139
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007140void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
7141 CXXConstructorDecl *Constructor) {
Sean Hunt1e238652011-05-12 03:51:51 +00007142 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00007143 !Constructor->doesThisDeclarationHaveABody() &&
7144 !Constructor->isDeleted()) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00007145 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00007146
Anders Carlssonf6513ed2010-04-23 16:04:08 +00007147 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00007148 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00007149
Douglas Gregor39957dc2010-05-01 15:04:51 +00007150 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007151 DiagnosticErrorTrap Trap(Diags);
Sean Huntcbb67482011-01-08 20:30:50 +00007152 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007153 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00007154 Diag(CurrentLocation, diag::note_member_synthesized_at)
Sean Huntf961ea52011-05-10 19:08:14 +00007155 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00007156 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007157 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00007158 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007159
7160 SourceLocation Loc = Constructor->getLocation();
7161 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
7162
7163 Constructor->setUsed();
7164 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007165
7166 if (ASTMutationListener *L = getASTMutationListener()) {
7167 L->CompletedImplicitDefinition(Constructor);
7168 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007169}
7170
Richard Smith7a614d82011-06-11 17:19:42 +00007171/// Get any existing defaulted default constructor for the given class. Do not
7172/// implicitly define one if it does not exist.
7173static CXXConstructorDecl *getDefaultedDefaultConstructorUnsafe(Sema &Self,
7174 CXXRecordDecl *D) {
7175 ASTContext &Context = Self.Context;
7176 QualType ClassType = Context.getTypeDeclType(D);
7177 DeclarationName ConstructorName
7178 = Context.DeclarationNames.getCXXConstructorName(
7179 Context.getCanonicalType(ClassType.getUnqualifiedType()));
7180
7181 DeclContext::lookup_const_iterator Con, ConEnd;
7182 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
7183 Con != ConEnd; ++Con) {
7184 // A function template cannot be defaulted.
7185 if (isa<FunctionTemplateDecl>(*Con))
7186 continue;
7187
7188 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
7189 if (Constructor->isDefaultConstructor())
7190 return Constructor->isDefaulted() ? Constructor : 0;
7191 }
7192 return 0;
7193}
7194
7195void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
7196 if (!D) return;
7197 AdjustDeclIfTemplate(D);
7198
7199 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D);
7200 CXXConstructorDecl *CtorDecl
7201 = getDefaultedDefaultConstructorUnsafe(*this, ClassDecl);
7202
7203 if (!CtorDecl) return;
7204
7205 // Compute the exception specification for the default constructor.
7206 const FunctionProtoType *CtorTy =
7207 CtorDecl->getType()->castAs<FunctionProtoType>();
7208 if (CtorTy->getExceptionSpecType() == EST_Delayed) {
7209 ImplicitExceptionSpecification Spec =
7210 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
7211 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
7212 assert(EPI.ExceptionSpecType != EST_Delayed);
7213
7214 CtorDecl->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
7215 }
7216
7217 // If the default constructor is explicitly defaulted, checking the exception
7218 // specification is deferred until now.
7219 if (!CtorDecl->isInvalidDecl() && CtorDecl->isExplicitlyDefaulted() &&
7220 !ClassDecl->isDependentType())
7221 CheckExplicitlyDefaultedDefaultConstructor(CtorDecl);
7222}
7223
Sebastian Redlf677ea32011-02-05 19:23:19 +00007224void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
7225 // We start with an initial pass over the base classes to collect those that
7226 // inherit constructors from. If there are none, we can forgo all further
7227 // processing.
Chris Lattner5f9e2722011-07-23 10:55:15 +00007228 typedef SmallVector<const RecordType *, 4> BasesVector;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007229 BasesVector BasesToInheritFrom;
7230 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
7231 BaseE = ClassDecl->bases_end();
7232 BaseIt != BaseE; ++BaseIt) {
7233 if (BaseIt->getInheritConstructors()) {
7234 QualType Base = BaseIt->getType();
7235 if (Base->isDependentType()) {
7236 // If we inherit constructors from anything that is dependent, just
7237 // abort processing altogether. We'll get another chance for the
7238 // instantiations.
7239 return;
7240 }
7241 BasesToInheritFrom.push_back(Base->castAs<RecordType>());
7242 }
7243 }
7244 if (BasesToInheritFrom.empty())
7245 return;
7246
7247 // Now collect the constructors that we already have in the current class.
7248 // Those take precedence over inherited constructors.
7249 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
7250 // unless there is a user-declared constructor with the same signature in
7251 // the class where the using-declaration appears.
7252 llvm::SmallSet<const Type *, 8> ExistingConstructors;
7253 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
7254 CtorE = ClassDecl->ctor_end();
7255 CtorIt != CtorE; ++CtorIt) {
7256 ExistingConstructors.insert(
7257 Context.getCanonicalType(CtorIt->getType()).getTypePtr());
7258 }
7259
7260 Scope *S = getScopeForContext(ClassDecl);
7261 DeclarationName CreatedCtorName =
7262 Context.DeclarationNames.getCXXConstructorName(
7263 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
7264
7265 // Now comes the true work.
7266 // First, we keep a map from constructor types to the base that introduced
7267 // them. Needed for finding conflicting constructors. We also keep the
7268 // actually inserted declarations in there, for pretty diagnostics.
7269 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
7270 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
7271 ConstructorToSourceMap InheritedConstructors;
7272 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
7273 BaseE = BasesToInheritFrom.end();
7274 BaseIt != BaseE; ++BaseIt) {
7275 const RecordType *Base = *BaseIt;
7276 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
7277 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
7278 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
7279 CtorE = BaseDecl->ctor_end();
7280 CtorIt != CtorE; ++CtorIt) {
7281 // Find the using declaration for inheriting this base's constructors.
7282 DeclarationName Name =
7283 Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
7284 UsingDecl *UD = dyn_cast_or_null<UsingDecl>(
7285 LookupSingleName(S, Name,SourceLocation(), LookupUsingDeclName));
7286 SourceLocation UsingLoc = UD ? UD->getLocation() :
7287 ClassDecl->getLocation();
7288
7289 // C++0x [class.inhctor]p1: The candidate set of inherited constructors
7290 // from the class X named in the using-declaration consists of actual
7291 // constructors and notional constructors that result from the
7292 // transformation of defaulted parameters as follows:
7293 // - all non-template default constructors of X, and
7294 // - for each non-template constructor of X that has at least one
7295 // parameter with a default argument, the set of constructors that
7296 // results from omitting any ellipsis parameter specification and
7297 // successively omitting parameters with a default argument from the
7298 // end of the parameter-type-list.
7299 CXXConstructorDecl *BaseCtor = *CtorIt;
7300 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
7301 const FunctionProtoType *BaseCtorType =
7302 BaseCtor->getType()->getAs<FunctionProtoType>();
7303
7304 for (unsigned params = BaseCtor->getMinRequiredArguments(),
7305 maxParams = BaseCtor->getNumParams();
7306 params <= maxParams; ++params) {
7307 // Skip default constructors. They're never inherited.
7308 if (params == 0)
7309 continue;
7310 // Skip copy and move constructors for the same reason.
7311 if (CanBeCopyOrMove && params == 1)
7312 continue;
7313
7314 // Build up a function type for this particular constructor.
7315 // FIXME: The working paper does not consider that the exception spec
7316 // for the inheriting constructor might be larger than that of the
Richard Smith7a614d82011-06-11 17:19:42 +00007317 // source. This code doesn't yet, either. When it does, this code will
7318 // need to be delayed until after exception specifications and in-class
7319 // member initializers are attached.
Sebastian Redlf677ea32011-02-05 19:23:19 +00007320 const Type *NewCtorType;
7321 if (params == maxParams)
7322 NewCtorType = BaseCtorType;
7323 else {
Chris Lattner5f9e2722011-07-23 10:55:15 +00007324 SmallVector<QualType, 16> Args;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007325 for (unsigned i = 0; i < params; ++i) {
7326 Args.push_back(BaseCtorType->getArgType(i));
7327 }
7328 FunctionProtoType::ExtProtoInfo ExtInfo =
7329 BaseCtorType->getExtProtoInfo();
7330 ExtInfo.Variadic = false;
7331 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
7332 Args.data(), params, ExtInfo)
7333 .getTypePtr();
7334 }
7335 const Type *CanonicalNewCtorType =
7336 Context.getCanonicalType(NewCtorType);
7337
7338 // Now that we have the type, first check if the class already has a
7339 // constructor with this signature.
7340 if (ExistingConstructors.count(CanonicalNewCtorType))
7341 continue;
7342
7343 // Then we check if we have already declared an inherited constructor
7344 // with this signature.
7345 std::pair<ConstructorToSourceMap::iterator, bool> result =
7346 InheritedConstructors.insert(std::make_pair(
7347 CanonicalNewCtorType,
7348 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
7349 if (!result.second) {
7350 // Already in the map. If it came from a different class, that's an
7351 // error. Not if it's from the same.
7352 CanQualType PreviousBase = result.first->second.first;
7353 if (CanonicalBase != PreviousBase) {
7354 const CXXConstructorDecl *PrevCtor = result.first->second.second;
7355 const CXXConstructorDecl *PrevBaseCtor =
7356 PrevCtor->getInheritedConstructor();
7357 assert(PrevBaseCtor && "Conflicting constructor was not inherited");
7358
7359 Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
7360 Diag(BaseCtor->getLocation(),
7361 diag::note_using_decl_constructor_conflict_current_ctor);
7362 Diag(PrevBaseCtor->getLocation(),
7363 diag::note_using_decl_constructor_conflict_previous_ctor);
7364 Diag(PrevCtor->getLocation(),
7365 diag::note_using_decl_constructor_conflict_previous_using);
7366 }
7367 continue;
7368 }
7369
7370 // OK, we're there, now add the constructor.
7371 // C++0x [class.inhctor]p8: [...] that would be performed by a
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007372 // user-written inline constructor [...]
Sebastian Redlf677ea32011-02-05 19:23:19 +00007373 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
7374 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007375 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
7376 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007377 /*ImplicitlyDeclared=*/true,
7378 // FIXME: Due to a defect in the standard, we treat inherited
7379 // constructors as constexpr even if that makes them ill-formed.
7380 /*Constexpr=*/BaseCtor->isConstexpr());
Sebastian Redlf677ea32011-02-05 19:23:19 +00007381 NewCtor->setAccess(BaseCtor->getAccess());
7382
7383 // Build up the parameter decls and add them.
Chris Lattner5f9e2722011-07-23 10:55:15 +00007384 SmallVector<ParmVarDecl *, 16> ParamDecls;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007385 for (unsigned i = 0; i < params; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007386 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
7387 UsingLoc, UsingLoc,
Sebastian Redlf677ea32011-02-05 19:23:19 +00007388 /*IdentifierInfo=*/0,
7389 BaseCtorType->getArgType(i),
7390 /*TInfo=*/0, SC_None,
7391 SC_None, /*DefaultArg=*/0));
7392 }
David Blaikie4278c652011-09-21 18:16:56 +00007393 NewCtor->setParams(ParamDecls);
Sebastian Redlf677ea32011-02-05 19:23:19 +00007394 NewCtor->setInheritedConstructor(BaseCtor);
7395
7396 PushOnScopeChains(NewCtor, S, false);
7397 ClassDecl->addDecl(NewCtor);
7398 result.first->second.second = NewCtor;
7399 }
7400 }
7401 }
7402}
7403
Sean Huntcb45a0f2011-05-12 22:46:25 +00007404Sema::ImplicitExceptionSpecification
7405Sema::ComputeDefaultedDtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007406 // C++ [except.spec]p14:
7407 // An implicitly declared special member function (Clause 12) shall have
7408 // an exception-specification.
7409 ImplicitExceptionSpecification ExceptSpec(Context);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007410 if (ClassDecl->isInvalidDecl())
7411 return ExceptSpec;
7412
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007413 // Direct base-class destructors.
7414 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7415 BEnd = ClassDecl->bases_end();
7416 B != BEnd; ++B) {
7417 if (B->isVirtual()) // Handled below.
7418 continue;
7419
7420 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
7421 ExceptSpec.CalledDecl(
Sebastian Redl0ee33912011-05-19 05:13:44 +00007422 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007423 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00007424
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007425 // Virtual base-class destructors.
7426 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7427 BEnd = ClassDecl->vbases_end();
7428 B != BEnd; ++B) {
7429 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
7430 ExceptSpec.CalledDecl(
Sebastian Redl0ee33912011-05-19 05:13:44 +00007431 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007432 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00007433
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007434 // Field destructors.
7435 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7436 FEnd = ClassDecl->field_end();
7437 F != FEnd; ++F) {
7438 if (const RecordType *RecordTy
7439 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
7440 ExceptSpec.CalledDecl(
Sebastian Redl0ee33912011-05-19 05:13:44 +00007441 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007442 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007443
Sean Huntcb45a0f2011-05-12 22:46:25 +00007444 return ExceptSpec;
7445}
7446
7447CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
7448 // C++ [class.dtor]p2:
7449 // If a class has no user-declared destructor, a destructor is
7450 // declared implicitly. An implicitly-declared destructor is an
7451 // inline public member of its class.
7452
7453 ImplicitExceptionSpecification Spec =
Sebastian Redl0ee33912011-05-19 05:13:44 +00007454 ComputeDefaultedDtorExceptionSpec(ClassDecl);
Sean Huntcb45a0f2011-05-12 22:46:25 +00007455 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
7456
Douglas Gregor4923aa22010-07-02 20:37:36 +00007457 // Create the actual destructor declaration.
John McCalle23cf432010-12-14 08:05:40 +00007458 QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Sebastian Redl60618fa2011-03-12 11:50:43 +00007459
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007460 CanQualType ClassType
7461 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007462 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007463 DeclarationName Name
7464 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007465 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007466 CXXDestructorDecl *Destructor
Sebastian Redl60618fa2011-03-12 11:50:43 +00007467 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, Ty, 0,
7468 /*isInline=*/true,
7469 /*isImplicitlyDeclared=*/true);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007470 Destructor->setAccess(AS_public);
Sean Huntcb45a0f2011-05-12 22:46:25 +00007471 Destructor->setDefaulted();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007472 Destructor->setImplicit();
7473 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor4923aa22010-07-02 20:37:36 +00007474
7475 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00007476 ++ASTContext::NumImplicitDestructorsDeclared;
7477
7478 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00007479 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00007480 PushOnScopeChains(Destructor, S, false);
7481 ClassDecl->addDecl(Destructor);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007482
7483 // This could be uniqued if it ever proves significant.
7484 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
Sean Huntcb45a0f2011-05-12 22:46:25 +00007485
7486 if (ShouldDeleteDestructor(Destructor))
7487 Destructor->setDeletedAsWritten();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007488
7489 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor4923aa22010-07-02 20:37:36 +00007490
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007491 return Destructor;
7492}
7493
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007494void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00007495 CXXDestructorDecl *Destructor) {
Sean Huntcd10dec2011-05-23 23:14:04 +00007496 assert((Destructor->isDefaulted() &&
7497 !Destructor->doesThisDeclarationHaveABody()) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007498 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00007499 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007500 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007501
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007502 if (Destructor->isInvalidDecl())
7503 return;
7504
Douglas Gregor39957dc2010-05-01 15:04:51 +00007505 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007506
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007507 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00007508 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
7509 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00007510
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007511 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00007512 Diag(CurrentLocation, diag::note_member_synthesized_at)
7513 << CXXDestructor << Context.getTagDeclType(ClassDecl);
7514
7515 Destructor->setInvalidDecl();
7516 return;
7517 }
7518
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007519 SourceLocation Loc = Destructor->getLocation();
7520 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
Douglas Gregor690b2db2011-09-22 20:32:43 +00007521 Destructor->setImplicitlyDefined(true);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007522 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007523 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007524
7525 if (ASTMutationListener *L = getASTMutationListener()) {
7526 L->CompletedImplicitDefinition(Destructor);
7527 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007528}
7529
Sebastian Redl0ee33912011-05-19 05:13:44 +00007530void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *classDecl,
7531 CXXDestructorDecl *destructor) {
7532 // C++11 [class.dtor]p3:
7533 // A declaration of a destructor that does not have an exception-
7534 // specification is implicitly considered to have the same exception-
7535 // specification as an implicit declaration.
7536 const FunctionProtoType *dtorType = destructor->getType()->
7537 getAs<FunctionProtoType>();
7538 if (dtorType->hasExceptionSpec())
7539 return;
7540
7541 ImplicitExceptionSpecification exceptSpec =
7542 ComputeDefaultedDtorExceptionSpec(classDecl);
7543
Chandler Carruth3f224b22011-09-20 04:55:26 +00007544 // Replace the destructor's type, building off the existing one. Fortunately,
7545 // the only thing of interest in the destructor type is its extended info.
7546 // The return and arguments are fixed.
7547 FunctionProtoType::ExtProtoInfo epi = dtorType->getExtProtoInfo();
Sebastian Redl0ee33912011-05-19 05:13:44 +00007548 epi.ExceptionSpecType = exceptSpec.getExceptionSpecType();
7549 epi.NumExceptions = exceptSpec.size();
7550 epi.Exceptions = exceptSpec.data();
7551 QualType ty = Context.getFunctionType(Context.VoidTy, 0, 0, epi);
7552
7553 destructor->setType(ty);
7554
7555 // FIXME: If the destructor has a body that could throw, and the newly created
7556 // spec doesn't allow exceptions, we should emit a warning, because this
7557 // change in behavior can break conforming C++03 programs at runtime.
7558 // However, we don't have a body yet, so it needs to be done somewhere else.
7559}
7560
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007561/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregor06a9f362010-05-01 20:49:11 +00007562/// \c To.
7563///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007564/// This routine is used to copy/move the members of a class with an
7565/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregor06a9f362010-05-01 20:49:11 +00007566/// copied are arrays, this routine builds for loops to copy them.
7567///
7568/// \param S The Sema object used for type-checking.
7569///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007570/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007571///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007572/// \param T The type of the expressions being copied/moved. Both expressions
7573/// must have this type.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007574///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007575/// \param To The expression we are copying/moving to.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007576///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007577/// \param From The expression we are copying/moving from.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007578///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007579/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor6cdc1612010-05-04 15:20:55 +00007580/// Otherwise, it's a non-static member subobject.
7581///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007582/// \param Copying Whether we're copying or moving.
7583///
Douglas Gregor06a9f362010-05-01 20:49:11 +00007584/// \param Depth Internal parameter recording the depth of the recursion.
7585///
7586/// \returns A statement or a loop that copies the expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00007587static StmtResult
Douglas Gregor06a9f362010-05-01 20:49:11 +00007588BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCall9ae2f072010-08-23 23:25:46 +00007589 Expr *To, Expr *From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007590 bool CopyingBaseSubobject, bool Copying,
7591 unsigned Depth = 0) {
7592 // C++0x [class.copy]p28:
Douglas Gregor06a9f362010-05-01 20:49:11 +00007593 // Each subobject is assigned in the manner appropriate to its type:
7594 //
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007595 // - if the subobject is of class type, as if by a call to operator= with
7596 // the subobject as the object expression and the corresponding
7597 // subobject of x as a single function argument (as if by explicit
7598 // qualification; that is, ignoring any possible virtual overriding
7599 // functions in more derived classes);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007600 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
7601 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7602
7603 // Look for operator=.
7604 DeclarationName Name
7605 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
7606 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
7607 S.LookupQualifiedName(OpLookup, ClassDecl, false);
7608
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007609 // Filter out any result that isn't a copy/move-assignment operator.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007610 LookupResult::Filter F = OpLookup.makeFilter();
7611 while (F.hasNext()) {
7612 NamedDecl *D = F.next();
7613 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007614 if (Copying ? Method->isCopyAssignmentOperator() :
7615 Method->isMoveAssignmentOperator())
Douglas Gregor06a9f362010-05-01 20:49:11 +00007616 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007617
Douglas Gregor06a9f362010-05-01 20:49:11 +00007618 F.erase();
John McCallb0207482010-03-16 06:11:48 +00007619 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007620 F.done();
7621
Douglas Gregor6cdc1612010-05-04 15:20:55 +00007622 // Suppress the protected check (C++ [class.protected]) for each of the
7623 // assignment operators we found. This strange dance is required when
7624 // we're assigning via a base classes's copy-assignment operator. To
7625 // ensure that we're getting the right base class subobject (without
7626 // ambiguities), we need to cast "this" to that subobject type; to
7627 // ensure that we don't go through the virtual call mechanism, we need
7628 // to qualify the operator= name with the base class (see below). However,
7629 // this means that if the base class has a protected copy assignment
7630 // operator, the protected member access check will fail. So, we
7631 // rewrite "protected" access to "public" access in this case, since we
7632 // know by construction that we're calling from a derived class.
7633 if (CopyingBaseSubobject) {
7634 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
7635 L != LEnd; ++L) {
7636 if (L.getAccess() == AS_protected)
7637 L.setAccess(AS_public);
7638 }
7639 }
7640
Douglas Gregor06a9f362010-05-01 20:49:11 +00007641 // Create the nested-name-specifier that will be used to qualify the
7642 // reference to operator=; this is required to suppress the virtual
7643 // call mechanism.
7644 CXXScopeSpec SS;
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00007645 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Douglas Gregorc34348a2011-02-24 17:54:50 +00007646 SS.MakeTrivial(S.Context,
7647 NestedNameSpecifier::Create(S.Context, 0, false,
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00007648 CanonicalT),
Douglas Gregorc34348a2011-02-24 17:54:50 +00007649 Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007650
7651 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00007652 ExprResult OpEqualRef
John McCall9ae2f072010-08-23 23:25:46 +00007653 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00007654 /*TemplateKWLoc=*/SourceLocation(),
7655 /*FirstQualifierInScope=*/0,
7656 OpLookup,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007657 /*TemplateArgs=*/0,
7658 /*SuppressQualifierCheck=*/true);
7659 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007660 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007661
7662 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00007663
John McCall60d7b3a2010-08-24 06:29:42 +00007664 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00007665 OpEqualRef.takeAs<Expr>(),
7666 Loc, &From, 1, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007667 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007668 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007669
7670 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007671 }
John McCallb0207482010-03-16 06:11:48 +00007672
Douglas Gregor06a9f362010-05-01 20:49:11 +00007673 // - if the subobject is of scalar type, the built-in assignment
7674 // operator is used.
7675 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
7676 if (!ArrayTy) {
John McCall2de56d12010-08-25 11:45:40 +00007677 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007678 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007679 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007680
7681 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007682 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007683
7684 // - if the subobject is an array, each element is assigned, in the
7685 // manner appropriate to the element type;
7686
7687 // Construct a loop over the array bounds, e.g.,
7688 //
7689 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
7690 //
7691 // that will copy each of the array elements.
7692 QualType SizeType = S.Context.getSizeType();
7693
7694 // Create the iteration variable.
7695 IdentifierInfo *IterationVarName = 0;
7696 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00007697 SmallString<8> Str;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007698 llvm::raw_svector_ostream OS(Str);
7699 OS << "__i" << Depth;
7700 IterationVarName = &S.Context.Idents.get(OS.str());
7701 }
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007702 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007703 IterationVarName, SizeType,
7704 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00007705 SC_None, SC_None);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007706
7707 // Initialize the iteration variable to zero.
7708 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00007709 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00007710
7711 // Create a reference to the iteration variable; we'll use this several
7712 // times throughout.
7713 Expr *IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00007714 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007715 assert(IterationVarRef && "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00007716 Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take();
7717 assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!");
7718
Douglas Gregor06a9f362010-05-01 20:49:11 +00007719 // Create the DeclStmt that holds the iteration variable.
7720 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
7721
7722 // Create the comparison against the array bound.
Jay Foad9f71a8f2010-12-07 08:25:34 +00007723 llvm::APInt Upper
7724 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCall9ae2f072010-08-23 23:25:46 +00007725 Expr *Comparison
Eli Friedman8c382062012-01-23 02:35:22 +00007726 = new (S.Context) BinaryOperator(IterationVarRefRVal,
John McCallf89e55a2010-11-18 06:31:45 +00007727 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
7728 BO_NE, S.Context.BoolTy,
7729 VK_RValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007730
7731 // Create the pre-increment of the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00007732 Expr *Increment
John McCallf89e55a2010-11-18 06:31:45 +00007733 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
7734 VK_LValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007735
7736 // Subscript the "from" and "to" expressions with the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00007737 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00007738 IterationVarRefRVal,
7739 Loc));
John McCall9ae2f072010-08-23 23:25:46 +00007740 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00007741 IterationVarRefRVal,
7742 Loc));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007743 if (!Copying) // Cast to rvalue
7744 From = CastForMoving(S, From);
7745
7746 // Build the copy/move for an individual element of the array.
John McCallf89e55a2010-11-18 06:31:45 +00007747 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
7748 To, From, CopyingBaseSubobject,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007749 Copying, Depth + 1);
Douglas Gregorff331c12010-07-25 18:17:45 +00007750 if (Copy.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007751 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007752
7753 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00007754 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007755 S.MakeFullExpr(Comparison),
John McCalld226f652010-08-21 09:40:31 +00007756 0, S.MakeFullExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00007757 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007758}
7759
Sean Hunt30de05c2011-05-14 05:23:20 +00007760std::pair<Sema::ImplicitExceptionSpecification, bool>
7761Sema::ComputeDefaultedCopyAssignmentExceptionSpecAndConst(
7762 CXXRecordDecl *ClassDecl) {
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007763 if (ClassDecl->isInvalidDecl())
7764 return std::make_pair(ImplicitExceptionSpecification(Context), false);
7765
Douglas Gregord3c35902010-07-01 16:36:15 +00007766 // C++ [class.copy]p10:
7767 // If the class definition does not explicitly declare a copy
7768 // assignment operator, one is declared implicitly.
7769 // The implicitly-defined copy assignment operator for a class X
7770 // will have the form
7771 //
7772 // X& X::operator=(const X&)
7773 //
7774 // if
7775 bool HasConstCopyAssignment = true;
7776
7777 // -- each direct base class B of X has a copy assignment operator
7778 // whose parameter is of type const B&, const volatile B& or B,
7779 // and
7780 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7781 BaseEnd = ClassDecl->bases_end();
7782 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00007783 // We'll handle this below
7784 if (LangOpts.CPlusPlus0x && Base->isVirtual())
7785 continue;
7786
Douglas Gregord3c35902010-07-01 16:36:15 +00007787 assert(!Base->getType()->isDependentType() &&
7788 "Cannot generate implicit members for class with dependent bases.");
Sean Hunt661c67a2011-06-21 23:42:56 +00007789 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
7790 LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
7791 &HasConstCopyAssignment);
7792 }
7793
Richard Smithebaf0e62011-10-18 20:49:44 +00007794 // In C++11, the above citation has "or virtual" added
Sean Hunt661c67a2011-06-21 23:42:56 +00007795 if (LangOpts.CPlusPlus0x) {
7796 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7797 BaseEnd = ClassDecl->vbases_end();
7798 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
7799 assert(!Base->getType()->isDependentType() &&
7800 "Cannot generate implicit members for class with dependent bases.");
7801 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
7802 LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
7803 &HasConstCopyAssignment);
7804 }
Douglas Gregord3c35902010-07-01 16:36:15 +00007805 }
7806
7807 // -- for all the nonstatic data members of X that are of a class
7808 // type M (or array thereof), each such class type has a copy
7809 // assignment operator whose parameter is of type const M&,
7810 // const volatile M& or M.
7811 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7812 FieldEnd = ClassDecl->field_end();
7813 HasConstCopyAssignment && Field != FieldEnd;
7814 ++Field) {
7815 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00007816 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7817 LookupCopyingAssignment(FieldClassDecl, Qualifiers::Const, false, 0,
7818 &HasConstCopyAssignment);
Douglas Gregord3c35902010-07-01 16:36:15 +00007819 }
7820 }
7821
7822 // Otherwise, the implicitly declared copy assignment operator will
7823 // have the form
7824 //
7825 // X& X::operator=(X&)
Douglas Gregord3c35902010-07-01 16:36:15 +00007826
Douglas Gregorb87786f2010-07-01 17:48:08 +00007827 // C++ [except.spec]p14:
7828 // An implicitly declared special member function (Clause 12) shall have an
7829 // exception-specification. [...]
Sean Hunt661c67a2011-06-21 23:42:56 +00007830
7831 // It is unspecified whether or not an implicit copy assignment operator
7832 // attempts to deduplicate calls to assignment operators of virtual bases are
7833 // made. As such, this exception specification is effectively unspecified.
7834 // Based on a similar decision made for constness in C++0x, we're erring on
7835 // the side of assuming such calls to be made regardless of whether they
7836 // actually happen.
Douglas Gregorb87786f2010-07-01 17:48:08 +00007837 ImplicitExceptionSpecification ExceptSpec(Context);
Sean Hunt661c67a2011-06-21 23:42:56 +00007838 unsigned ArgQuals = HasConstCopyAssignment ? Qualifiers::Const : 0;
Douglas Gregorb87786f2010-07-01 17:48:08 +00007839 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7840 BaseEnd = ClassDecl->bases_end();
7841 Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00007842 if (Base->isVirtual())
7843 continue;
7844
Douglas Gregora376d102010-07-02 21:50:04 +00007845 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00007846 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00007847 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7848 ArgQuals, false, 0))
Douglas Gregorb87786f2010-07-01 17:48:08 +00007849 ExceptSpec.CalledDecl(CopyAssign);
7850 }
Sean Hunt661c67a2011-06-21 23:42:56 +00007851
7852 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7853 BaseEnd = ClassDecl->vbases_end();
7854 Base != BaseEnd; ++Base) {
7855 CXXRecordDecl *BaseClassDecl
7856 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7857 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7858 ArgQuals, false, 0))
7859 ExceptSpec.CalledDecl(CopyAssign);
7860 }
7861
Douglas Gregorb87786f2010-07-01 17:48:08 +00007862 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7863 FieldEnd = ClassDecl->field_end();
7864 Field != FieldEnd;
7865 ++Field) {
7866 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00007867 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7868 if (CXXMethodDecl *CopyAssign =
7869 LookupCopyingAssignment(FieldClassDecl, ArgQuals, false, 0))
7870 ExceptSpec.CalledDecl(CopyAssign);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007871 }
Douglas Gregorb87786f2010-07-01 17:48:08 +00007872 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007873
Sean Hunt30de05c2011-05-14 05:23:20 +00007874 return std::make_pair(ExceptSpec, HasConstCopyAssignment);
7875}
7876
7877CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
7878 // Note: The following rules are largely analoguous to the copy
7879 // constructor rules. Note that virtual bases are not taken into account
7880 // for determining the argument type of the operator. Note also that
7881 // operators taking an object instead of a reference are allowed.
7882
7883 ImplicitExceptionSpecification Spec(Context);
7884 bool Const;
7885 llvm::tie(Spec, Const) =
7886 ComputeDefaultedCopyAssignmentExceptionSpecAndConst(ClassDecl);
7887
7888 QualType ArgType = Context.getTypeDeclType(ClassDecl);
7889 QualType RetType = Context.getLValueReferenceType(ArgType);
7890 if (Const)
7891 ArgType = ArgType.withConst();
7892 ArgType = Context.getLValueReferenceType(ArgType);
7893
Douglas Gregord3c35902010-07-01 16:36:15 +00007894 // An implicitly-declared copy assignment operator is an inline public
7895 // member of its class.
Sean Hunt30de05c2011-05-14 05:23:20 +00007896 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Douglas Gregord3c35902010-07-01 16:36:15 +00007897 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007898 SourceLocation ClassLoc = ClassDecl->getLocation();
7899 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregord3c35902010-07-01 16:36:15 +00007900 CXXMethodDecl *CopyAssignment
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007901 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
John McCalle23cf432010-12-14 08:05:40 +00007902 Context.getFunctionType(RetType, &ArgType, 1, EPI),
Douglas Gregord3c35902010-07-01 16:36:15 +00007903 /*TInfo=*/0, /*isStatic=*/false,
John McCalld931b082010-08-26 03:08:43 +00007904 /*StorageClassAsWritten=*/SC_None,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007905 /*isInline=*/true, /*isConstexpr=*/false,
Douglas Gregorf5251602011-03-08 17:10:18 +00007906 SourceLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00007907 CopyAssignment->setAccess(AS_public);
Sean Hunt7f410192011-05-14 05:23:24 +00007908 CopyAssignment->setDefaulted();
Douglas Gregord3c35902010-07-01 16:36:15 +00007909 CopyAssignment->setImplicit();
7910 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Douglas Gregord3c35902010-07-01 16:36:15 +00007911
7912 // Add the parameter to the operator.
7913 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007914 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregord3c35902010-07-01 16:36:15 +00007915 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00007916 SC_None,
7917 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00007918 CopyAssignment->setParams(FromParam);
Douglas Gregord3c35902010-07-01 16:36:15 +00007919
Douglas Gregora376d102010-07-02 21:50:04 +00007920 // Note that we have added this copy-assignment operator.
Douglas Gregora376d102010-07-02 21:50:04 +00007921 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Sean Hunt7f410192011-05-14 05:23:24 +00007922
Douglas Gregor23c94db2010-07-02 17:43:08 +00007923 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora376d102010-07-02 21:50:04 +00007924 PushOnScopeChains(CopyAssignment, S, false);
7925 ClassDecl->addDecl(CopyAssignment);
Douglas Gregord3c35902010-07-01 16:36:15 +00007926
Nico Weberafcc96a2012-01-23 03:19:29 +00007927 // C++0x [class.copy]p19:
7928 // .... If the class definition does not explicitly declare a copy
7929 // assignment operator, there is no user-declared move constructor, and
7930 // there is no user-declared move assignment operator, a copy assignment
7931 // operator is implicitly declared as defaulted.
7932 if ((ClassDecl->hasUserDeclaredMoveConstructor() &&
Nico Weber28976602012-01-23 04:01:33 +00007933 !getLangOptions().MicrosoftMode) ||
7934 ClassDecl->hasUserDeclaredMoveAssignment() ||
Sean Hunt1ccbc542011-06-22 01:05:13 +00007935 ShouldDeleteCopyAssignmentOperator(CopyAssignment))
Sean Hunt71a682f2011-05-18 03:41:58 +00007936 CopyAssignment->setDeletedAsWritten();
7937
Douglas Gregord3c35902010-07-01 16:36:15 +00007938 AddOverriddenMethods(ClassDecl, CopyAssignment);
7939 return CopyAssignment;
7940}
7941
Douglas Gregor06a9f362010-05-01 20:49:11 +00007942void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
7943 CXXMethodDecl *CopyAssignOperator) {
Sean Hunt7f410192011-05-14 05:23:24 +00007944 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00007945 CopyAssignOperator->isOverloadedOperator() &&
7946 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Sean Huntcd10dec2011-05-23 23:14:04 +00007947 !CopyAssignOperator->doesThisDeclarationHaveABody()) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00007948 "DefineImplicitCopyAssignment called for wrong function");
7949
7950 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
7951
7952 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
7953 CopyAssignOperator->setInvalidDecl();
7954 return;
7955 }
7956
7957 CopyAssignOperator->setUsed();
7958
7959 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007960 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007961
7962 // C++0x [class.copy]p30:
7963 // The implicitly-defined or explicitly-defaulted copy assignment operator
7964 // for a non-union class X performs memberwise copy assignment of its
7965 // subobjects. The direct base classes of X are assigned first, in the
7966 // order of their declaration in the base-specifier-list, and then the
7967 // immediate non-static data members of X are assigned, in the order in
7968 // which they were declared in the class definition.
7969
7970 // The statements that form the synthesized function body.
John McCallca0408f2010-08-23 06:44:23 +00007971 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007972
7973 // The parameter for the "other" object, which we are copying from.
7974 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
7975 Qualifiers OtherQuals = Other->getType().getQualifiers();
7976 QualType OtherRefType = Other->getType();
7977 if (const LValueReferenceType *OtherRef
7978 = OtherRefType->getAs<LValueReferenceType>()) {
7979 OtherRefType = OtherRef->getPointeeType();
7980 OtherQuals = OtherRefType.getQualifiers();
7981 }
7982
7983 // Our location for everything implicitly-generated.
7984 SourceLocation Loc = CopyAssignOperator->getLocation();
7985
7986 // Construct a reference to the "other" object. We'll be using this
7987 // throughout the generated ASTs.
John McCall09431682010-11-18 19:01:18 +00007988 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007989 assert(OtherRef && "Reference to parameter cannot fail!");
7990
7991 // Construct the "this" pointer. We'll be using this throughout the generated
7992 // ASTs.
7993 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
7994 assert(This && "Reference to this cannot fail!");
7995
7996 // Assign base classes.
7997 bool Invalid = false;
7998 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7999 E = ClassDecl->bases_end(); Base != E; ++Base) {
8000 // Form the assignment:
8001 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
8002 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00008003 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00008004 Invalid = true;
8005 continue;
8006 }
8007
John McCallf871d0c2010-08-07 06:22:56 +00008008 CXXCastPath BasePath;
8009 BasePath.push_back(Base);
8010
Douglas Gregor06a9f362010-05-01 20:49:11 +00008011 // Construct the "from" expression, which is an implicit cast to the
8012 // appropriately-qualified base type.
John McCall3fa5cae2010-10-26 07:05:15 +00008013 Expr *From = OtherRef;
John Wiegley429bb272011-04-08 18:41:53 +00008014 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
8015 CK_UncheckedDerivedToBase,
8016 VK_LValue, &BasePath).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008017
8018 // Dereference "this".
John McCall5baba9d2010-08-25 10:28:54 +00008019 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008020
8021 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley429bb272011-04-08 18:41:53 +00008022 To = ImpCastExprToType(To.take(),
8023 Context.getCVRQualifiedType(BaseType,
8024 CopyAssignOperator->getTypeQualifiers()),
8025 CK_UncheckedDerivedToBase,
8026 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008027
8028 // Build the copy.
John McCall60d7b3a2010-08-24 06:29:42 +00008029 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00008030 To.get(), From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008031 /*CopyingBaseSubobject=*/true,
8032 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008033 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008034 Diag(CurrentLocation, diag::note_member_synthesized_at)
8035 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8036 CopyAssignOperator->setInvalidDecl();
8037 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008038 }
8039
8040 // Success! Record the copy.
8041 Statements.push_back(Copy.takeAs<Expr>());
8042 }
8043
8044 // \brief Reference to the __builtin_memcpy function.
8045 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00008046 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00008047 Expr *CollectableMemCpyRef = 0;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008048
8049 // Assign non-static members.
8050 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8051 FieldEnd = ClassDecl->field_end();
8052 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00008053 if (Field->isUnnamedBitfield())
8054 continue;
8055
Douglas Gregor06a9f362010-05-01 20:49:11 +00008056 // Check for members of reference type; we can't copy those.
8057 if (Field->getType()->isReferenceType()) {
8058 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8059 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8060 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008061 Diag(CurrentLocation, diag::note_member_synthesized_at)
8062 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008063 Invalid = true;
8064 continue;
8065 }
8066
8067 // Check for members of const-qualified, non-class type.
8068 QualType BaseType = Context.getBaseElementType(Field->getType());
8069 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8070 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8071 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8072 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008073 Diag(CurrentLocation, diag::note_member_synthesized_at)
8074 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008075 Invalid = true;
8076 continue;
8077 }
John McCallb77115d2011-06-17 00:18:42 +00008078
8079 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00008080 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8081 continue;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008082
8083 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00008084 if (FieldType->isIncompleteArrayType()) {
8085 assert(ClassDecl->hasFlexibleArrayMember() &&
8086 "Incomplete array type is not valid");
8087 continue;
8088 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008089
8090 // Build references to the field in the object we're copying from and to.
8091 CXXScopeSpec SS; // Intentionally empty
8092 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8093 LookupMemberName);
8094 MemberLookup.addDecl(*Field);
8095 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00008096 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall09431682010-11-18 19:01:18 +00008097 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008098 SS, SourceLocation(), 0,
8099 MemberLookup, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00008100 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall09431682010-11-18 19:01:18 +00008101 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008102 SS, SourceLocation(), 0,
8103 MemberLookup, 0);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008104 assert(!From.isInvalid() && "Implicit field reference cannot fail");
8105 assert(!To.isInvalid() && "Implicit field reference cannot fail");
8106
8107 // If the field should be copied with __builtin_memcpy rather than via
8108 // explicit assignments, do so. This optimization only applies for arrays
8109 // of scalars and arrays of class type with trivial copy-assignment
8110 // operators.
Fariborz Jahanian6b167f42011-08-09 00:26:11 +00008111 if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008112 && BaseType.hasTrivialAssignment(Context, /*Copying=*/true)) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00008113 // Compute the size of the memory buffer to be copied.
8114 QualType SizeType = Context.getSizeType();
8115 llvm::APInt Size(Context.getTypeSize(SizeType),
8116 Context.getTypeSizeInChars(BaseType).getQuantity());
8117 for (const ConstantArrayType *Array
8118 = Context.getAsConstantArrayType(FieldType);
8119 Array;
8120 Array = Context.getAsConstantArrayType(Array->getElementType())) {
Jay Foad9f71a8f2010-12-07 08:25:34 +00008121 llvm::APInt ArraySize
8122 = Array->getSize().zextOrTrunc(Size.getBitWidth());
Douglas Gregor06a9f362010-05-01 20:49:11 +00008123 Size *= ArraySize;
8124 }
8125
8126 // Take the address of the field references for "from" and "to".
John McCall2de56d12010-08-25 11:45:40 +00008127 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
8128 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00008129
8130 bool NeedsCollectableMemCpy =
8131 (BaseType->isRecordType() &&
8132 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
8133
8134 if (NeedsCollectableMemCpy) {
8135 if (!CollectableMemCpyRef) {
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00008136 // Create a reference to the __builtin_objc_memmove_collectable function.
8137 LookupResult R(*this,
8138 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00008139 Loc, LookupOrdinaryName);
8140 LookupName(R, TUScope, true);
8141
8142 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
8143 if (!CollectableMemCpy) {
8144 // Something went horribly wrong earlier, and we will have
8145 // complained about it.
8146 Invalid = true;
8147 continue;
8148 }
8149
8150 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
8151 CollectableMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00008152 VK_LValue, Loc, 0).take();
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00008153 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
8154 }
8155 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008156 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00008157 else if (!BuiltinMemCpyRef) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00008158 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
8159 LookupOrdinaryName);
8160 LookupName(R, TUScope, true);
8161
8162 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
8163 if (!BuiltinMemCpy) {
8164 // Something went horribly wrong earlier, and we will have complained
8165 // about it.
8166 Invalid = true;
8167 continue;
8168 }
8169
8170 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
8171 BuiltinMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00008172 VK_LValue, Loc, 0).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008173 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
8174 }
8175
John McCallca0408f2010-08-23 06:44:23 +00008176 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008177 CallArgs.push_back(To.takeAs<Expr>());
8178 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00008179 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCall60d7b3a2010-08-24 06:29:42 +00008180 ExprResult Call = ExprError();
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00008181 if (NeedsCollectableMemCpy)
8182 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00008183 CollectableMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00008184 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00008185 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00008186 else
8187 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00008188 BuiltinMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00008189 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00008190 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00008191
Douglas Gregor06a9f362010-05-01 20:49:11 +00008192 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8193 Statements.push_back(Call.takeAs<Expr>());
8194 continue;
8195 }
8196
8197 // Build the copy of this field.
John McCall60d7b3a2010-08-24 06:29:42 +00008198 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008199 To.get(), From.get(),
8200 /*CopyingBaseSubobject=*/false,
8201 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008202 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008203 Diag(CurrentLocation, diag::note_member_synthesized_at)
8204 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8205 CopyAssignOperator->setInvalidDecl();
8206 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008207 }
8208
8209 // Success! Record the copy.
8210 Statements.push_back(Copy.takeAs<Stmt>());
8211 }
8212
8213 if (!Invalid) {
8214 // Add a "return *this;"
John McCall2de56d12010-08-25 11:45:40 +00008215 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008216
John McCall60d7b3a2010-08-24 06:29:42 +00008217 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00008218 if (Return.isInvalid())
8219 Invalid = true;
8220 else {
8221 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008222
8223 if (Trap.hasErrorOccurred()) {
8224 Diag(CurrentLocation, diag::note_member_synthesized_at)
8225 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8226 Invalid = true;
8227 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008228 }
8229 }
8230
8231 if (Invalid) {
8232 CopyAssignOperator->setInvalidDecl();
8233 return;
8234 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008235
8236 StmtResult Body;
8237 {
8238 CompoundScopeRAII CompoundScope(*this);
8239 Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
8240 /*isStmtExpr=*/false);
8241 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8242 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008243 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008244
8245 if (ASTMutationListener *L = getASTMutationListener()) {
8246 L->CompletedImplicitDefinition(CopyAssignOperator);
8247 }
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008248}
8249
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008250Sema::ImplicitExceptionSpecification
8251Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXRecordDecl *ClassDecl) {
8252 ImplicitExceptionSpecification ExceptSpec(Context);
8253
8254 if (ClassDecl->isInvalidDecl())
8255 return ExceptSpec;
8256
8257 // C++0x [except.spec]p14:
8258 // An implicitly declared special member function (Clause 12) shall have an
8259 // exception-specification. [...]
8260
8261 // It is unspecified whether or not an implicit move assignment operator
8262 // attempts to deduplicate calls to assignment operators of virtual bases are
8263 // made. As such, this exception specification is effectively unspecified.
8264 // Based on a similar decision made for constness in C++0x, we're erring on
8265 // the side of assuming such calls to be made regardless of whether they
8266 // actually happen.
8267 // Note that a move constructor is not implicitly declared when there are
8268 // virtual bases, but it can still be user-declared and explicitly defaulted.
8269 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8270 BaseEnd = ClassDecl->bases_end();
8271 Base != BaseEnd; ++Base) {
8272 if (Base->isVirtual())
8273 continue;
8274
8275 CXXRecordDecl *BaseClassDecl
8276 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8277 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
8278 false, 0))
8279 ExceptSpec.CalledDecl(MoveAssign);
8280 }
8281
8282 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8283 BaseEnd = ClassDecl->vbases_end();
8284 Base != BaseEnd; ++Base) {
8285 CXXRecordDecl *BaseClassDecl
8286 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8287 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
8288 false, 0))
8289 ExceptSpec.CalledDecl(MoveAssign);
8290 }
8291
8292 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8293 FieldEnd = ClassDecl->field_end();
8294 Field != FieldEnd;
8295 ++Field) {
8296 QualType FieldType = Context.getBaseElementType((*Field)->getType());
8297 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8298 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(FieldClassDecl,
8299 false, 0))
8300 ExceptSpec.CalledDecl(MoveAssign);
8301 }
8302 }
8303
8304 return ExceptSpec;
8305}
8306
8307CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
8308 // Note: The following rules are largely analoguous to the move
8309 // constructor rules.
8310
8311 ImplicitExceptionSpecification Spec(
8312 ComputeDefaultedMoveAssignmentExceptionSpec(ClassDecl));
8313
8314 QualType ArgType = Context.getTypeDeclType(ClassDecl);
8315 QualType RetType = Context.getLValueReferenceType(ArgType);
8316 ArgType = Context.getRValueReferenceType(ArgType);
8317
8318 // An implicitly-declared move assignment operator is an inline public
8319 // member of its class.
8320 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8321 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8322 SourceLocation ClassLoc = ClassDecl->getLocation();
8323 DeclarationNameInfo NameInfo(Name, ClassLoc);
8324 CXXMethodDecl *MoveAssignment
8325 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8326 Context.getFunctionType(RetType, &ArgType, 1, EPI),
8327 /*TInfo=*/0, /*isStatic=*/false,
8328 /*StorageClassAsWritten=*/SC_None,
8329 /*isInline=*/true,
8330 /*isConstexpr=*/false,
8331 SourceLocation());
8332 MoveAssignment->setAccess(AS_public);
8333 MoveAssignment->setDefaulted();
8334 MoveAssignment->setImplicit();
8335 MoveAssignment->setTrivial(ClassDecl->hasTrivialMoveAssignment());
8336
8337 // Add the parameter to the operator.
8338 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
8339 ClassLoc, ClassLoc, /*Id=*/0,
8340 ArgType, /*TInfo=*/0,
8341 SC_None,
8342 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008343 MoveAssignment->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008344
8345 // Note that we have added this copy-assignment operator.
8346 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
8347
8348 // C++0x [class.copy]p9:
8349 // If the definition of a class X does not explicitly declare a move
8350 // assignment operator, one will be implicitly declared as defaulted if and
8351 // only if:
8352 // [...]
8353 // - the move assignment operator would not be implicitly defined as
8354 // deleted.
8355 if (ShouldDeleteMoveAssignmentOperator(MoveAssignment)) {
8356 // Cache this result so that we don't try to generate this over and over
8357 // on every lookup, leaking memory and wasting time.
8358 ClassDecl->setFailedImplicitMoveAssignment();
8359 return 0;
8360 }
8361
8362 if (Scope *S = getScopeForContext(ClassDecl))
8363 PushOnScopeChains(MoveAssignment, S, false);
8364 ClassDecl->addDecl(MoveAssignment);
8365
8366 AddOverriddenMethods(ClassDecl, MoveAssignment);
8367 return MoveAssignment;
8368}
8369
8370void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
8371 CXXMethodDecl *MoveAssignOperator) {
8372 assert((MoveAssignOperator->isDefaulted() &&
8373 MoveAssignOperator->isOverloadedOperator() &&
8374 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
8375 !MoveAssignOperator->doesThisDeclarationHaveABody()) &&
8376 "DefineImplicitMoveAssignment called for wrong function");
8377
8378 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
8379
8380 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
8381 MoveAssignOperator->setInvalidDecl();
8382 return;
8383 }
8384
8385 MoveAssignOperator->setUsed();
8386
8387 ImplicitlyDefinedFunctionScope Scope(*this, MoveAssignOperator);
8388 DiagnosticErrorTrap Trap(Diags);
8389
8390 // C++0x [class.copy]p28:
8391 // The implicitly-defined or move assignment operator for a non-union class
8392 // X performs memberwise move assignment of its subobjects. The direct base
8393 // classes of X are assigned first, in the order of their declaration in the
8394 // base-specifier-list, and then the immediate non-static data members of X
8395 // are assigned, in the order in which they were declared in the class
8396 // definition.
8397
8398 // The statements that form the synthesized function body.
8399 ASTOwningVector<Stmt*> Statements(*this);
8400
8401 // The parameter for the "other" object, which we are move from.
8402 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
8403 QualType OtherRefType = Other->getType()->
8404 getAs<RValueReferenceType>()->getPointeeType();
8405 assert(OtherRefType.getQualifiers() == 0 &&
8406 "Bad argument type of defaulted move assignment");
8407
8408 // Our location for everything implicitly-generated.
8409 SourceLocation Loc = MoveAssignOperator->getLocation();
8410
8411 // Construct a reference to the "other" object. We'll be using this
8412 // throughout the generated ASTs.
8413 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
8414 assert(OtherRef && "Reference to parameter cannot fail!");
8415 // Cast to rvalue.
8416 OtherRef = CastForMoving(*this, OtherRef);
8417
8418 // Construct the "this" pointer. We'll be using this throughout the generated
8419 // ASTs.
8420 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8421 assert(This && "Reference to this cannot fail!");
8422
8423 // Assign base classes.
8424 bool Invalid = false;
8425 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8426 E = ClassDecl->bases_end(); Base != E; ++Base) {
8427 // Form the assignment:
8428 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
8429 QualType BaseType = Base->getType().getUnqualifiedType();
8430 if (!BaseType->isRecordType()) {
8431 Invalid = true;
8432 continue;
8433 }
8434
8435 CXXCastPath BasePath;
8436 BasePath.push_back(Base);
8437
8438 // Construct the "from" expression, which is an implicit cast to the
8439 // appropriately-qualified base type.
8440 Expr *From = OtherRef;
8441 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
Douglas Gregorb2b56582011-09-06 16:26:56 +00008442 VK_XValue, &BasePath).take();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008443
8444 // Dereference "this".
8445 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8446
8447 // Implicitly cast "this" to the appropriately-qualified base type.
8448 To = ImpCastExprToType(To.take(),
8449 Context.getCVRQualifiedType(BaseType,
8450 MoveAssignOperator->getTypeQualifiers()),
8451 CK_UncheckedDerivedToBase,
8452 VK_LValue, &BasePath);
8453
8454 // Build the move.
8455 StmtResult Move = BuildSingleCopyAssign(*this, Loc, BaseType,
8456 To.get(), From,
8457 /*CopyingBaseSubobject=*/true,
8458 /*Copying=*/false);
8459 if (Move.isInvalid()) {
8460 Diag(CurrentLocation, diag::note_member_synthesized_at)
8461 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8462 MoveAssignOperator->setInvalidDecl();
8463 return;
8464 }
8465
8466 // Success! Record the move.
8467 Statements.push_back(Move.takeAs<Expr>());
8468 }
8469
8470 // \brief Reference to the __builtin_memcpy function.
8471 Expr *BuiltinMemCpyRef = 0;
8472 // \brief Reference to the __builtin_objc_memmove_collectable function.
8473 Expr *CollectableMemCpyRef = 0;
8474
8475 // Assign non-static members.
8476 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8477 FieldEnd = ClassDecl->field_end();
8478 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00008479 if (Field->isUnnamedBitfield())
8480 continue;
8481
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008482 // Check for members of reference type; we can't move those.
8483 if (Field->getType()->isReferenceType()) {
8484 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8485 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8486 Diag(Field->getLocation(), diag::note_declared_at);
8487 Diag(CurrentLocation, diag::note_member_synthesized_at)
8488 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8489 Invalid = true;
8490 continue;
8491 }
8492
8493 // Check for members of const-qualified, non-class type.
8494 QualType BaseType = Context.getBaseElementType(Field->getType());
8495 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8496 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8497 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8498 Diag(Field->getLocation(), diag::note_declared_at);
8499 Diag(CurrentLocation, diag::note_member_synthesized_at)
8500 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8501 Invalid = true;
8502 continue;
8503 }
8504
8505 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00008506 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8507 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008508
8509 QualType FieldType = Field->getType().getNonReferenceType();
8510 if (FieldType->isIncompleteArrayType()) {
8511 assert(ClassDecl->hasFlexibleArrayMember() &&
8512 "Incomplete array type is not valid");
8513 continue;
8514 }
8515
8516 // Build references to the field in the object we're copying from and to.
8517 CXXScopeSpec SS; // Intentionally empty
8518 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8519 LookupMemberName);
8520 MemberLookup.addDecl(*Field);
8521 MemberLookup.resolveKind();
8522 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
8523 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008524 SS, SourceLocation(), 0,
8525 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008526 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
8527 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008528 SS, SourceLocation(), 0,
8529 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008530 assert(!From.isInvalid() && "Implicit field reference cannot fail");
8531 assert(!To.isInvalid() && "Implicit field reference cannot fail");
8532
8533 assert(!From.get()->isLValue() && // could be xvalue or prvalue
8534 "Member reference with rvalue base must be rvalue except for reference "
8535 "members, which aren't allowed for move assignment.");
8536
8537 // If the field should be copied with __builtin_memcpy rather than via
8538 // explicit assignments, do so. This optimization only applies for arrays
8539 // of scalars and arrays of class type with trivial move-assignment
8540 // operators.
8541 if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
8542 && BaseType.hasTrivialAssignment(Context, /*Copying=*/false)) {
8543 // Compute the size of the memory buffer to be copied.
8544 QualType SizeType = Context.getSizeType();
8545 llvm::APInt Size(Context.getTypeSize(SizeType),
8546 Context.getTypeSizeInChars(BaseType).getQuantity());
8547 for (const ConstantArrayType *Array
8548 = Context.getAsConstantArrayType(FieldType);
8549 Array;
8550 Array = Context.getAsConstantArrayType(Array->getElementType())) {
8551 llvm::APInt ArraySize
8552 = Array->getSize().zextOrTrunc(Size.getBitWidth());
8553 Size *= ArraySize;
8554 }
8555
Douglas Gregor45d3d712011-09-01 02:09:07 +00008556 // Take the address of the field references for "from" and "to". We
8557 // directly construct UnaryOperators here because semantic analysis
8558 // does not permit us to take the address of an xvalue.
8559 From = new (Context) UnaryOperator(From.get(), UO_AddrOf,
8560 Context.getPointerType(From.get()->getType()),
8561 VK_RValue, OK_Ordinary, Loc);
8562 To = new (Context) UnaryOperator(To.get(), UO_AddrOf,
8563 Context.getPointerType(To.get()->getType()),
8564 VK_RValue, OK_Ordinary, Loc);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008565
8566 bool NeedsCollectableMemCpy =
8567 (BaseType->isRecordType() &&
8568 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
8569
8570 if (NeedsCollectableMemCpy) {
8571 if (!CollectableMemCpyRef) {
8572 // Create a reference to the __builtin_objc_memmove_collectable function.
8573 LookupResult R(*this,
8574 &Context.Idents.get("__builtin_objc_memmove_collectable"),
8575 Loc, LookupOrdinaryName);
8576 LookupName(R, TUScope, true);
8577
8578 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
8579 if (!CollectableMemCpy) {
8580 // Something went horribly wrong earlier, and we will have
8581 // complained about it.
8582 Invalid = true;
8583 continue;
8584 }
8585
8586 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
8587 CollectableMemCpy->getType(),
8588 VK_LValue, Loc, 0).take();
8589 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
8590 }
8591 }
8592 // Create a reference to the __builtin_memcpy builtin function.
8593 else if (!BuiltinMemCpyRef) {
8594 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
8595 LookupOrdinaryName);
8596 LookupName(R, TUScope, true);
8597
8598 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
8599 if (!BuiltinMemCpy) {
8600 // Something went horribly wrong earlier, and we will have complained
8601 // about it.
8602 Invalid = true;
8603 continue;
8604 }
8605
8606 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
8607 BuiltinMemCpy->getType(),
8608 VK_LValue, Loc, 0).take();
8609 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
8610 }
8611
8612 ASTOwningVector<Expr*> CallArgs(*this);
8613 CallArgs.push_back(To.takeAs<Expr>());
8614 CallArgs.push_back(From.takeAs<Expr>());
8615 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
8616 ExprResult Call = ExprError();
8617 if (NeedsCollectableMemCpy)
8618 Call = ActOnCallExpr(/*Scope=*/0,
8619 CollectableMemCpyRef,
8620 Loc, move_arg(CallArgs),
8621 Loc);
8622 else
8623 Call = ActOnCallExpr(/*Scope=*/0,
8624 BuiltinMemCpyRef,
8625 Loc, move_arg(CallArgs),
8626 Loc);
8627
8628 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8629 Statements.push_back(Call.takeAs<Expr>());
8630 continue;
8631 }
8632
8633 // Build the move of this field.
8634 StmtResult Move = BuildSingleCopyAssign(*this, Loc, FieldType,
8635 To.get(), From.get(),
8636 /*CopyingBaseSubobject=*/false,
8637 /*Copying=*/false);
8638 if (Move.isInvalid()) {
8639 Diag(CurrentLocation, diag::note_member_synthesized_at)
8640 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8641 MoveAssignOperator->setInvalidDecl();
8642 return;
8643 }
8644
8645 // Success! Record the copy.
8646 Statements.push_back(Move.takeAs<Stmt>());
8647 }
8648
8649 if (!Invalid) {
8650 // Add a "return *this;"
8651 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8652
8653 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
8654 if (Return.isInvalid())
8655 Invalid = true;
8656 else {
8657 Statements.push_back(Return.takeAs<Stmt>());
8658
8659 if (Trap.hasErrorOccurred()) {
8660 Diag(CurrentLocation, diag::note_member_synthesized_at)
8661 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8662 Invalid = true;
8663 }
8664 }
8665 }
8666
8667 if (Invalid) {
8668 MoveAssignOperator->setInvalidDecl();
8669 return;
8670 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008671
8672 StmtResult Body;
8673 {
8674 CompoundScopeRAII CompoundScope(*this);
8675 Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
8676 /*isStmtExpr=*/false);
8677 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8678 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008679 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
8680
8681 if (ASTMutationListener *L = getASTMutationListener()) {
8682 L->CompletedImplicitDefinition(MoveAssignOperator);
8683 }
8684}
8685
Sean Hunt49634cf2011-05-13 06:10:58 +00008686std::pair<Sema::ImplicitExceptionSpecification, bool>
8687Sema::ComputeDefaultedCopyCtorExceptionSpecAndConst(CXXRecordDecl *ClassDecl) {
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008688 if (ClassDecl->isInvalidDecl())
8689 return std::make_pair(ImplicitExceptionSpecification(Context), false);
8690
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008691 // C++ [class.copy]p5:
8692 // The implicitly-declared copy constructor for a class X will
8693 // have the form
8694 //
8695 // X::X(const X&)
8696 //
8697 // if
Sean Huntc530d172011-06-10 04:44:37 +00008698 // FIXME: It ought to be possible to store this on the record.
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008699 bool HasConstCopyConstructor = true;
8700
8701 // -- each direct or virtual base class B of X has a copy
8702 // constructor whose first parameter is of type const B& or
8703 // const volatile B&, and
8704 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8705 BaseEnd = ClassDecl->bases_end();
8706 HasConstCopyConstructor && Base != BaseEnd;
8707 ++Base) {
Douglas Gregor598a8542010-07-01 18:27:03 +00008708 // Virtual bases are handled below.
8709 if (Base->isVirtual())
8710 continue;
8711
Douglas Gregor22584312010-07-02 23:41:54 +00008712 CXXRecordDecl *BaseClassDecl
Douglas Gregor598a8542010-07-01 18:27:03 +00008713 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00008714 LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
8715 &HasConstCopyConstructor);
Douglas Gregor598a8542010-07-01 18:27:03 +00008716 }
8717
8718 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8719 BaseEnd = ClassDecl->vbases_end();
8720 HasConstCopyConstructor && Base != BaseEnd;
8721 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00008722 CXXRecordDecl *BaseClassDecl
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008723 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00008724 LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
8725 &HasConstCopyConstructor);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008726 }
8727
8728 // -- for all the nonstatic data members of X that are of a
8729 // class type M (or array thereof), each such class type
8730 // has a copy constructor whose first parameter is of type
8731 // const M& or const volatile M&.
8732 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8733 FieldEnd = ClassDecl->field_end();
8734 HasConstCopyConstructor && Field != FieldEnd;
8735 ++Field) {
Douglas Gregor598a8542010-07-01 18:27:03 +00008736 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Huntc530d172011-06-10 04:44:37 +00008737 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Sean Hunt661c67a2011-06-21 23:42:56 +00008738 LookupCopyingConstructor(FieldClassDecl, Qualifiers::Const,
8739 &HasConstCopyConstructor);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008740 }
8741 }
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008742 // Otherwise, the implicitly declared copy constructor will have
8743 // the form
8744 //
8745 // X::X(X&)
Sean Hunt49634cf2011-05-13 06:10:58 +00008746
Douglas Gregor0d405db2010-07-01 20:59:04 +00008747 // C++ [except.spec]p14:
8748 // An implicitly declared special member function (Clause 12) shall have an
8749 // exception-specification. [...]
8750 ImplicitExceptionSpecification ExceptSpec(Context);
8751 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
8752 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8753 BaseEnd = ClassDecl->bases_end();
8754 Base != BaseEnd;
8755 ++Base) {
8756 // Virtual bases are handled below.
8757 if (Base->isVirtual())
8758 continue;
8759
Douglas Gregor22584312010-07-02 23:41:54 +00008760 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00008761 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00008762 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008763 LookupCopyingConstructor(BaseClassDecl, Quals))
Douglas Gregor0d405db2010-07-01 20:59:04 +00008764 ExceptSpec.CalledDecl(CopyConstructor);
8765 }
8766 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8767 BaseEnd = ClassDecl->vbases_end();
8768 Base != BaseEnd;
8769 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00008770 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00008771 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00008772 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008773 LookupCopyingConstructor(BaseClassDecl, Quals))
Douglas Gregor0d405db2010-07-01 20:59:04 +00008774 ExceptSpec.CalledDecl(CopyConstructor);
8775 }
8776 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8777 FieldEnd = ClassDecl->field_end();
8778 Field != FieldEnd;
8779 ++Field) {
8780 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Huntc530d172011-06-10 04:44:37 +00008781 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8782 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008783 LookupCopyingConstructor(FieldClassDecl, Quals))
Sean Huntc530d172011-06-10 04:44:37 +00008784 ExceptSpec.CalledDecl(CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00008785 }
8786 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008787
Sean Hunt49634cf2011-05-13 06:10:58 +00008788 return std::make_pair(ExceptSpec, HasConstCopyConstructor);
8789}
8790
8791CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
8792 CXXRecordDecl *ClassDecl) {
8793 // C++ [class.copy]p4:
8794 // If the class definition does not explicitly declare a copy
8795 // constructor, one is declared implicitly.
8796
8797 ImplicitExceptionSpecification Spec(Context);
8798 bool Const;
8799 llvm::tie(Spec, Const) =
8800 ComputeDefaultedCopyCtorExceptionSpecAndConst(ClassDecl);
8801
8802 QualType ClassType = Context.getTypeDeclType(ClassDecl);
8803 QualType ArgType = ClassType;
8804 if (Const)
8805 ArgType = ArgType.withConst();
8806 ArgType = Context.getLValueReferenceType(ArgType);
8807
8808 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8809
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008810 DeclarationName Name
8811 = Context.DeclarationNames.getCXXConstructorName(
8812 Context.getCanonicalType(ClassType));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008813 SourceLocation ClassLoc = ClassDecl->getLocation();
8814 DeclarationNameInfo NameInfo(Name, ClassLoc);
Sean Hunt49634cf2011-05-13 06:10:58 +00008815
8816 // An implicitly-declared copy constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00008817 // member of its class.
8818 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
8819 Context, ClassDecl, ClassLoc, NameInfo,
8820 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI), /*TInfo=*/0,
8821 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
8822 /*isConstexpr=*/ClassDecl->defaultedCopyConstructorIsConstexpr() &&
8823 getLangOptions().CPlusPlus0x);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008824 CopyConstructor->setAccess(AS_public);
Sean Hunt49634cf2011-05-13 06:10:58 +00008825 CopyConstructor->setDefaulted();
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008826 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
Richard Smith61802452011-12-22 02:22:31 +00008827
Douglas Gregor22584312010-07-02 23:41:54 +00008828 // Note that we have declared this constructor.
Douglas Gregor22584312010-07-02 23:41:54 +00008829 ++ASTContext::NumImplicitCopyConstructorsDeclared;
8830
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008831 // Add the parameter to the constructor.
8832 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008833 ClassLoc, ClassLoc,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008834 /*IdentifierInfo=*/0,
8835 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00008836 SC_None,
8837 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008838 CopyConstructor->setParams(FromParam);
Sean Hunt49634cf2011-05-13 06:10:58 +00008839
Douglas Gregor23c94db2010-07-02 17:43:08 +00008840 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor22584312010-07-02 23:41:54 +00008841 PushOnScopeChains(CopyConstructor, S, false);
8842 ClassDecl->addDecl(CopyConstructor);
Sean Hunt71a682f2011-05-18 03:41:58 +00008843
Nico Weberafcc96a2012-01-23 03:19:29 +00008844 // C++11 [class.copy]p8:
8845 // ... If the class definition does not explicitly declare a copy
8846 // constructor, there is no user-declared move constructor, and there is no
8847 // user-declared move assignment operator, a copy constructor is implicitly
8848 // declared as defaulted.
Sean Hunt1ccbc542011-06-22 01:05:13 +00008849 if (ClassDecl->hasUserDeclaredMoveConstructor() ||
Nico Weberafcc96a2012-01-23 03:19:29 +00008850 (ClassDecl->hasUserDeclaredMoveAssignment() &&
Nico Weber28976602012-01-23 04:01:33 +00008851 !getLangOptions().MicrosoftMode) ||
Sean Huntc32d6842011-10-11 04:55:36 +00008852 ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Sean Hunt71a682f2011-05-18 03:41:58 +00008853 CopyConstructor->setDeletedAsWritten();
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008854
8855 return CopyConstructor;
8856}
8857
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008858void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Sean Hunt49634cf2011-05-13 06:10:58 +00008859 CXXConstructorDecl *CopyConstructor) {
8860 assert((CopyConstructor->isDefaulted() &&
8861 CopyConstructor->isCopyConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00008862 !CopyConstructor->doesThisDeclarationHaveABody()) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008863 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00008864
Anders Carlsson63010a72010-04-23 16:24:12 +00008865 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008866 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008867
Douglas Gregor39957dc2010-05-01 15:04:51 +00008868 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008869 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008870
Sean Huntcbb67482011-01-08 20:30:50 +00008871 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008872 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00008873 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008874 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00008875 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008876 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008877 Sema::CompoundScopeRAII CompoundScope(*this);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008878 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
8879 CopyConstructor->getLocation(),
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008880 MultiStmtArg(*this, 0, 0),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008881 /*isStmtExpr=*/false)
8882 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00008883 CopyConstructor->setImplicitlyDefined(true);
Anders Carlsson8e142cc2010-04-25 00:52:09 +00008884 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008885
8886 CopyConstructor->setUsed();
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008887 if (ASTMutationListener *L = getASTMutationListener()) {
8888 L->CompletedImplicitDefinition(CopyConstructor);
8889 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008890}
8891
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008892Sema::ImplicitExceptionSpecification
8893Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
8894 // C++ [except.spec]p14:
8895 // An implicitly declared special member function (Clause 12) shall have an
8896 // exception-specification. [...]
8897 ImplicitExceptionSpecification ExceptSpec(Context);
8898 if (ClassDecl->isInvalidDecl())
8899 return ExceptSpec;
8900
8901 // Direct base-class constructors.
8902 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8903 BEnd = ClassDecl->bases_end();
8904 B != BEnd; ++B) {
8905 if (B->isVirtual()) // Handled below.
8906 continue;
8907
8908 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8909 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8910 CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl);
8911 // If this is a deleted function, add it anyway. This might be conformant
8912 // with the standard. This might not. I'm not sure. It might not matter.
8913 if (Constructor)
8914 ExceptSpec.CalledDecl(Constructor);
8915 }
8916 }
8917
8918 // Virtual base-class constructors.
8919 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8920 BEnd = ClassDecl->vbases_end();
8921 B != BEnd; ++B) {
8922 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8923 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8924 CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl);
8925 // If this is a deleted function, add it anyway. This might be conformant
8926 // with the standard. This might not. I'm not sure. It might not matter.
8927 if (Constructor)
8928 ExceptSpec.CalledDecl(Constructor);
8929 }
8930 }
8931
8932 // Field constructors.
8933 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8934 FEnd = ClassDecl->field_end();
8935 F != FEnd; ++F) {
Douglas Gregorf4853882011-11-28 20:03:15 +00008936 if (const RecordType *RecordTy
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008937 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8938 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8939 CXXConstructorDecl *Constructor = LookupMovingConstructor(FieldRecDecl);
8940 // If this is a deleted function, add it anyway. This might be conformant
8941 // with the standard. This might not. I'm not sure. It might not matter.
8942 // In particular, the problem is that this function never gets called. It
8943 // might just be ill-formed because this function attempts to refer to
8944 // a deleted function here.
8945 if (Constructor)
8946 ExceptSpec.CalledDecl(Constructor);
8947 }
8948 }
8949
8950 return ExceptSpec;
8951}
8952
8953CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
8954 CXXRecordDecl *ClassDecl) {
8955 ImplicitExceptionSpecification Spec(
8956 ComputeDefaultedMoveCtorExceptionSpec(ClassDecl));
8957
8958 QualType ClassType = Context.getTypeDeclType(ClassDecl);
8959 QualType ArgType = Context.getRValueReferenceType(ClassType);
8960
8961 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8962
8963 DeclarationName Name
8964 = Context.DeclarationNames.getCXXConstructorName(
8965 Context.getCanonicalType(ClassType));
8966 SourceLocation ClassLoc = ClassDecl->getLocation();
8967 DeclarationNameInfo NameInfo(Name, ClassLoc);
8968
8969 // C++0x [class.copy]p11:
8970 // An implicitly-declared copy/move constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00008971 // member of its class.
8972 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
8973 Context, ClassDecl, ClassLoc, NameInfo,
8974 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI), /*TInfo=*/0,
8975 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
8976 /*isConstexpr=*/ClassDecl->defaultedMoveConstructorIsConstexpr() &&
8977 getLangOptions().CPlusPlus0x);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008978 MoveConstructor->setAccess(AS_public);
8979 MoveConstructor->setDefaulted();
8980 MoveConstructor->setTrivial(ClassDecl->hasTrivialMoveConstructor());
Richard Smith61802452011-12-22 02:22:31 +00008981
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008982 // Add the parameter to the constructor.
8983 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
8984 ClassLoc, ClassLoc,
8985 /*IdentifierInfo=*/0,
8986 ArgType, /*TInfo=*/0,
8987 SC_None,
8988 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008989 MoveConstructor->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008990
8991 // C++0x [class.copy]p9:
8992 // If the definition of a class X does not explicitly declare a move
8993 // constructor, one will be implicitly declared as defaulted if and only if:
8994 // [...]
8995 // - the move constructor would not be implicitly defined as deleted.
Sean Hunt769bb2d2011-10-11 06:43:29 +00008996 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008997 // Cache this result so that we don't try to generate this over and over
8998 // on every lookup, leaking memory and wasting time.
8999 ClassDecl->setFailedImplicitMoveConstructor();
9000 return 0;
9001 }
9002
9003 // Note that we have declared this constructor.
9004 ++ASTContext::NumImplicitMoveConstructorsDeclared;
9005
9006 if (Scope *S = getScopeForContext(ClassDecl))
9007 PushOnScopeChains(MoveConstructor, S, false);
9008 ClassDecl->addDecl(MoveConstructor);
9009
9010 return MoveConstructor;
9011}
9012
9013void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
9014 CXXConstructorDecl *MoveConstructor) {
9015 assert((MoveConstructor->isDefaulted() &&
9016 MoveConstructor->isMoveConstructor() &&
9017 !MoveConstructor->doesThisDeclarationHaveABody()) &&
9018 "DefineImplicitMoveConstructor - call it for implicit move ctor");
9019
9020 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
9021 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
9022
9023 ImplicitlyDefinedFunctionScope Scope(*this, MoveConstructor);
9024 DiagnosticErrorTrap Trap(Diags);
9025
9026 if (SetCtorInitializers(MoveConstructor, 0, 0, /*AnyErrors=*/false) ||
9027 Trap.hasErrorOccurred()) {
9028 Diag(CurrentLocation, diag::note_member_synthesized_at)
9029 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
9030 MoveConstructor->setInvalidDecl();
9031 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009032 Sema::CompoundScopeRAII CompoundScope(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009033 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
9034 MoveConstructor->getLocation(),
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009035 MultiStmtArg(*this, 0, 0),
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009036 /*isStmtExpr=*/false)
9037 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00009038 MoveConstructor->setImplicitlyDefined(true);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009039 }
9040
9041 MoveConstructor->setUsed();
9042
9043 if (ASTMutationListener *L = getASTMutationListener()) {
9044 L->CompletedImplicitDefinition(MoveConstructor);
9045 }
9046}
9047
Douglas Gregore4e68d42012-02-15 19:33:52 +00009048bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
9049 return FD->isDeleted() &&
9050 (FD->isDefaulted() || FD->isImplicit()) &&
9051 isa<CXXMethodDecl>(FD);
9052}
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009053
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009054/// \brief Mark the call operator of the given lambda closure type as "used".
9055static void markLambdaCallOperatorUsed(Sema &S, CXXRecordDecl *Lambda) {
9056 CXXMethodDecl *CallOperator
9057 = cast<CXXMethodDecl>(
9058 *Lambda->lookup(
9059 S.Context.DeclarationNames.getCXXOperatorName(OO_Call)).first);
9060 CallOperator->setReferenced();
9061 CallOperator->setUsed();
9062}
9063
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009064void Sema::DefineImplicitLambdaToFunctionPointerConversion(
9065 SourceLocation CurrentLocation,
9066 CXXConversionDecl *Conv)
9067{
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009068 CXXRecordDecl *Lambda = Conv->getParent();
9069
9070 // Make sure that the lambda call operator is marked used.
9071 markLambdaCallOperatorUsed(*this, Lambda);
9072
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009073 Conv->setUsed();
9074
9075 ImplicitlyDefinedFunctionScope Scope(*this, Conv);
9076 DiagnosticErrorTrap Trap(Diags);
9077
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009078 // Return the address of the __invoke function.
9079 DeclarationName InvokeName = &Context.Idents.get("__invoke");
9080 CXXMethodDecl *Invoke
9081 = cast<CXXMethodDecl>(*Lambda->lookup(InvokeName).first);
9082 Expr *FunctionRef = BuildDeclRefExpr(Invoke, Invoke->getType(),
9083 VK_LValue, Conv->getLocation()).take();
9084 assert(FunctionRef && "Can't refer to __invoke function?");
9085 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
9086 Conv->setBody(new (Context) CompoundStmt(Context, &Return, 1,
9087 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009088 Conv->getLocation()));
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009089
9090 // Fill in the __invoke function with a dummy implementation. IR generation
9091 // will fill in the actual details.
9092 Invoke->setUsed();
9093 Invoke->setReferenced();
9094 Invoke->setBody(new (Context) CompoundStmt(Context, 0, 0, Conv->getLocation(),
9095 Conv->getLocation()));
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009096
9097 if (ASTMutationListener *L = getASTMutationListener()) {
9098 L->CompletedImplicitDefinition(Conv);
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009099 L->CompletedImplicitDefinition(Invoke);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009100 }
9101}
9102
9103void Sema::DefineImplicitLambdaToBlockPointerConversion(
9104 SourceLocation CurrentLocation,
9105 CXXConversionDecl *Conv)
9106{
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009107 // Make sure that the lambda call operator is marked used.
9108 markLambdaCallOperatorUsed(*this, Conv->getParent());
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009109 Conv->setUsed();
9110
9111 ImplicitlyDefinedFunctionScope Scope(*this, Conv);
9112 DiagnosticErrorTrap Trap(Diags);
9113
9114 // Copy-initialize the lambda object as needed to capture
9115 Expr *This = ActOnCXXThis(CurrentLocation).take();
9116 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
9117 ExprResult Init = PerformCopyInitialization(
9118 InitializedEntity::InitializeBlock(CurrentLocation,
9119 DerefThis->getType(),
9120 /*NRVO=*/false),
9121 CurrentLocation, DerefThis);
9122 if (!Init.isInvalid())
9123 Init = ActOnFinishFullExpr(Init.take());
9124
9125 if (!Init.isInvalid())
9126 Conv->setLambdaToBlockPointerCopyInit(Init.take());
9127 else {
9128 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
9129 }
9130
9131 // Introduce a bogus body, which IR generation will override anyway.
9132 Conv->setBody(new (Context) CompoundStmt(Context, 0, 0, Conv->getLocation(),
9133 Conv->getLocation()));
9134
9135 if (ASTMutationListener *L = getASTMutationListener()) {
9136 L->CompletedImplicitDefinition(Conv);
9137 }
9138}
9139
John McCall60d7b3a2010-08-24 06:29:42 +00009140ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00009141Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00009142 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00009143 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009144 bool HadMultipleCandidates,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009145 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009146 unsigned ConstructKind,
9147 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009148 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00009149
Douglas Gregor2f599792010-04-02 18:24:57 +00009150 // C++0x [class.copy]p34:
9151 // When certain criteria are met, an implementation is allowed to
9152 // omit the copy/move construction of a class object, even if the
9153 // copy/move constructor and/or destructor for the object have
9154 // side effects. [...]
9155 // - when a temporary class object that has not been bound to a
9156 // reference (12.2) would be copied/moved to a class object
9157 // with the same cv-unqualified type, the copy/move operation
9158 // can be omitted by constructing the temporary object
9159 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +00009160 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregor70a21de2011-01-27 23:24:55 +00009161 Constructor->isCopyOrMoveConstructor() && ExprArgs.size() >= 1) {
Douglas Gregor2f599792010-04-02 18:24:57 +00009162 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
John McCall558d2ab2010-09-15 10:14:12 +00009163 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009164 }
Mike Stump1eb44332009-09-09 15:08:12 +00009165
9166 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009167 Elidable, move(ExprArgs), HadMultipleCandidates,
9168 RequiresZeroInit, ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009169}
9170
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009171/// BuildCXXConstructExpr - Creates a complete call to a constructor,
9172/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00009173ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00009174Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
9175 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00009176 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009177 bool HadMultipleCandidates,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009178 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009179 unsigned ConstructKind,
9180 SourceRange ParenRange) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00009181 unsigned NumExprs = ExprArgs.size();
9182 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00009183
Nick Lewycky909a70d2011-03-25 01:44:32 +00009184 for (specific_attr_iterator<NonNullAttr>
9185 i = Constructor->specific_attr_begin<NonNullAttr>(),
9186 e = Constructor->specific_attr_end<NonNullAttr>(); i != e; ++i) {
9187 const NonNullAttr *NonNull = *i;
9188 CheckNonNullArguments(NonNull, ExprArgs.get(), ConstructLoc);
9189 }
9190
Eli Friedman5f2987c2012-02-02 03:46:19 +00009191 MarkFunctionReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00009192 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009193 Constructor, Elidable, Exprs, NumExprs,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00009194 HadMultipleCandidates, /*FIXME*/false,
9195 RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009196 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
9197 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009198}
9199
Mike Stump1eb44332009-09-09 15:08:12 +00009200bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009201 CXXConstructorDecl *Constructor,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009202 MultiExprArg Exprs,
9203 bool HadMultipleCandidates) {
Chandler Carruth428edaf2010-10-25 08:47:36 +00009204 // FIXME: Provide the correct paren SourceRange when available.
John McCall60d7b3a2010-08-24 06:29:42 +00009205 ExprResult TempResult =
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00009206 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009207 move(Exprs), HadMultipleCandidates, false,
9208 CXXConstructExpr::CK_Complete, SourceRange());
Anders Carlssonfe2de492009-08-25 05:18:00 +00009209 if (TempResult.isInvalid())
9210 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00009211
Anders Carlssonda3f4e22009-08-25 05:12:04 +00009212 Expr *Temp = TempResult.takeAs<Expr>();
John McCallb4eb64d2010-10-08 02:01:28 +00009213 CheckImplicitConversions(Temp, VD->getLocation());
Eli Friedman5f2987c2012-02-02 03:46:19 +00009214 MarkFunctionReferenced(VD->getLocation(), Constructor);
John McCall4765fa02010-12-06 08:20:24 +00009215 Temp = MaybeCreateExprWithCleanups(Temp);
Douglas Gregor838db382010-02-11 01:19:42 +00009216 VD->setInit(Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00009217
Anders Carlssonfe2de492009-08-25 05:18:00 +00009218 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00009219}
9220
John McCall68c6c9a2010-02-02 09:10:11 +00009221void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009222 if (VD->isInvalidDecl()) return;
9223
John McCall68c6c9a2010-02-02 09:10:11 +00009224 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009225 if (ClassDecl->isInvalidDecl()) return;
9226 if (ClassDecl->hasTrivialDestructor()) return;
9227 if (ClassDecl->isDependentContext()) return;
John McCall626e96e2010-08-01 20:20:59 +00009228
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009229 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedman5f2987c2012-02-02 03:46:19 +00009230 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009231 CheckDestructorAccess(VD->getLocation(), Destructor,
9232 PDiag(diag::err_access_dtor_var)
9233 << VD->getDeclName()
9234 << VD->getType());
Anders Carlsson2b32dad2011-03-24 01:01:41 +00009235
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009236 if (!VD->hasGlobalStorage()) return;
9237
9238 // Emit warning for non-trivial dtor in global scope (a real global,
9239 // class-static, function-static).
9240 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
9241
9242 // TODO: this should be re-enabled for static locals by !CXAAtExit
9243 if (!VD->isStaticLocal())
9244 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00009245}
9246
Douglas Gregor39da0b82009-09-09 23:08:42 +00009247/// \brief Given a constructor and the set of arguments provided for the
9248/// constructor, convert the arguments and add any required default arguments
9249/// to form a proper call to this constructor.
9250///
9251/// \returns true if an error occurred, false otherwise.
9252bool
9253Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
9254 MultiExprArg ArgsPtr,
9255 SourceLocation Loc,
John McCallca0408f2010-08-23 06:44:23 +00009256 ASTOwningVector<Expr*> &ConvertedArgs) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00009257 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
9258 unsigned NumArgs = ArgsPtr.size();
9259 Expr **Args = (Expr **)ArgsPtr.get();
9260
9261 const FunctionProtoType *Proto
9262 = Constructor->getType()->getAs<FunctionProtoType>();
9263 assert(Proto && "Constructor without a prototype?");
9264 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00009265
9266 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009267 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00009268 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009269 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00009270 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009271
9272 VariadicCallType CallType =
9273 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner5f9e2722011-07-23 10:55:15 +00009274 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009275 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
9276 Proto, 0, Args, NumArgs, AllArgs,
9277 CallType);
Benjamin Kramer14c59822012-02-14 12:06:21 +00009278 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009279 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00009280}
9281
Anders Carlsson20d45d22009-12-12 00:32:00 +00009282static inline bool
9283CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
9284 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00009285 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +00009286 if (isa<NamespaceDecl>(DC)) {
9287 return SemaRef.Diag(FnDecl->getLocation(),
9288 diag::err_operator_new_delete_declared_in_namespace)
9289 << FnDecl->getDeclName();
9290 }
9291
9292 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +00009293 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00009294 return SemaRef.Diag(FnDecl->getLocation(),
9295 diag::err_operator_new_delete_declared_static)
9296 << FnDecl->getDeclName();
9297 }
9298
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00009299 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00009300}
9301
Anders Carlsson156c78e2009-12-13 17:53:43 +00009302static inline bool
9303CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
9304 CanQualType ExpectedResultType,
9305 CanQualType ExpectedFirstParamType,
9306 unsigned DependentParamTypeDiag,
9307 unsigned InvalidParamTypeDiag) {
9308 QualType ResultType =
9309 FnDecl->getType()->getAs<FunctionType>()->getResultType();
9310
9311 // Check that the result type is not dependent.
9312 if (ResultType->isDependentType())
9313 return SemaRef.Diag(FnDecl->getLocation(),
9314 diag::err_operator_new_delete_dependent_result_type)
9315 << FnDecl->getDeclName() << ExpectedResultType;
9316
9317 // Check that the result type is what we expect.
9318 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
9319 return SemaRef.Diag(FnDecl->getLocation(),
9320 diag::err_operator_new_delete_invalid_result_type)
9321 << FnDecl->getDeclName() << ExpectedResultType;
9322
9323 // A function template must have at least 2 parameters.
9324 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
9325 return SemaRef.Diag(FnDecl->getLocation(),
9326 diag::err_operator_new_delete_template_too_few_parameters)
9327 << FnDecl->getDeclName();
9328
9329 // The function decl must have at least 1 parameter.
9330 if (FnDecl->getNumParams() == 0)
9331 return SemaRef.Diag(FnDecl->getLocation(),
9332 diag::err_operator_new_delete_too_few_parameters)
9333 << FnDecl->getDeclName();
9334
9335 // Check the the first parameter type is not dependent.
9336 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
9337 if (FirstParamType->isDependentType())
9338 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
9339 << FnDecl->getDeclName() << ExpectedFirstParamType;
9340
9341 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +00009342 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +00009343 ExpectedFirstParamType)
9344 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
9345 << FnDecl->getDeclName() << ExpectedFirstParamType;
9346
9347 return false;
9348}
9349
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009350static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +00009351CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00009352 // C++ [basic.stc.dynamic.allocation]p1:
9353 // A program is ill-formed if an allocation function is declared in a
9354 // namespace scope other than global scope or declared static in global
9355 // scope.
9356 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9357 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +00009358
9359 CanQualType SizeTy =
9360 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
9361
9362 // C++ [basic.stc.dynamic.allocation]p1:
9363 // The return type shall be void*. The first parameter shall have type
9364 // std::size_t.
9365 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
9366 SizeTy,
9367 diag::err_operator_new_dependent_param_type,
9368 diag::err_operator_new_param_type))
9369 return true;
9370
9371 // C++ [basic.stc.dynamic.allocation]p1:
9372 // The first parameter shall not have an associated default argument.
9373 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +00009374 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +00009375 diag::err_operator_new_default_arg)
9376 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
9377
9378 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +00009379}
9380
9381static bool
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009382CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
9383 // C++ [basic.stc.dynamic.deallocation]p1:
9384 // A program is ill-formed if deallocation functions are declared in a
9385 // namespace scope other than global scope or declared static in global
9386 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +00009387 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9388 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009389
9390 // C++ [basic.stc.dynamic.deallocation]p2:
9391 // Each deallocation function shall return void and its first parameter
9392 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +00009393 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
9394 SemaRef.Context.VoidPtrTy,
9395 diag::err_operator_delete_dependent_param_type,
9396 diag::err_operator_delete_param_type))
9397 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009398
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009399 return false;
9400}
9401
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009402/// CheckOverloadedOperatorDeclaration - Check whether the declaration
9403/// of this overloaded operator is well-formed. If so, returns false;
9404/// otherwise, emits appropriate diagnostics and returns true.
9405bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009406 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009407 "Expected an overloaded operator declaration");
9408
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009409 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
9410
Mike Stump1eb44332009-09-09 15:08:12 +00009411 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009412 // The allocation and deallocation functions, operator new,
9413 // operator new[], operator delete and operator delete[], are
9414 // described completely in 3.7.3. The attributes and restrictions
9415 // found in the rest of this subclause do not apply to them unless
9416 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +00009417 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009418 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00009419
Anders Carlssona3ccda52009-12-12 00:26:23 +00009420 if (Op == OO_New || Op == OO_Array_New)
9421 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009422
9423 // C++ [over.oper]p6:
9424 // An operator function shall either be a non-static member
9425 // function or be a non-member function and have at least one
9426 // parameter whose type is a class, a reference to a class, an
9427 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009428 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
9429 if (MethodDecl->isStatic())
9430 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009431 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009432 } else {
9433 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009434 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
9435 ParamEnd = FnDecl->param_end();
9436 Param != ParamEnd; ++Param) {
9437 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00009438 if (ParamType->isDependentType() || ParamType->isRecordType() ||
9439 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009440 ClassOrEnumParam = true;
9441 break;
9442 }
9443 }
9444
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009445 if (!ClassOrEnumParam)
9446 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009447 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009448 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009449 }
9450
9451 // C++ [over.oper]p8:
9452 // An operator function cannot have default arguments (8.3.6),
9453 // except where explicitly stated below.
9454 //
Mike Stump1eb44332009-09-09 15:08:12 +00009455 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009456 // (C++ [over.call]p1).
9457 if (Op != OO_Call) {
9458 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
9459 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +00009460 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00009461 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00009462 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +00009463 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009464 }
9465 }
9466
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009467 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
9468 { false, false, false }
9469#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
9470 , { Unary, Binary, MemberOnly }
9471#include "clang/Basic/OperatorKinds.def"
9472 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009473
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009474 bool CanBeUnaryOperator = OperatorUses[Op][0];
9475 bool CanBeBinaryOperator = OperatorUses[Op][1];
9476 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009477
9478 // C++ [over.oper]p8:
9479 // [...] Operator functions cannot have more or fewer parameters
9480 // than the number required for the corresponding operator, as
9481 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00009482 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009483 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009484 if (Op != OO_Call &&
9485 ((NumParams == 1 && !CanBeUnaryOperator) ||
9486 (NumParams == 2 && !CanBeBinaryOperator) ||
9487 (NumParams < 1) || (NumParams > 2))) {
9488 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00009489 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009490 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00009491 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009492 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00009493 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009494 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00009495 assert(CanBeBinaryOperator &&
9496 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00009497 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009498 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009499
Chris Lattner416e46f2008-11-21 07:57:12 +00009500 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009501 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009502 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00009503
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009504 // Overloaded operators other than operator() cannot be variadic.
9505 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00009506 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009507 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009508 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009509 }
9510
9511 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009512 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
9513 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009514 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009515 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009516 }
9517
9518 // C++ [over.inc]p1:
9519 // The user-defined function called operator++ implements the
9520 // prefix and postfix ++ operator. If this function is a member
9521 // function with no parameters, or a non-member function with one
9522 // parameter of class or enumeration type, it defines the prefix
9523 // increment operator ++ for objects of that type. If the function
9524 // is a member function with one parameter (which shall be of type
9525 // int) or a non-member function with two parameters (the second
9526 // of which shall be of type int), it defines the postfix
9527 // increment operator ++ for objects of that type.
9528 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
9529 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
9530 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00009531 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009532 ParamIsInt = BT->getKind() == BuiltinType::Int;
9533
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00009534 if (!ParamIsInt)
9535 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00009536 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00009537 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009538 }
9539
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009540 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009541}
Chris Lattner5a003a42008-12-17 07:09:26 +00009542
Sean Hunta6c058d2010-01-13 09:01:02 +00009543/// CheckLiteralOperatorDeclaration - Check whether the declaration
9544/// of this literal operator function is well-formed. If so, returns
9545/// false; otherwise, emits appropriate diagnostics and returns true.
9546bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
9547 DeclContext *DC = FnDecl->getDeclContext();
9548 Decl::Kind Kind = DC->getDeclKind();
9549 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
9550 Kind != Decl::LinkageSpec) {
9551 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
9552 << FnDecl->getDeclName();
9553 return true;
9554 }
9555
9556 bool Valid = false;
9557
Sean Hunt216c2782010-04-07 23:11:06 +00009558 // template <char...> type operator "" name() is the only valid template
9559 // signature, and the only valid signature with no parameters.
9560 if (FnDecl->param_size() == 0) {
9561 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
9562 // Must have only one template parameter
9563 TemplateParameterList *Params = TpDecl->getTemplateParameters();
9564 if (Params->size() == 1) {
9565 NonTypeTemplateParmDecl *PmDecl =
9566 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +00009567
Sean Hunt216c2782010-04-07 23:11:06 +00009568 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +00009569 if (PmDecl && PmDecl->isTemplateParameterPack() &&
9570 Context.hasSameType(PmDecl->getType(), Context.CharTy))
9571 Valid = true;
9572 }
9573 }
9574 } else {
Sean Hunta6c058d2010-01-13 09:01:02 +00009575 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +00009576 FunctionDecl::param_iterator Param = FnDecl->param_begin();
9577
Sean Hunta6c058d2010-01-13 09:01:02 +00009578 QualType T = (*Param)->getType();
9579
Sean Hunt30019c02010-04-07 22:57:35 +00009580 // unsigned long long int, long double, and any character type are allowed
9581 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +00009582 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
9583 Context.hasSameType(T, Context.LongDoubleTy) ||
9584 Context.hasSameType(T, Context.CharTy) ||
9585 Context.hasSameType(T, Context.WCharTy) ||
9586 Context.hasSameType(T, Context.Char16Ty) ||
9587 Context.hasSameType(T, Context.Char32Ty)) {
9588 if (++Param == FnDecl->param_end())
9589 Valid = true;
9590 goto FinishedParams;
9591 }
9592
Sean Hunt30019c02010-04-07 22:57:35 +00009593 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +00009594 const PointerType *PT = T->getAs<PointerType>();
9595 if (!PT)
9596 goto FinishedParams;
9597 T = PT->getPointeeType();
9598 if (!T.isConstQualified())
9599 goto FinishedParams;
9600 T = T.getUnqualifiedType();
9601
9602 // Move on to the second parameter;
9603 ++Param;
9604
9605 // If there is no second parameter, the first must be a const char *
9606 if (Param == FnDecl->param_end()) {
9607 if (Context.hasSameType(T, Context.CharTy))
9608 Valid = true;
9609 goto FinishedParams;
9610 }
9611
9612 // const char *, const wchar_t*, const char16_t*, and const char32_t*
9613 // are allowed as the first parameter to a two-parameter function
9614 if (!(Context.hasSameType(T, Context.CharTy) ||
9615 Context.hasSameType(T, Context.WCharTy) ||
9616 Context.hasSameType(T, Context.Char16Ty) ||
9617 Context.hasSameType(T, Context.Char32Ty)))
9618 goto FinishedParams;
9619
9620 // The second and final parameter must be an std::size_t
9621 T = (*Param)->getType().getUnqualifiedType();
9622 if (Context.hasSameType(T, Context.getSizeType()) &&
9623 ++Param == FnDecl->param_end())
9624 Valid = true;
9625 }
9626
9627 // FIXME: This diagnostic is absolutely terrible.
9628FinishedParams:
9629 if (!Valid) {
9630 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
9631 << FnDecl->getDeclName();
9632 return true;
9633 }
9634
Douglas Gregor1155c422011-08-30 22:40:35 +00009635 StringRef LiteralName
9636 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
9637 if (LiteralName[0] != '_') {
9638 // C++0x [usrlit.suffix]p1:
9639 // Literal suffix identifiers that do not start with an underscore are
9640 // reserved for future standardization.
9641 bool IsHexFloat = true;
9642 if (LiteralName.size() > 1 &&
9643 (LiteralName[0] == 'P' || LiteralName[0] == 'p')) {
9644 for (unsigned I = 1, N = LiteralName.size(); I < N; ++I) {
9645 if (!isdigit(LiteralName[I])) {
9646 IsHexFloat = false;
9647 break;
9648 }
9649 }
9650 }
9651
9652 if (IsHexFloat)
9653 Diag(FnDecl->getLocation(), diag::warn_user_literal_hexfloat)
9654 << LiteralName;
9655 else
9656 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
9657 }
9658
Sean Hunta6c058d2010-01-13 09:01:02 +00009659 return false;
9660}
9661
Douglas Gregor074149e2009-01-05 19:45:36 +00009662/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
9663/// linkage specification, including the language and (if present)
9664/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
9665/// the location of the language string literal, which is provided
9666/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
9667/// the '{' brace. Otherwise, this linkage specification does not
9668/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +00009669Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
9670 SourceLocation LangLoc,
Chris Lattner5f9e2722011-07-23 10:55:15 +00009671 StringRef Lang,
Chris Lattner7d642712010-11-09 20:15:55 +00009672 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00009673 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +00009674 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00009675 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +00009676 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00009677 Language = LinkageSpecDecl::lang_cxx;
9678 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00009679 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +00009680 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +00009681 }
Mike Stump1eb44332009-09-09 15:08:12 +00009682
Chris Lattnercc98eac2008-12-17 07:13:27 +00009683 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +00009684
Douglas Gregor074149e2009-01-05 19:45:36 +00009685 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009686 ExternLoc, LangLoc, Language);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009687 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00009688 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +00009689 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +00009690}
9691
Abramo Bagnara35f9a192010-07-30 16:47:02 +00009692/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +00009693/// the C++ linkage specification LinkageSpec. If RBraceLoc is
9694/// valid, it's the position of the closing '}' brace in a linkage
9695/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +00009696Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +00009697 Decl *LinkageSpec,
9698 SourceLocation RBraceLoc) {
9699 if (LinkageSpec) {
9700 if (RBraceLoc.isValid()) {
9701 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
9702 LSDecl->setRBraceLoc(RBraceLoc);
9703 }
Douglas Gregor074149e2009-01-05 19:45:36 +00009704 PopDeclContext();
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +00009705 }
Douglas Gregor074149e2009-01-05 19:45:36 +00009706 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00009707}
9708
Douglas Gregord308e622009-05-18 20:51:54 +00009709/// \brief Perform semantic analysis for the variable declaration that
9710/// occurs within a C++ catch clause, returning the newly-created
9711/// variable.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009712VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +00009713 TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009714 SourceLocation StartLoc,
9715 SourceLocation Loc,
9716 IdentifierInfo *Name) {
Douglas Gregord308e622009-05-18 20:51:54 +00009717 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +00009718 QualType ExDeclType = TInfo->getType();
9719
Sebastian Redl4b07b292008-12-22 19:15:10 +00009720 // Arrays and functions decay.
9721 if (ExDeclType->isArrayType())
9722 ExDeclType = Context.getArrayDecayedType(ExDeclType);
9723 else if (ExDeclType->isFunctionType())
9724 ExDeclType = Context.getPointerType(ExDeclType);
9725
9726 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
9727 // The exception-declaration shall not denote a pointer or reference to an
9728 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009729 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +00009730 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +00009731 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009732 Invalid = true;
9733 }
Douglas Gregord308e622009-05-18 20:51:54 +00009734
Sebastian Redl4b07b292008-12-22 19:15:10 +00009735 QualType BaseType = ExDeclType;
9736 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00009737 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +00009738 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009739 BaseType = Ptr->getPointeeType();
9740 Mode = 1;
Douglas Gregorecd7b042012-01-24 19:01:26 +00009741 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +00009742 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009743 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00009744 BaseType = Ref->getPointeeType();
9745 Mode = 2;
Douglas Gregorecd7b042012-01-24 19:01:26 +00009746 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009747 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009748 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregorecd7b042012-01-24 19:01:26 +00009749 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +00009750 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009751
Mike Stump1eb44332009-09-09 15:08:12 +00009752 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +00009753 RequireNonAbstractType(Loc, ExDeclType,
9754 diag::err_abstract_type_in_decl,
9755 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00009756 Invalid = true;
9757
John McCall5a180392010-07-24 00:37:23 +00009758 // Only the non-fragile NeXT runtime currently supports C++ catches
9759 // of ObjC types, and no runtime supports catching ObjC types by value.
9760 if (!Invalid && getLangOptions().ObjC1) {
9761 QualType T = ExDeclType;
9762 if (const ReferenceType *RT = T->getAs<ReferenceType>())
9763 T = RT->getPointeeType();
9764
9765 if (T->isObjCObjectType()) {
9766 Diag(Loc, diag::err_objc_object_catch);
9767 Invalid = true;
9768 } else if (T->isObjCObjectPointerType()) {
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +00009769 if (!getLangOptions().ObjCNonFragileABI)
9770 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall5a180392010-07-24 00:37:23 +00009771 }
9772 }
9773
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009774 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
9775 ExDeclType, TInfo, SC_None, SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +00009776 ExDecl->setExceptionVariable(true);
9777
Douglas Gregor9aab9c42011-12-10 01:22:52 +00009778 // In ARC, infer 'retaining' for variables of retainable type.
9779 if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
9780 Invalid = true;
9781
Douglas Gregorc41b8782011-07-06 18:14:43 +00009782 if (!Invalid && !ExDeclType->isDependentType()) {
John McCalle996ffd2011-02-16 08:02:54 +00009783 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
Douglas Gregor6d182892010-03-05 23:38:39 +00009784 // C++ [except.handle]p16:
9785 // The object declared in an exception-declaration or, if the
9786 // exception-declaration does not specify a name, a temporary (12.2) is
9787 // copy-initialized (8.5) from the exception object. [...]
9788 // The object is destroyed when the handler exits, after the destruction
9789 // of any automatic objects initialized within the handler.
9790 //
9791 // We just pretend to initialize the object with itself, then make sure
9792 // it can be destroyed later.
John McCalle996ffd2011-02-16 08:02:54 +00009793 QualType initType = ExDeclType;
9794
9795 InitializedEntity entity =
9796 InitializedEntity::InitializeVariable(ExDecl);
9797 InitializationKind initKind =
9798 InitializationKind::CreateCopy(Loc, SourceLocation());
9799
9800 Expr *opaqueValue =
9801 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
9802 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
9803 ExprResult result = sequence.Perform(*this, entity, initKind,
9804 MultiExprArg(&opaqueValue, 1));
9805 if (result.isInvalid())
Douglas Gregor6d182892010-03-05 23:38:39 +00009806 Invalid = true;
John McCalle996ffd2011-02-16 08:02:54 +00009807 else {
9808 // If the constructor used was non-trivial, set this as the
9809 // "initializer".
9810 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
9811 if (!construct->getConstructor()->isTrivial()) {
9812 Expr *init = MaybeCreateExprWithCleanups(construct);
9813 ExDecl->setInit(init);
9814 }
9815
9816 // And make sure it's destructable.
9817 FinalizeVarWithDestructor(ExDecl, recordType);
9818 }
Douglas Gregor6d182892010-03-05 23:38:39 +00009819 }
9820 }
9821
Douglas Gregord308e622009-05-18 20:51:54 +00009822 if (Invalid)
9823 ExDecl->setInvalidDecl();
9824
9825 return ExDecl;
9826}
9827
9828/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
9829/// handler.
John McCalld226f652010-08-21 09:40:31 +00009830Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +00009831 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +00009832 bool Invalid = D.isInvalidType();
9833
9834 // Check for unexpanded parameter packs.
9835 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
9836 UPPC_ExceptionType)) {
9837 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
9838 D.getIdentifierLoc());
9839 Invalid = true;
9840 }
9841
Sebastian Redl4b07b292008-12-22 19:15:10 +00009842 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +00009843 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +00009844 LookupOrdinaryName,
9845 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009846 // The scope should be freshly made just for us. There is just no way
9847 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +00009848 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +00009849 if (PrevDecl->isTemplateParameter()) {
9850 // Maybe we will complain about the shadowed template parameter.
9851 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregorcb8f9512011-10-20 17:58:49 +00009852 PrevDecl = 0;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009853 }
9854 }
9855
Chris Lattnereaaebc72009-04-25 08:06:05 +00009856 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009857 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
9858 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00009859 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009860 }
9861
Douglas Gregor83cb9422010-09-09 17:09:21 +00009862 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009863 D.getSourceRange().getBegin(),
9864 D.getIdentifierLoc(),
9865 D.getIdentifier());
Chris Lattnereaaebc72009-04-25 08:06:05 +00009866 if (Invalid)
9867 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00009868
Sebastian Redl4b07b292008-12-22 19:15:10 +00009869 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00009870 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00009871 PushOnScopeChains(ExDecl, S);
9872 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009873 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00009874
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00009875 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +00009876 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009877}
Anders Carlssonfb311762009-03-14 00:25:26 +00009878
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009879Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +00009880 Expr *AssertExpr,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009881 Expr *AssertMessageExpr_,
9882 SourceLocation RParenLoc) {
John McCall9ae2f072010-08-23 23:25:46 +00009883 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
Anders Carlssonfb311762009-03-14 00:25:26 +00009884
Anders Carlssonc3082412009-03-14 00:33:21 +00009885 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
Richard Smith282e7e62012-02-04 09:53:13 +00009886 // In a static_assert-declaration, the constant-expression shall be a
9887 // constant expression that can be contextually converted to bool.
9888 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
9889 if (Converted.isInvalid())
9890 return 0;
9891
Richard Smithdaaefc52011-12-14 23:32:26 +00009892 llvm::APSInt Cond;
Richard Smith282e7e62012-02-04 09:53:13 +00009893 if (VerifyIntegerConstantExpression(Converted.get(), &Cond,
9894 PDiag(diag::err_static_assert_expression_is_not_constant),
9895 /*AllowFold=*/false).isInvalid())
John McCalld226f652010-08-21 09:40:31 +00009896 return 0;
Anders Carlssonfb311762009-03-14 00:25:26 +00009897
Richard Smithdaaefc52011-12-14 23:32:26 +00009898 if (!Cond)
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009899 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Benjamin Kramer8d042582009-12-11 13:33:18 +00009900 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlssonc3082412009-03-14 00:33:21 +00009901 }
Mike Stump1eb44332009-09-09 15:08:12 +00009902
Douglas Gregor399ad972010-12-15 23:55:21 +00009903 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
9904 return 0;
9905
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009906 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
9907 AssertExpr, AssertMessage, RParenLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00009908
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009909 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +00009910 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +00009911}
Sebastian Redl50de12f2009-03-24 22:27:57 +00009912
Douglas Gregor1d869352010-04-07 16:53:43 +00009913/// \brief Perform semantic analysis of the given friend type declaration.
9914///
9915/// \returns A friend declaration that.
Abramo Bagnara0216df82011-10-29 20:52:52 +00009916FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation Loc,
9917 SourceLocation FriendLoc,
Douglas Gregor1d869352010-04-07 16:53:43 +00009918 TypeSourceInfo *TSInfo) {
9919 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
9920
9921 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00009922 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +00009923
Richard Smith6b130222011-10-18 21:39:00 +00009924 // C++03 [class.friend]p2:
9925 // An elaborated-type-specifier shall be used in a friend declaration
9926 // for a class.*
9927 //
9928 // * The class-key of the elaborated-type-specifier is required.
9929 if (!ActiveTemplateInstantiations.empty()) {
9930 // Do not complain about the form of friend template types during
9931 // template instantiation; we will already have complained when the
9932 // template was declared.
9933 } else if (!T->isElaboratedTypeSpecifier()) {
9934 // If we evaluated the type to a record type, suggest putting
9935 // a tag in front.
9936 if (const RecordType *RT = T->getAs<RecordType>()) {
9937 RecordDecl *RD = RT->getDecl();
9938
9939 std::string InsertionText = std::string(" ") + RD->getKindName();
9940
9941 Diag(TypeRange.getBegin(),
9942 getLangOptions().CPlusPlus0x ?
9943 diag::warn_cxx98_compat_unelaborated_friend_type :
9944 diag::ext_unelaborated_friend_type)
9945 << (unsigned) RD->getTagKind()
9946 << T
9947 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
9948 InsertionText);
9949 } else {
9950 Diag(FriendLoc,
9951 getLangOptions().CPlusPlus0x ?
9952 diag::warn_cxx98_compat_nonclass_type_friend :
9953 diag::ext_nonclass_type_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +00009954 << T
Douglas Gregor1d869352010-04-07 16:53:43 +00009955 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregor1d869352010-04-07 16:53:43 +00009956 }
Richard Smith6b130222011-10-18 21:39:00 +00009957 } else if (T->getAs<EnumType>()) {
9958 Diag(FriendLoc,
9959 getLangOptions().CPlusPlus0x ?
9960 diag::warn_cxx98_compat_enum_friend :
9961 diag::ext_enum_friend)
9962 << T
9963 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregor1d869352010-04-07 16:53:43 +00009964 }
9965
Douglas Gregor06245bf2010-04-07 17:57:12 +00009966 // C++0x [class.friend]p3:
9967 // If the type specifier in a friend declaration designates a (possibly
9968 // cv-qualified) class type, that class is declared as a friend; otherwise,
9969 // the friend declaration is ignored.
9970
9971 // FIXME: C++0x has some syntactic restrictions on friend type declarations
9972 // in [class.friend]p3 that we do not implement.
Douglas Gregor1d869352010-04-07 16:53:43 +00009973
Abramo Bagnara0216df82011-10-29 20:52:52 +00009974 return FriendDecl::Create(Context, CurContext, Loc, TSInfo, FriendLoc);
Douglas Gregor1d869352010-04-07 16:53:43 +00009975}
9976
John McCall9a34edb2010-10-19 01:40:49 +00009977/// Handle a friend tag declaration where the scope specifier was
9978/// templated.
9979Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
9980 unsigned TagSpec, SourceLocation TagLoc,
9981 CXXScopeSpec &SS,
9982 IdentifierInfo *Name, SourceLocation NameLoc,
9983 AttributeList *Attr,
9984 MultiTemplateParamsArg TempParamLists) {
9985 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
9986
9987 bool isExplicitSpecialization = false;
John McCall9a34edb2010-10-19 01:40:49 +00009988 bool Invalid = false;
9989
9990 if (TemplateParameterList *TemplateParams
Douglas Gregorc8406492011-05-10 18:27:06 +00009991 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
John McCall9a34edb2010-10-19 01:40:49 +00009992 TempParamLists.get(),
9993 TempParamLists.size(),
9994 /*friend*/ true,
9995 isExplicitSpecialization,
9996 Invalid)) {
John McCall9a34edb2010-10-19 01:40:49 +00009997 if (TemplateParams->size() > 0) {
9998 // This is a declaration of a class template.
9999 if (Invalid)
10000 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +000010001
Eric Christopher4110e132011-07-21 05:34:24 +000010002 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
10003 SS, Name, NameLoc, Attr,
10004 TemplateParams, AS_public,
Douglas Gregore7612302011-09-09 19:05:14 +000010005 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher4110e132011-07-21 05:34:24 +000010006 TempParamLists.size() - 1,
Abramo Bagnarac57c17d2011-03-10 13:28:31 +000010007 (TemplateParameterList**) TempParamLists.release()).take();
John McCall9a34edb2010-10-19 01:40:49 +000010008 } else {
10009 // The "template<>" header is extraneous.
10010 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
10011 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
10012 isExplicitSpecialization = true;
10013 }
10014 }
10015
10016 if (Invalid) return 0;
10017
John McCall9a34edb2010-10-19 01:40:49 +000010018 bool isAllExplicitSpecializations = true;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +000010019 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
John McCall9a34edb2010-10-19 01:40:49 +000010020 if (TempParamLists.get()[I]->size()) {
10021 isAllExplicitSpecializations = false;
10022 break;
10023 }
10024 }
10025
10026 // FIXME: don't ignore attributes.
10027
10028 // If it's explicit specializations all the way down, just forget
10029 // about the template header and build an appropriate non-templated
10030 // friend. TODO: for source fidelity, remember the headers.
10031 if (isAllExplicitSpecializations) {
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010032 if (SS.isEmpty()) {
10033 bool Owned = false;
10034 bool IsDependent = false;
10035 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
10036 Attr, AS_public,
10037 /*ModulePrivateLoc=*/SourceLocation(),
10038 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smithbdad7a22012-01-10 01:33:14 +000010039 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010040 /*ScopedEnumUsesClassTag=*/false,
10041 /*UnderlyingType=*/TypeResult());
10042 }
10043
Douglas Gregor2494dd02011-03-01 01:34:45 +000010044 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall9a34edb2010-10-19 01:40:49 +000010045 ElaboratedTypeKeyword Keyword
10046 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010047 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +000010048 *Name, NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010049 if (T.isNull())
10050 return 0;
10051
10052 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10053 if (isa<DependentNameType>(T)) {
10054 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara38a42912012-02-06 19:09:27 +000010055 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010056 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010057 TL.setNameLoc(NameLoc);
10058 } else {
10059 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara38a42912012-02-06 19:09:27 +000010060 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +000010061 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010062 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
10063 }
10064
10065 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
10066 TSI, FriendLoc);
10067 Friend->setAccess(AS_public);
10068 CurContext->addDecl(Friend);
10069 return Friend;
10070 }
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010071
10072 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
10073
10074
John McCall9a34edb2010-10-19 01:40:49 +000010075
10076 // Handle the case of a templated-scope friend class. e.g.
10077 // template <class T> class A<T>::B;
10078 // FIXME: we don't support these right now.
10079 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
10080 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
10081 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10082 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara38a42912012-02-06 19:09:27 +000010083 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010084 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCall9a34edb2010-10-19 01:40:49 +000010085 TL.setNameLoc(NameLoc);
10086
10087 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
10088 TSI, FriendLoc);
10089 Friend->setAccess(AS_public);
10090 Friend->setUnsupportedFriend(true);
10091 CurContext->addDecl(Friend);
10092 return Friend;
10093}
10094
10095
John McCalldd4a3b02009-09-16 22:47:08 +000010096/// Handle a friend type declaration. This works in tandem with
10097/// ActOnTag.
10098///
10099/// Notes on friend class templates:
10100///
10101/// We generally treat friend class declarations as if they were
10102/// declaring a class. So, for example, the elaborated type specifier
10103/// in a friend declaration is required to obey the restrictions of a
10104/// class-head (i.e. no typedefs in the scope chain), template
10105/// parameters are required to match up with simple template-ids, &c.
10106/// However, unlike when declaring a template specialization, it's
10107/// okay to refer to a template specialization without an empty
10108/// template parameter declaration, e.g.
10109/// friend class A<T>::B<unsigned>;
10110/// We permit this as a special case; if there are any template
10111/// parameters present at all, require proper matching, i.e.
10112/// template <> template <class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +000010113Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +000010114 MultiTemplateParamsArg TempParams) {
John McCall02cace72009-08-28 07:59:38 +000010115 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall67d1a672009-08-06 02:15:43 +000010116
10117 assert(DS.isFriendSpecified());
10118 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10119
John McCalldd4a3b02009-09-16 22:47:08 +000010120 // Try to convert the decl specifier to a type. This works for
10121 // friend templates because ActOnTag never produces a ClassTemplateDecl
10122 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +000010123 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +000010124 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
10125 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +000010126 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +000010127 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010128
Douglas Gregor6ccab972010-12-16 01:14:37 +000010129 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
10130 return 0;
10131
John McCalldd4a3b02009-09-16 22:47:08 +000010132 // This is definitely an error in C++98. It's probably meant to
10133 // be forbidden in C++0x, too, but the specification is just
10134 // poorly written.
10135 //
10136 // The problem is with declarations like the following:
10137 // template <T> friend A<T>::foo;
10138 // where deciding whether a class C is a friend or not now hinges
10139 // on whether there exists an instantiation of A that causes
10140 // 'foo' to equal C. There are restrictions on class-heads
10141 // (which we declare (by fiat) elaborated friend declarations to
10142 // be) that makes this tractable.
10143 //
10144 // FIXME: handle "template <> friend class A<T>;", which
10145 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +000010146 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +000010147 Diag(Loc, diag::err_tagless_friend_type_template)
10148 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +000010149 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +000010150 }
Douglas Gregor1d869352010-04-07 16:53:43 +000010151
John McCall02cace72009-08-28 07:59:38 +000010152 // C++98 [class.friend]p1: A friend of a class is a function
10153 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +000010154 // This is fixed in DR77, which just barely didn't make the C++03
10155 // deadline. It's also a very silly restriction that seriously
10156 // affects inner classes and which nobody else seems to implement;
10157 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +000010158 //
10159 // But note that we could warn about it: it's always useless to
10160 // friend one of your own members (it's not, however, worthless to
10161 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +000010162
John McCalldd4a3b02009-09-16 22:47:08 +000010163 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +000010164 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +000010165 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +000010166 NumTempParamLists,
John McCallbe04b6d2010-10-16 07:23:36 +000010167 TempParams.release(),
John McCall32f2fb52010-03-25 18:04:51 +000010168 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +000010169 DS.getFriendSpecLoc());
10170 else
Abramo Bagnara0216df82011-10-29 20:52:52 +000010171 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregor1d869352010-04-07 16:53:43 +000010172
10173 if (!D)
John McCalld226f652010-08-21 09:40:31 +000010174 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +000010175
John McCalldd4a3b02009-09-16 22:47:08 +000010176 D->setAccess(AS_public);
10177 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +000010178
John McCalld226f652010-08-21 09:40:31 +000010179 return D;
John McCall02cace72009-08-28 07:59:38 +000010180}
10181
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010182Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
John McCall337ec3d2010-10-12 23:13:28 +000010183 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +000010184 const DeclSpec &DS = D.getDeclSpec();
10185
10186 assert(DS.isFriendSpecified());
10187 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10188
10189 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +000010190 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall67d1a672009-08-06 02:15:43 +000010191
10192 // C++ [class.friend]p1
10193 // A friend of a class is a function or class....
10194 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +000010195 // It *doesn't* see through dependent types, which is correct
10196 // according to [temp.arg.type]p3:
10197 // If a declaration acquires a function type through a
10198 // type dependent on a template-parameter and this causes
10199 // a declaration that does not use the syntactic form of a
10200 // function declarator to have a function type, the program
10201 // is ill-formed.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010202 if (!TInfo->getType()->isFunctionType()) {
John McCall67d1a672009-08-06 02:15:43 +000010203 Diag(Loc, diag::err_unexpected_friend);
10204
10205 // It might be worthwhile to try to recover by creating an
10206 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +000010207 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010208 }
10209
10210 // C++ [namespace.memdef]p3
10211 // - If a friend declaration in a non-local class first declares a
10212 // class or function, the friend class or function is a member
10213 // of the innermost enclosing namespace.
10214 // - The name of the friend is not found by simple name lookup
10215 // until a matching declaration is provided in that namespace
10216 // scope (either before or after the class declaration granting
10217 // friendship).
10218 // - If a friend function is called, its name may be found by the
10219 // name lookup that considers functions from namespaces and
10220 // classes associated with the types of the function arguments.
10221 // - When looking for a prior declaration of a class or a function
10222 // declared as a friend, scopes outside the innermost enclosing
10223 // namespace scope are not considered.
10224
John McCall337ec3d2010-10-12 23:13:28 +000010225 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +000010226 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
10227 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +000010228 assert(Name);
10229
Douglas Gregor6ccab972010-12-16 01:14:37 +000010230 // Check for unexpanded parameter packs.
10231 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
10232 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
10233 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
10234 return 0;
10235
John McCall67d1a672009-08-06 02:15:43 +000010236 // The context we found the declaration in, or in which we should
10237 // create the declaration.
10238 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +000010239 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +000010240 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +000010241 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +000010242
John McCall337ec3d2010-10-12 23:13:28 +000010243 // FIXME: there are different rules in local classes
John McCall67d1a672009-08-06 02:15:43 +000010244
John McCall337ec3d2010-10-12 23:13:28 +000010245 // There are four cases here.
10246 // - There's no scope specifier, in which case we just go to the
John McCall29ae6e52010-10-13 05:45:15 +000010247 // appropriate scope and look for a function or function template
John McCall337ec3d2010-10-12 23:13:28 +000010248 // there as appropriate.
10249 // Recover from invalid scope qualifiers as if they just weren't there.
10250 if (SS.isInvalid() || !SS.isSet()) {
John McCall29ae6e52010-10-13 05:45:15 +000010251 // C++0x [namespace.memdef]p3:
10252 // If the name in a friend declaration is neither qualified nor
10253 // a template-id and the declaration is a function or an
10254 // elaborated-type-specifier, the lookup to determine whether
10255 // the entity has been previously declared shall not consider
10256 // any scopes outside the innermost enclosing namespace.
10257 // C++0x [class.friend]p11:
10258 // If a friend declaration appears in a local class and the name
10259 // specified is an unqualified name, a prior declaration is
10260 // looked up without considering scopes that are outside the
10261 // innermost enclosing non-class scope. For a friend function
10262 // declaration, if there is no prior declaration, the program is
10263 // ill-formed.
10264 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCall8a407372010-10-14 22:22:28 +000010265 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +000010266
John McCall29ae6e52010-10-13 05:45:15 +000010267 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +000010268 DC = CurContext;
10269 while (true) {
10270 // Skip class contexts. If someone can cite chapter and verse
10271 // for this behavior, that would be nice --- it's what GCC and
10272 // EDG do, and it seems like a reasonable intent, but the spec
10273 // really only says that checks for unqualified existing
10274 // declarations should stop at the nearest enclosing namespace,
10275 // not that they should only consider the nearest enclosing
10276 // namespace.
Douglas Gregor182ddf02009-09-28 00:08:27 +000010277 while (DC->isRecord())
10278 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +000010279
John McCall68263142009-11-18 22:49:29 +000010280 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +000010281
10282 // TODO: decide what we think about using declarations.
John McCall29ae6e52010-10-13 05:45:15 +000010283 if (isLocal || !Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +000010284 break;
John McCall29ae6e52010-10-13 05:45:15 +000010285
John McCall8a407372010-10-14 22:22:28 +000010286 if (isTemplateId) {
10287 if (isa<TranslationUnitDecl>(DC)) break;
10288 } else {
10289 if (DC->isFileContext()) break;
10290 }
John McCall67d1a672009-08-06 02:15:43 +000010291 DC = DC->getParent();
10292 }
10293
10294 // C++ [class.friend]p1: A friend of a class is a function or
10295 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000010296 // C++11 changes this for both friend types and functions.
John McCall7f27d922009-08-06 20:49:32 +000010297 // Most C++ 98 compilers do seem to give an error here, so
10298 // we do, too.
Richard Smithebaf0e62011-10-18 20:49:44 +000010299 if (!Previous.empty() && DC->Equals(CurContext))
10300 Diag(DS.getFriendSpecLoc(),
10301 getLangOptions().CPlusPlus0x ?
10302 diag::warn_cxx98_compat_friend_is_member :
10303 diag::err_friend_is_member);
John McCall337ec3d2010-10-12 23:13:28 +000010304
John McCall380aaa42010-10-13 06:22:15 +000010305 DCScope = getScopeForDeclContext(S, DC);
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000010306
Douglas Gregor883af832011-10-10 01:11:59 +000010307 // C++ [class.friend]p6:
10308 // A function can be defined in a friend declaration of a class if and
10309 // only if the class is a non-local class (9.8), the function name is
10310 // unqualified, and the function has namespace scope.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010311 if (isLocal && D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010312 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
10313 }
10314
John McCall337ec3d2010-10-12 23:13:28 +000010315 // - There's a non-dependent scope specifier, in which case we
10316 // compute it and do a previous lookup there for a function
10317 // or function template.
10318 } else if (!SS.getScopeRep()->isDependent()) {
10319 DC = computeDeclContext(SS);
10320 if (!DC) return 0;
10321
10322 if (RequireCompleteDeclContext(SS, DC)) return 0;
10323
10324 LookupQualifiedName(Previous, DC);
10325
10326 // Ignore things found implicitly in the wrong scope.
10327 // TODO: better diagnostics for this case. Suggesting the right
10328 // qualified scope would be nice...
10329 LookupResult::Filter F = Previous.makeFilter();
10330 while (F.hasNext()) {
10331 NamedDecl *D = F.next();
10332 if (!DC->InEnclosingNamespaceSetOf(
10333 D->getDeclContext()->getRedeclContext()))
10334 F.erase();
10335 }
10336 F.done();
10337
10338 if (Previous.empty()) {
10339 D.setInvalidType();
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010340 Diag(Loc, diag::err_qualified_friend_not_found)
10341 << Name << TInfo->getType();
John McCall337ec3d2010-10-12 23:13:28 +000010342 return 0;
10343 }
10344
10345 // C++ [class.friend]p1: A friend of a class is a function or
10346 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000010347 if (DC->Equals(CurContext))
10348 Diag(DS.getFriendSpecLoc(),
10349 getLangOptions().CPlusPlus0x ?
10350 diag::warn_cxx98_compat_friend_is_member :
10351 diag::err_friend_is_member);
Douglas Gregor883af832011-10-10 01:11:59 +000010352
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010353 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010354 // C++ [class.friend]p6:
10355 // A function can be defined in a friend declaration of a class if and
10356 // only if the class is a non-local class (9.8), the function name is
10357 // unqualified, and the function has namespace scope.
10358 SemaDiagnosticBuilder DB
10359 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
10360
10361 DB << SS.getScopeRep();
10362 if (DC->isFileContext())
10363 DB << FixItHint::CreateRemoval(SS.getRange());
10364 SS.clear();
10365 }
John McCall337ec3d2010-10-12 23:13:28 +000010366
10367 // - There's a scope specifier that does not match any template
10368 // parameter lists, in which case we use some arbitrary context,
10369 // create a method or method template, and wait for instantiation.
10370 // - There's a scope specifier that does match some template
10371 // parameter lists, which we don't handle right now.
10372 } else {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010373 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010374 // C++ [class.friend]p6:
10375 // A function can be defined in a friend declaration of a class if and
10376 // only if the class is a non-local class (9.8), the function name is
10377 // unqualified, and the function has namespace scope.
10378 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
10379 << SS.getScopeRep();
10380 }
10381
John McCall337ec3d2010-10-12 23:13:28 +000010382 DC = CurContext;
10383 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +000010384 }
Douglas Gregor883af832011-10-10 01:11:59 +000010385
John McCall29ae6e52010-10-13 05:45:15 +000010386 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +000010387 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +000010388 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
10389 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
10390 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +000010391 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +000010392 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
10393 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +000010394 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010395 }
John McCall67d1a672009-08-06 02:15:43 +000010396 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010397
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000010398 // FIXME: This is an egregious hack to cope with cases where the scope stack
10399 // does not contain the declaration context, i.e., in an out-of-line
10400 // definition of a class.
10401 Scope FakeDCScope(S, Scope::DeclScope, Diags);
10402 if (!DCScope) {
10403 FakeDCScope.setEntity(DC);
10404 DCScope = &FakeDCScope;
10405 }
10406
Francois Pichetaf0f4d02011-08-14 03:52:19 +000010407 bool AddToScope = true;
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010408 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
10409 move(TemplateParams), AddToScope);
John McCalld226f652010-08-21 09:40:31 +000010410 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +000010411
Douglas Gregor182ddf02009-09-28 00:08:27 +000010412 assert(ND->getDeclContext() == DC);
10413 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +000010414
John McCallab88d972009-08-31 22:39:49 +000010415 // Add the function declaration to the appropriate lookup tables,
10416 // adjusting the redeclarations list as necessary. We don't
10417 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +000010418 //
John McCallab88d972009-08-31 22:39:49 +000010419 // Also update the scope-based lookup if the target context's
10420 // lookup context is in lexical scope.
10421 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000010422 DC = DC->getRedeclContext();
Douglas Gregor182ddf02009-09-28 00:08:27 +000010423 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCallab88d972009-08-31 22:39:49 +000010424 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +000010425 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +000010426 }
John McCall02cace72009-08-28 07:59:38 +000010427
10428 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +000010429 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +000010430 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +000010431 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +000010432 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +000010433
John McCall337ec3d2010-10-12 23:13:28 +000010434 if (ND->isInvalidDecl())
10435 FrD->setInvalidDecl();
John McCall6102ca12010-10-16 06:59:13 +000010436 else {
10437 FunctionDecl *FD;
10438 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
10439 FD = FTD->getTemplatedDecl();
10440 else
10441 FD = cast<FunctionDecl>(ND);
10442
10443 // Mark templated-scope function declarations as unsupported.
10444 if (FD->getNumTemplateParameterLists())
10445 FrD->setUnsupportedFriend(true);
10446 }
John McCall337ec3d2010-10-12 23:13:28 +000010447
John McCalld226f652010-08-21 09:40:31 +000010448 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +000010449}
10450
John McCalld226f652010-08-21 09:40:31 +000010451void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
10452 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +000010453
Sebastian Redl50de12f2009-03-24 22:27:57 +000010454 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
10455 if (!Fn) {
10456 Diag(DelLoc, diag::err_deleted_non_function);
10457 return;
10458 }
Douglas Gregoref96ee02012-01-14 16:38:05 +000010459 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
Sebastian Redl50de12f2009-03-24 22:27:57 +000010460 Diag(DelLoc, diag::err_deleted_decl_not_first);
10461 Diag(Prev->getLocation(), diag::note_previous_declaration);
10462 // If the declaration wasn't the first, we delete the function anyway for
10463 // recovery.
10464 }
Sean Hunt10620eb2011-05-06 20:44:56 +000010465 Fn->setDeletedAsWritten();
Sebastian Redl50de12f2009-03-24 22:27:57 +000010466}
Sebastian Redl13e88542009-04-27 21:33:24 +000010467
Sean Hunte4246a62011-05-12 06:15:49 +000010468void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
10469 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
10470
10471 if (MD) {
Sean Hunteb88ae52011-05-23 21:07:59 +000010472 if (MD->getParent()->isDependentType()) {
10473 MD->setDefaulted();
10474 MD->setExplicitlyDefaulted();
10475 return;
10476 }
10477
Sean Hunte4246a62011-05-12 06:15:49 +000010478 CXXSpecialMember Member = getSpecialMember(MD);
10479 if (Member == CXXInvalid) {
10480 Diag(DefaultLoc, diag::err_default_special_members);
10481 return;
10482 }
10483
10484 MD->setDefaulted();
10485 MD->setExplicitlyDefaulted();
10486
Sean Huntcd10dec2011-05-23 23:14:04 +000010487 // If this definition appears within the record, do the checking when
10488 // the record is complete.
10489 const FunctionDecl *Primary = MD;
10490 if (MD->getTemplatedKind() != FunctionDecl::TK_NonTemplate)
10491 // Find the uninstantiated declaration that actually had the '= default'
10492 // on it.
10493 MD->getTemplateInstantiationPattern()->isDefined(Primary);
10494
10495 if (Primary == Primary->getCanonicalDecl())
Sean Hunte4246a62011-05-12 06:15:49 +000010496 return;
10497
10498 switch (Member) {
10499 case CXXDefaultConstructor: {
10500 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10501 CheckExplicitlyDefaultedDefaultConstructor(CD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010502 if (!CD->isInvalidDecl())
10503 DefineImplicitDefaultConstructor(DefaultLoc, CD);
10504 break;
10505 }
10506
10507 case CXXCopyConstructor: {
10508 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10509 CheckExplicitlyDefaultedCopyConstructor(CD);
10510 if (!CD->isInvalidDecl())
10511 DefineImplicitCopyConstructor(DefaultLoc, CD);
Sean Hunte4246a62011-05-12 06:15:49 +000010512 break;
10513 }
Sean Huntcb45a0f2011-05-12 22:46:25 +000010514
Sean Hunt2b188082011-05-14 05:23:28 +000010515 case CXXCopyAssignment: {
10516 CheckExplicitlyDefaultedCopyAssignment(MD);
10517 if (!MD->isInvalidDecl())
10518 DefineImplicitCopyAssignment(DefaultLoc, MD);
10519 break;
10520 }
10521
Sean Huntcb45a0f2011-05-12 22:46:25 +000010522 case CXXDestructor: {
10523 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
10524 CheckExplicitlyDefaultedDestructor(DD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010525 if (!DD->isInvalidDecl())
10526 DefineImplicitDestructor(DefaultLoc, DD);
Sean Huntcb45a0f2011-05-12 22:46:25 +000010527 break;
10528 }
10529
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010530 case CXXMoveConstructor: {
10531 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10532 CheckExplicitlyDefaultedMoveConstructor(CD);
10533 if (!CD->isInvalidDecl())
10534 DefineImplicitMoveConstructor(DefaultLoc, CD);
Sean Hunt82713172011-05-25 23:16:36 +000010535 break;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010536 }
Sean Hunt82713172011-05-25 23:16:36 +000010537
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010538 case CXXMoveAssignment: {
10539 CheckExplicitlyDefaultedMoveAssignment(MD);
10540 if (!MD->isInvalidDecl())
10541 DefineImplicitMoveAssignment(DefaultLoc, MD);
10542 break;
10543 }
10544
10545 case CXXInvalid:
David Blaikieb219cfc2011-09-23 05:06:16 +000010546 llvm_unreachable("Invalid special member.");
Sean Hunte4246a62011-05-12 06:15:49 +000010547 }
10548 } else {
10549 Diag(DefaultLoc, diag::err_default_special_members);
10550 }
10551}
10552
Sebastian Redl13e88542009-04-27 21:33:24 +000010553static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +000010554 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +000010555 Stmt *SubStmt = *CI;
10556 if (!SubStmt)
10557 continue;
10558 if (isa<ReturnStmt>(SubStmt))
10559 Self.Diag(SubStmt->getSourceRange().getBegin(),
10560 diag::err_return_in_constructor_handler);
10561 if (!isa<Expr>(SubStmt))
10562 SearchForReturnInStmt(Self, SubStmt);
10563 }
10564}
10565
10566void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
10567 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
10568 CXXCatchStmt *Handler = TryBlock->getHandler(I);
10569 SearchForReturnInStmt(*this, Handler);
10570 }
10571}
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010572
Mike Stump1eb44332009-09-09 15:08:12 +000010573bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010574 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +000010575 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
10576 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010577
Chandler Carruth73857792010-02-15 11:53:20 +000010578 if (Context.hasSameType(NewTy, OldTy) ||
10579 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010580 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000010581
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010582 // Check if the return types are covariant
10583 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +000010584
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010585 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010586 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
10587 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010588 NewClassTy = NewPT->getPointeeType();
10589 OldClassTy = OldPT->getPointeeType();
10590 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010591 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
10592 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
10593 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
10594 NewClassTy = NewRT->getPointeeType();
10595 OldClassTy = OldRT->getPointeeType();
10596 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010597 }
10598 }
Mike Stump1eb44332009-09-09 15:08:12 +000010599
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010600 // The return types aren't either both pointers or references to a class type.
10601 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +000010602 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010603 diag::err_different_return_type_for_overriding_virtual_function)
10604 << New->getDeclName() << NewTy << OldTy;
10605 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +000010606
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010607 return true;
10608 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010609
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010610 // C++ [class.virtual]p6:
10611 // If the return type of D::f differs from the return type of B::f, the
10612 // class type in the return type of D::f shall be complete at the point of
10613 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +000010614 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
10615 if (!RT->isBeingDefined() &&
10616 RequireCompleteType(New->getLocation(), NewClassTy,
10617 PDiag(diag::err_covariant_return_incomplete)
10618 << New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010619 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +000010620 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010621
Douglas Gregora4923eb2009-11-16 21:35:15 +000010622 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010623 // Check if the new class derives from the old class.
10624 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
10625 Diag(New->getLocation(),
10626 diag::err_covariant_return_not_derived)
10627 << New->getDeclName() << NewTy << OldTy;
10628 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10629 return true;
10630 }
Mike Stump1eb44332009-09-09 15:08:12 +000010631
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010632 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +000010633 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +000010634 diag::err_covariant_return_inaccessible_base,
10635 diag::err_covariant_return_ambiguous_derived_to_base_conv,
10636 // FIXME: Should this point to the return type?
10637 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCalleee1d542011-02-14 07:13:47 +000010638 // FIXME: this note won't trigger for delayed access control
10639 // diagnostics, and it's impossible to get an undelayed error
10640 // here from access control during the original parse because
10641 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010642 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10643 return true;
10644 }
10645 }
Mike Stump1eb44332009-09-09 15:08:12 +000010646
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010647 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010648 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010649 Diag(New->getLocation(),
10650 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010651 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010652 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10653 return true;
10654 };
Mike Stump1eb44332009-09-09 15:08:12 +000010655
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010656
10657 // The new class type must have the same or less qualifiers as the old type.
10658 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
10659 Diag(New->getLocation(),
10660 diag::err_covariant_return_type_class_type_more_qualified)
10661 << New->getDeclName() << NewTy << OldTy;
10662 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10663 return true;
10664 };
Mike Stump1eb44332009-09-09 15:08:12 +000010665
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010666 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010667}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010668
Douglas Gregor4ba31362009-12-01 17:24:26 +000010669/// \brief Mark the given method pure.
10670///
10671/// \param Method the method to be marked pure.
10672///
10673/// \param InitRange the source range that covers the "0" initializer.
10674bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnara796aa442011-03-12 11:17:06 +000010675 SourceLocation EndLoc = InitRange.getEnd();
10676 if (EndLoc.isValid())
10677 Method->setRangeEnd(EndLoc);
10678
Douglas Gregor4ba31362009-12-01 17:24:26 +000010679 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
10680 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +000010681 return false;
Abramo Bagnara796aa442011-03-12 11:17:06 +000010682 }
Douglas Gregor4ba31362009-12-01 17:24:26 +000010683
10684 if (!Method->isInvalidDecl())
10685 Diag(Method->getLocation(), diag::err_non_virtual_pure)
10686 << Method->getDeclName() << InitRange;
10687 return true;
10688}
10689
John McCall731ad842009-12-19 09:28:58 +000010690/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
10691/// an initializer for the out-of-line declaration 'Dcl'. The scope
10692/// is a fresh scope pushed for just this purpose.
10693///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010694/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
10695/// static data member of class X, names should be looked up in the scope of
10696/// class X.
John McCalld226f652010-08-21 09:40:31 +000010697void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010698 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000010699 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010700
John McCall731ad842009-12-19 09:28:58 +000010701 // We should only get called for declarations with scope specifiers, like:
10702 // int foo::bar;
10703 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000010704 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010705}
10706
10707/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +000010708/// initializer for the out-of-line declaration 'D'.
10709void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010710 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000010711 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010712
John McCall731ad842009-12-19 09:28:58 +000010713 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000010714 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010715}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010716
10717/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
10718/// C++ if/switch/while/for statement.
10719/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +000010720DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010721 // C++ 6.4p2:
10722 // The declarator shall not specify a function or an array.
10723 // The type-specifier-seq shall not contain typedef and shall not declare a
10724 // new class or enumeration.
10725 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
10726 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000010727
10728 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor9a30c992011-07-05 16:13:20 +000010729 if (!Dcl)
10730 return true;
10731
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000010732 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
10733 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010734 << D.getSourceRange();
Douglas Gregor9a30c992011-07-05 16:13:20 +000010735 return true;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010736 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010737
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010738 return Dcl;
10739}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010740
Douglas Gregordfe65432011-07-28 19:11:31 +000010741void Sema::LoadExternalVTableUses() {
10742 if (!ExternalSource)
10743 return;
10744
10745 SmallVector<ExternalVTableUse, 4> VTables;
10746 ExternalSource->ReadUsedVTables(VTables);
10747 SmallVector<VTableUse, 4> NewUses;
10748 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
10749 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
10750 = VTablesUsed.find(VTables[I].Record);
10751 // Even if a definition wasn't required before, it may be required now.
10752 if (Pos != VTablesUsed.end()) {
10753 if (!Pos->second && VTables[I].DefinitionRequired)
10754 Pos->second = true;
10755 continue;
10756 }
10757
10758 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
10759 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
10760 }
10761
10762 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
10763}
10764
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010765void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
10766 bool DefinitionRequired) {
10767 // Ignore any vtable uses in unevaluated operands or for classes that do
10768 // not have a vtable.
10769 if (!Class->isDynamicClass() || Class->isDependentContext() ||
10770 CurContext->isDependentContext() ||
Eli Friedman78a54242012-01-21 04:44:06 +000010771 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolabbf58bb2010-03-10 02:19:29 +000010772 return;
10773
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010774 // Try to insert this class into the map.
Douglas Gregordfe65432011-07-28 19:11:31 +000010775 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010776 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10777 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
10778 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
10779 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +000010780 // If we already had an entry, check to see if we are promoting this vtable
10781 // to required a definition. If so, we need to reappend to the VTableUses
10782 // list, since we may have already processed the first entry.
10783 if (DefinitionRequired && !Pos.first->second) {
10784 Pos.first->second = true;
10785 } else {
10786 // Otherwise, we can early exit.
10787 return;
10788 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010789 }
10790
10791 // Local classes need to have their virtual members marked
10792 // immediately. For all other classes, we mark their virtual members
10793 // at the end of the translation unit.
10794 if (Class->isLocalClass())
10795 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +000010796 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010797 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +000010798}
10799
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010800bool Sema::DefineUsedVTables() {
Douglas Gregordfe65432011-07-28 19:11:31 +000010801 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010802 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +000010803 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +000010804
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010805 // Note: The VTableUses vector could grow as a result of marking
10806 // the members of a class as "used", so we check the size each
10807 // time through the loop and prefer indices (with are stable) to
10808 // iterators (which are not).
Douglas Gregor78844032011-04-22 22:25:37 +000010809 bool DefinedAnything = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010810 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +000010811 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010812 if (!Class)
10813 continue;
10814
10815 SourceLocation Loc = VTableUses[I].second;
10816
10817 // If this class has a key function, but that key function is
10818 // defined in another translation unit, we don't need to emit the
10819 // vtable even though we're using it.
10820 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +000010821 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010822 switch (KeyFunction->getTemplateSpecializationKind()) {
10823 case TSK_Undeclared:
10824 case TSK_ExplicitSpecialization:
10825 case TSK_ExplicitInstantiationDeclaration:
10826 // The key function is in another translation unit.
10827 continue;
10828
10829 case TSK_ExplicitInstantiationDefinition:
10830 case TSK_ImplicitInstantiation:
10831 // We will be instantiating the key function.
10832 break;
10833 }
10834 } else if (!KeyFunction) {
10835 // If we have a class with no key function that is the subject
10836 // of an explicit instantiation declaration, suppress the
10837 // vtable; it will live with the explicit instantiation
10838 // definition.
10839 bool IsExplicitInstantiationDeclaration
10840 = Class->getTemplateSpecializationKind()
10841 == TSK_ExplicitInstantiationDeclaration;
10842 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
10843 REnd = Class->redecls_end();
10844 R != REnd; ++R) {
10845 TemplateSpecializationKind TSK
10846 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
10847 if (TSK == TSK_ExplicitInstantiationDeclaration)
10848 IsExplicitInstantiationDeclaration = true;
10849 else if (TSK == TSK_ExplicitInstantiationDefinition) {
10850 IsExplicitInstantiationDeclaration = false;
10851 break;
10852 }
10853 }
10854
10855 if (IsExplicitInstantiationDeclaration)
10856 continue;
10857 }
10858
10859 // Mark all of the virtual members of this class as referenced, so
10860 // that we can build a vtable. Then, tell the AST consumer that a
10861 // vtable for this class is required.
Douglas Gregor78844032011-04-22 22:25:37 +000010862 DefinedAnything = true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010863 MarkVirtualMembersReferenced(Loc, Class);
10864 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10865 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
10866
10867 // Optionally warn if we're emitting a weak vtable.
10868 if (Class->getLinkage() == ExternalLinkage &&
10869 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Douglas Gregora120d012011-09-23 19:04:03 +000010870 const FunctionDecl *KeyFunctionDef = 0;
10871 if (!KeyFunction ||
10872 (KeyFunction->hasBody(KeyFunctionDef) &&
10873 KeyFunctionDef->isInlined()))
David Blaikie44d95b52011-12-09 18:32:50 +000010874 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
10875 TSK_ExplicitInstantiationDefinition
10876 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
10877 << Class;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010878 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010879 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010880 VTableUses.clear();
10881
Douglas Gregor78844032011-04-22 22:25:37 +000010882 return DefinedAnything;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010883}
Anders Carlssond6a637f2009-12-07 08:24:59 +000010884
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010885void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
10886 const CXXRecordDecl *RD) {
Anders Carlssond6a637f2009-12-07 08:24:59 +000010887 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
10888 e = RD->method_end(); i != e; ++i) {
10889 CXXMethodDecl *MD = *i;
10890
10891 // C++ [basic.def.odr]p2:
10892 // [...] A virtual member function is used if it is not pure. [...]
10893 if (MD->isVirtual() && !MD->isPure())
Eli Friedman5f2987c2012-02-02 03:46:19 +000010894 MarkFunctionReferenced(Loc, MD);
Anders Carlssond6a637f2009-12-07 08:24:59 +000010895 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010896
10897 // Only classes that have virtual bases need a VTT.
10898 if (RD->getNumVBases() == 0)
10899 return;
10900
10901 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
10902 e = RD->bases_end(); i != e; ++i) {
10903 const CXXRecordDecl *Base =
10904 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010905 if (Base->getNumVBases() == 0)
10906 continue;
10907 MarkVirtualMembersReferenced(Loc, Base);
10908 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000010909}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010910
10911/// SetIvarInitializers - This routine builds initialization ASTs for the
10912/// Objective-C implementation whose ivars need be initialized.
10913void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
10914 if (!getLangOptions().CPlusPlus)
10915 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +000010916 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +000010917 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010918 CollectIvarsToConstructOrDestruct(OID, ivars);
10919 if (ivars.empty())
10920 return;
Chris Lattner5f9e2722011-07-23 10:55:15 +000010921 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010922 for (unsigned i = 0; i < ivars.size(); i++) {
10923 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010924 if (Field->isInvalidDecl())
10925 continue;
10926
Sean Huntcbb67482011-01-08 20:30:50 +000010927 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010928 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
10929 InitializationKind InitKind =
10930 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
10931
10932 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +000010933 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +000010934 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregor53c374f2010-12-07 00:41:46 +000010935 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010936 // Note, MemberInit could actually come back empty if no initialization
10937 // is required (e.g., because it would call a trivial default constructor)
10938 if (!MemberInit.get() || MemberInit.isInvalid())
10939 continue;
John McCallb4eb64d2010-10-08 02:01:28 +000010940
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010941 Member =
Sean Huntcbb67482011-01-08 20:30:50 +000010942 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
10943 SourceLocation(),
10944 MemberInit.takeAs<Expr>(),
10945 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010946 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010947
10948 // Be sure that the destructor is accessible and is marked as referenced.
10949 if (const RecordType *RecordTy
10950 = Context.getBaseElementType(Field->getType())
10951 ->getAs<RecordType>()) {
10952 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +000010953 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010954 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010955 CheckDestructorAccess(Field->getLocation(), Destructor,
10956 PDiag(diag::err_access_dtor_ivar)
10957 << Context.getBaseElementType(Field->getType()));
10958 }
10959 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010960 }
10961 ObjCImplementation->setIvarInitializers(Context,
10962 AllToInit.data(), AllToInit.size());
10963 }
10964}
Sean Huntfe57eef2011-05-04 05:57:24 +000010965
Sean Huntebcbe1d2011-05-04 23:29:54 +000010966static
10967void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
10968 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
10969 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
10970 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
10971 Sema &S) {
10972 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
10973 CE = Current.end();
10974 if (Ctor->isInvalidDecl())
10975 return;
10976
10977 const FunctionDecl *FNTarget = 0;
10978 CXXConstructorDecl *Target;
10979
10980 // We ignore the result here since if we don't have a body, Target will be
10981 // null below.
10982 (void)Ctor->getTargetConstructor()->hasBody(FNTarget);
10983 Target
10984= const_cast<CXXConstructorDecl*>(cast_or_null<CXXConstructorDecl>(FNTarget));
10985
10986 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
10987 // Avoid dereferencing a null pointer here.
10988 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
10989
10990 if (!Current.insert(Canonical))
10991 return;
10992
10993 // We know that beyond here, we aren't chaining into a cycle.
10994 if (!Target || !Target->isDelegatingConstructor() ||
10995 Target->isInvalidDecl() || Valid.count(TCanonical)) {
10996 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
10997 Valid.insert(*CI);
10998 Current.clear();
10999 // We've hit a cycle.
11000 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
11001 Current.count(TCanonical)) {
11002 // If we haven't diagnosed this cycle yet, do so now.
11003 if (!Invalid.count(TCanonical)) {
11004 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Sean Huntc1598702011-05-05 00:05:47 +000011005 diag::warn_delegating_ctor_cycle)
Sean Huntebcbe1d2011-05-04 23:29:54 +000011006 << Ctor;
11007
11008 // Don't add a note for a function delegating directo to itself.
11009 if (TCanonical != Canonical)
11010 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
11011
11012 CXXConstructorDecl *C = Target;
11013 while (C->getCanonicalDecl() != Canonical) {
11014 (void)C->getTargetConstructor()->hasBody(FNTarget);
11015 assert(FNTarget && "Ctor cycle through bodiless function");
11016
11017 C
11018 = const_cast<CXXConstructorDecl*>(cast<CXXConstructorDecl>(FNTarget));
11019 S.Diag(C->getLocation(), diag::note_which_delegates_to);
11020 }
11021 }
11022
11023 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11024 Invalid.insert(*CI);
11025 Current.clear();
11026 } else {
11027 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
11028 }
11029}
11030
11031
Sean Huntfe57eef2011-05-04 05:57:24 +000011032void Sema::CheckDelegatingCtorCycles() {
11033 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
11034
Sean Huntebcbe1d2011-05-04 23:29:54 +000011035 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11036 CE = Current.end();
Sean Huntfe57eef2011-05-04 05:57:24 +000011037
Douglas Gregor0129b562011-07-27 21:57:17 +000011038 for (DelegatingCtorDeclsType::iterator
11039 I = DelegatingCtorDecls.begin(ExternalSource),
Sean Huntebcbe1d2011-05-04 23:29:54 +000011040 E = DelegatingCtorDecls.end();
11041 I != E; ++I) {
11042 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Sean Huntfe57eef2011-05-04 05:57:24 +000011043 }
Sean Huntebcbe1d2011-05-04 23:29:54 +000011044
11045 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
11046 (*CI)->setInvalidDecl();
Sean Huntfe57eef2011-05-04 05:57:24 +000011047}
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000011048
11049/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
11050Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
11051 // Implicitly declared functions (e.g. copy constructors) are
11052 // __host__ __device__
11053 if (D->isImplicit())
11054 return CFT_HostDevice;
11055
11056 if (D->hasAttr<CUDAGlobalAttr>())
11057 return CFT_Global;
11058
11059 if (D->hasAttr<CUDADeviceAttr>()) {
11060 if (D->hasAttr<CUDAHostAttr>())
11061 return CFT_HostDevice;
11062 else
11063 return CFT_Device;
11064 }
11065
11066 return CFT_Host;
11067}
11068
11069bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
11070 CUDAFunctionTarget CalleeTarget) {
11071 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
11072 // Callable from the device only."
11073 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
11074 return true;
11075
11076 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
11077 // Callable from the host only."
11078 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
11079 // Callable from the host only."
11080 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
11081 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
11082 return true;
11083
11084 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
11085 return true;
11086
11087 return false;
11088}