blob: ff1cbd14b6ab34a78a5f8150e87f4b266008ce6b [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"
Richard Trieude5e75c2012-06-14 23:11:34 +000026#include "clang/AST/EvaluatedExprVisitor.h"
Sean Hunt41717662011-02-26 19:13:13 +000027#include "clang/AST/ExprCXX.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000028#include "clang/AST/RecordLayout.h"
Douglas Gregorcefc3af2012-04-16 07:05:22 +000029#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000030#include "clang/AST/StmtVisitor.h"
Douglas Gregor802ab452009-12-02 22:36:29 +000031#include "clang/AST/TypeLoc.h"
Douglas Gregor02189362008-10-22 21:13:31 +000032#include "clang/AST/TypeOrdering.h"
John McCall19510852010-08-20 18:27:03 +000033#include "clang/Sema/DeclSpec.h"
34#include "clang/Sema/ParsedTemplate.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000035#include "clang/Basic/PartialDiagnostic.h"
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +000036#include "clang/Lex/Preprocessor.h"
Benjamin Kramer8fe83e12012-02-04 13:45:25 +000037#include "llvm/ADT/SmallString.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000038#include "llvm/ADT/STLExtras.h"
Douglas Gregorf8268ae2008-10-22 17:49:05 +000039#include <map>
Douglas Gregora8f32e02009-10-06 17:59:45 +000040#include <set>
Chris Lattner3d1cee32008-04-08 05:04:30 +000041
42using namespace clang;
43
Chris Lattner8123a952008-04-10 02:22:51 +000044//===----------------------------------------------------------------------===//
45// CheckDefaultArgumentVisitor
46//===----------------------------------------------------------------------===//
47
Chris Lattner9e979552008-04-12 23:52:44 +000048namespace {
49 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
50 /// the default argument of a parameter to determine whether it
51 /// contains any ill-formed subexpressions. For example, this will
52 /// diagnose the use of local variables or parameters within the
53 /// default argument expression.
Benjamin Kramer85b45212009-11-28 19:45:26 +000054 class CheckDefaultArgumentVisitor
Chris Lattnerb77792e2008-07-26 22:17:49 +000055 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattner9e979552008-04-12 23:52:44 +000056 Expr *DefaultArg;
57 Sema *S;
Chris Lattner8123a952008-04-10 02:22:51 +000058
Chris Lattner9e979552008-04-12 23:52:44 +000059 public:
Mike Stump1eb44332009-09-09 15:08:12 +000060 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattner9e979552008-04-12 23:52:44 +000061 : DefaultArg(defarg), S(s) {}
Chris Lattner8123a952008-04-10 02:22:51 +000062
Chris Lattner9e979552008-04-12 23:52:44 +000063 bool VisitExpr(Expr *Node);
64 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor796da182008-11-04 14:32:21 +000065 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Douglas Gregorf0459f82012-02-10 23:30:22 +000066 bool VisitLambdaExpr(LambdaExpr *Lambda);
Chris Lattner9e979552008-04-12 23:52:44 +000067 };
Chris Lattner8123a952008-04-10 02:22:51 +000068
Chris Lattner9e979552008-04-12 23:52:44 +000069 /// VisitExpr - Visit all of the children of this expression.
70 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
71 bool IsInvalid = false;
John McCall7502c1d2011-02-13 04:07:26 +000072 for (Stmt::child_range I = Node->children(); I; ++I)
Chris Lattnerb77792e2008-07-26 22:17:49 +000073 IsInvalid |= Visit(*I);
Chris Lattner9e979552008-04-12 23:52:44 +000074 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000075 }
76
Chris Lattner9e979552008-04-12 23:52:44 +000077 /// VisitDeclRefExpr - Visit a reference to a declaration, to
78 /// determine whether this declaration can be used in the default
79 /// argument expression.
80 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000081 NamedDecl *Decl = DRE->getDecl();
Chris Lattner9e979552008-04-12 23:52:44 +000082 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
83 // C++ [dcl.fct.default]p9
84 // Default arguments are evaluated each time the function is
85 // called. The order of evaluation of function arguments is
86 // unspecified. Consequently, parameters of a function shall not
87 // be used in default argument expressions, even if they are not
88 // evaluated. Parameters of a function declared before a default
89 // argument expression are in scope and can hide namespace and
90 // class member names.
Daniel Dunbar96a00142012-03-09 18:35:03 +000091 return S->Diag(DRE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000092 diag::err_param_default_argument_references_param)
Chris Lattner08631c52008-11-23 21:45:46 +000093 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff248a7532008-04-15 22:42:06 +000094 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000095 // C++ [dcl.fct.default]p7
96 // Local variables shall not be used in default argument
97 // expressions.
John McCallb6bbcc92010-10-15 04:57:14 +000098 if (VDecl->isLocalVarDecl())
Daniel Dunbar96a00142012-03-09 18:35:03 +000099 return S->Diag(DRE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000100 diag::err_param_default_argument_references_local)
Chris Lattner08631c52008-11-23 21:45:46 +0000101 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000102 }
Chris Lattner8123a952008-04-10 02:22:51 +0000103
Douglas Gregor3996f232008-11-04 13:41:56 +0000104 return false;
105 }
Chris Lattner9e979552008-04-12 23:52:44 +0000106
Douglas Gregor796da182008-11-04 14:32:21 +0000107 /// VisitCXXThisExpr - Visit a C++ "this" expression.
108 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
109 // C++ [dcl.fct.default]p8:
110 // The keyword this shall not be used in a default argument of a
111 // member function.
Daniel Dunbar96a00142012-03-09 18:35:03 +0000112 return S->Diag(ThisE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000113 diag::err_param_default_argument_references_this)
114 << ThisE->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000115 }
Douglas Gregorf0459f82012-02-10 23:30:22 +0000116
117 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
118 // C++11 [expr.lambda.prim]p13:
119 // A lambda-expression appearing in a default argument shall not
120 // implicitly or explicitly capture any entity.
121 if (Lambda->capture_begin() == Lambda->capture_end())
122 return false;
123
124 return S->Diag(Lambda->getLocStart(),
125 diag::err_lambda_capture_default_arg);
126 }
Chris Lattner8123a952008-04-10 02:22:51 +0000127}
128
Richard Smithe6975e92012-04-17 00:58:00 +0000129void Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
130 CXXMethodDecl *Method) {
Richard Smithb9d0b762012-07-27 04:22:15 +0000131 // If we have an MSAny spec already, don't bother.
132 if (!Method || ComputedEST == EST_MSAny)
Sean Hunt001cad92011-05-10 00:49:42 +0000133 return;
134
135 const FunctionProtoType *Proto
136 = Method->getType()->getAs<FunctionProtoType>();
Richard Smithe6975e92012-04-17 00:58:00 +0000137 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
138 if (!Proto)
139 return;
Sean Hunt001cad92011-05-10 00:49:42 +0000140
141 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
142
143 // If this function can throw any exceptions, make a note of that.
Richard Smithb9d0b762012-07-27 04:22:15 +0000144 if (EST == EST_MSAny || EST == EST_None) {
Sean Hunt001cad92011-05-10 00:49:42 +0000145 ClearExceptions();
146 ComputedEST = EST;
147 return;
148 }
149
Richard Smith7a614d82011-06-11 17:19:42 +0000150 // FIXME: If the call to this decl is using any of its default arguments, we
151 // need to search them for potentially-throwing calls.
152
Sean Hunt001cad92011-05-10 00:49:42 +0000153 // If this function has a basic noexcept, it doesn't affect the outcome.
154 if (EST == EST_BasicNoexcept)
155 return;
156
157 // If we have a throw-all spec at this point, ignore the function.
158 if (ComputedEST == EST_None)
159 return;
160
161 // If we're still at noexcept(true) and there's a nothrow() callee,
162 // change to that specification.
163 if (EST == EST_DynamicNone) {
164 if (ComputedEST == EST_BasicNoexcept)
165 ComputedEST = EST_DynamicNone;
166 return;
167 }
168
169 // Check out noexcept specs.
170 if (EST == EST_ComputedNoexcept) {
Richard Smithe6975e92012-04-17 00:58:00 +0000171 FunctionProtoType::NoexceptResult NR =
172 Proto->getNoexceptSpec(Self->Context);
Sean Hunt001cad92011-05-10 00:49:42 +0000173 assert(NR != FunctionProtoType::NR_NoNoexcept &&
174 "Must have noexcept result for EST_ComputedNoexcept.");
175 assert(NR != FunctionProtoType::NR_Dependent &&
176 "Should not generate implicit declarations for dependent cases, "
177 "and don't know how to handle them anyway.");
178
179 // noexcept(false) -> no spec on the new function
180 if (NR == FunctionProtoType::NR_Throw) {
181 ClearExceptions();
182 ComputedEST = EST_None;
183 }
184 // noexcept(true) won't change anything either.
185 return;
186 }
187
188 assert(EST == EST_Dynamic && "EST case not considered earlier.");
189 assert(ComputedEST != EST_None &&
190 "Shouldn't collect exceptions when throw-all is guaranteed.");
191 ComputedEST = EST_Dynamic;
192 // Record the exceptions in this function's exception specification.
193 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
194 EEnd = Proto->exception_end();
195 E != EEnd; ++E)
Richard Smithe6975e92012-04-17 00:58:00 +0000196 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(*E)))
Sean Hunt001cad92011-05-10 00:49:42 +0000197 Exceptions.push_back(*E);
198}
199
Richard Smith7a614d82011-06-11 17:19:42 +0000200void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
Richard Smithb9d0b762012-07-27 04:22:15 +0000201 if (!E || ComputedEST == EST_MSAny)
Richard Smith7a614d82011-06-11 17:19:42 +0000202 return;
203
204 // FIXME:
205 //
206 // C++0x [except.spec]p14:
NAKAMURA Takumi48579472011-06-21 03:19:28 +0000207 // [An] implicit exception-specification specifies the type-id T if and
208 // only if T is allowed by the exception-specification of a function directly
209 // invoked by f's implicit definition; f shall allow all exceptions if any
Richard Smith7a614d82011-06-11 17:19:42 +0000210 // function it directly invokes allows all exceptions, and f shall allow no
211 // exceptions if every function it directly invokes allows no exceptions.
212 //
213 // Note in particular that if an implicit exception-specification is generated
214 // for a function containing a throw-expression, that specification can still
215 // be noexcept(true).
216 //
217 // Note also that 'directly invoked' is not defined in the standard, and there
218 // is no indication that we should only consider potentially-evaluated calls.
219 //
220 // Ultimately we should implement the intent of the standard: the exception
221 // specification should be the set of exceptions which can be thrown by the
222 // implicit definition. For now, we assume that any non-nothrow expression can
223 // throw any exception.
224
Richard Smithe6975e92012-04-17 00:58:00 +0000225 if (Self->canThrow(E))
Richard Smith7a614d82011-06-11 17:19:42 +0000226 ComputedEST = EST_None;
227}
228
Anders Carlssoned961f92009-08-25 02:29:20 +0000229bool
John McCall9ae2f072010-08-23 23:25:46 +0000230Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump1eb44332009-09-09 15:08:12 +0000231 SourceLocation EqualLoc) {
Anders Carlsson5653ca52009-08-25 13:46:13 +0000232 if (RequireCompleteType(Param->getLocation(), Param->getType(),
233 diag::err_typecheck_decl_incomplete_type)) {
234 Param->setInvalidDecl();
235 return true;
236 }
237
Anders Carlssoned961f92009-08-25 02:29:20 +0000238 // C++ [dcl.fct.default]p5
239 // A default argument expression is implicitly converted (clause
240 // 4) to the parameter type. The default argument expression has
241 // the same semantic constraints as the initializer expression in
242 // a declaration of a variable of the parameter type, using the
243 // copy-initialization semantics (8.5).
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000244 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
245 Param);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000246 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
247 EqualLoc);
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000248 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
Benjamin Kramer5354e772012-08-23 23:38:35 +0000249 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000250 if (Result.isInvalid())
Anders Carlsson9351c172009-08-25 03:18:48 +0000251 return true;
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000252 Arg = Result.takeAs<Expr>();
Anders Carlssoned961f92009-08-25 02:29:20 +0000253
John McCallb4eb64d2010-10-08 02:01:28 +0000254 CheckImplicitConversions(Arg, EqualLoc);
John McCall4765fa02010-12-06 08:20:24 +0000255 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000256
Anders Carlssoned961f92009-08-25 02:29:20 +0000257 // Okay: add the default argument to the parameter
258 Param->setDefaultArg(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000259
Douglas Gregor8cfb7a32010-10-12 18:23:32 +0000260 // We have already instantiated this parameter; provide each of the
261 // instantiations with the uninstantiated default argument.
262 UnparsedDefaultArgInstantiationsMap::iterator InstPos
263 = UnparsedDefaultArgInstantiations.find(Param);
264 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
265 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
266 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
267
268 // We're done tracking this parameter's instantiations.
269 UnparsedDefaultArgInstantiations.erase(InstPos);
270 }
271
Anders Carlsson9351c172009-08-25 03:18:48 +0000272 return false;
Anders Carlssoned961f92009-08-25 02:29:20 +0000273}
274
Chris Lattner8123a952008-04-10 02:22:51 +0000275/// ActOnParamDefaultArgument - Check whether the default argument
276/// provided for a function parameter is well-formed. If so, attach it
277/// to the parameter declaration.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000278void
John McCalld226f652010-08-21 09:40:31 +0000279Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000280 Expr *DefaultArg) {
281 if (!param || !DefaultArg)
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000282 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000283
John McCalld226f652010-08-21 09:40:31 +0000284 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000285 UnparsedDefaultArgLocs.erase(Param);
286
Chris Lattner3d1cee32008-04-08 05:04:30 +0000287 // Default arguments are only permitted in C++
David Blaikie4e4d0842012-03-11 07:00:24 +0000288 if (!getLangOpts().CPlusPlus) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000289 Diag(EqualLoc, diag::err_param_default_argument)
290 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000291 Param->setInvalidDecl();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000292 return;
293 }
294
Douglas Gregor6f526752010-12-16 08:48:57 +0000295 // Check for unexpanded parameter packs.
296 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
297 Param->setInvalidDecl();
298 return;
299 }
300
Anders Carlsson66e30672009-08-25 01:02:06 +0000301 // Check that the default argument is well-formed
John McCall9ae2f072010-08-23 23:25:46 +0000302 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
303 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlsson66e30672009-08-25 01:02:06 +0000304 Param->setInvalidDecl();
305 return;
306 }
Mike Stump1eb44332009-09-09 15:08:12 +0000307
John McCall9ae2f072010-08-23 23:25:46 +0000308 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000309}
310
Douglas Gregor61366e92008-12-24 00:01:03 +0000311/// ActOnParamUnparsedDefaultArgument - We've seen a default
312/// argument for a function parameter, but we can't parse it yet
313/// because we're inside a class definition. Note that this default
314/// argument will be parsed later.
John McCalld226f652010-08-21 09:40:31 +0000315void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson5e300d12009-06-12 16:51:40 +0000316 SourceLocation EqualLoc,
317 SourceLocation ArgLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000318 if (!param)
319 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000320
John McCalld226f652010-08-21 09:40:31 +0000321 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000322 if (Param)
323 Param->setUnparsedDefaultArg();
Mike Stump1eb44332009-09-09 15:08:12 +0000324
Anders Carlsson5e300d12009-06-12 16:51:40 +0000325 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor61366e92008-12-24 00:01:03 +0000326}
327
Douglas Gregor72b505b2008-12-16 21:30:33 +0000328/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
329/// the default argument for the parameter param failed.
John McCalld226f652010-08-21 09:40:31 +0000330void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000331 if (!param)
332 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000333
John McCalld226f652010-08-21 09:40:31 +0000334 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Mike Stump1eb44332009-09-09 15:08:12 +0000335
Anders Carlsson5e300d12009-06-12 16:51:40 +0000336 Param->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000337
Anders Carlsson5e300d12009-06-12 16:51:40 +0000338 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000339}
340
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000341/// CheckExtraCXXDefaultArguments - Check for any extra default
342/// arguments in the declarator, which is not a function declaration
343/// or definition and therefore is not permitted to have default
344/// arguments. This routine should be invoked for every declarator
345/// that is not a function declaration or definition.
346void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
347 // C++ [dcl.fct.default]p3
348 // A default argument expression shall be specified only in the
349 // parameter-declaration-clause of a function declaration or in a
350 // template-parameter (14.1). It shall not be specified for a
351 // parameter pack. If it is specified in a
352 // parameter-declaration-clause, it shall not occur within a
353 // declarator or abstract-declarator of a parameter-declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000354 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000355 DeclaratorChunk &chunk = D.getTypeObject(i);
356 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000357 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
358 ParmVarDecl *Param =
John McCalld226f652010-08-21 09:40:31 +0000359 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000360 if (Param->hasUnparsedDefaultArg()) {
361 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000362 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
363 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
364 delete Toks;
365 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor61366e92008-12-24 00:01:03 +0000366 } else if (Param->getDefaultArg()) {
367 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
368 << Param->getDefaultArg()->getSourceRange();
369 Param->setDefaultArg(0);
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000370 }
371 }
372 }
373 }
374}
375
Chris Lattner3d1cee32008-04-08 05:04:30 +0000376// MergeCXXFunctionDecl - Merge two declarations of the same C++
377// function, once we already know that they have the same
Douglas Gregorcda9c672009-02-16 17:45:42 +0000378// type. Subroutine of MergeFunctionDecl. Returns true if there was an
379// error, false otherwise.
James Molloy9cda03f2012-03-13 08:55:35 +0000380bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
381 Scope *S) {
Douglas Gregorcda9c672009-02-16 17:45:42 +0000382 bool Invalid = false;
383
Chris Lattner3d1cee32008-04-08 05:04:30 +0000384 // C++ [dcl.fct.default]p4:
Chris Lattner3d1cee32008-04-08 05:04:30 +0000385 // For non-template functions, default arguments can be added in
386 // later declarations of a function in the same
387 // scope. Declarations in different scopes have completely
388 // distinct sets of default arguments. That is, declarations in
389 // inner scopes do not acquire default arguments from
390 // declarations in outer scopes, and vice versa. In a given
391 // function declaration, all parameters subsequent to a
392 // parameter with a default argument shall have default
393 // arguments supplied in this or previous declarations. A
394 // default argument shall not be redefined by a later
395 // declaration (not even to the same value).
Douglas Gregor6cc15182009-09-11 18:44:32 +0000396 //
397 // C++ [dcl.fct.default]p6:
398 // Except for member functions of class templates, the default arguments
399 // in a member function definition that appears outside of the class
400 // definition are added to the set of default arguments provided by the
401 // member function declaration in the class definition.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000402 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
403 ParmVarDecl *OldParam = Old->getParamDecl(p);
404 ParmVarDecl *NewParam = New->getParamDecl(p);
405
James Molloy9cda03f2012-03-13 08:55:35 +0000406 bool OldParamHasDfl = OldParam->hasDefaultArg();
407 bool NewParamHasDfl = NewParam->hasDefaultArg();
408
409 NamedDecl *ND = Old;
410 if (S && !isDeclInScope(ND, New->getDeclContext(), S))
411 // Ignore default parameters of old decl if they are not in
412 // the same scope.
413 OldParamHasDfl = false;
414
415 if (OldParamHasDfl && NewParamHasDfl) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000416
Francois Pichet8d051e02011-04-10 03:03:52 +0000417 unsigned DiagDefaultParamID =
418 diag::err_param_default_argument_redefinition;
419
420 // MSVC accepts that default parameters be redefined for member functions
421 // of template class. The new default parameter's value is ignored.
422 Invalid = true;
David Blaikie4e4d0842012-03-11 07:00:24 +0000423 if (getLangOpts().MicrosoftExt) {
Francois Pichet8d051e02011-04-10 03:03:52 +0000424 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
425 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000426 // Merge the old default argument into the new parameter.
427 NewParam->setHasInheritedDefaultArg();
428 if (OldParam->hasUninstantiatedDefaultArg())
429 NewParam->setUninstantiatedDefaultArg(
430 OldParam->getUninstantiatedDefaultArg());
431 else
432 NewParam->setDefaultArg(OldParam->getInit());
Francois Pichetcf320c62011-04-22 08:25:24 +0000433 DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
Francois Pichet8d051e02011-04-10 03:03:52 +0000434 Invalid = false;
435 }
436 }
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000437
Francois Pichet8cf90492011-04-10 04:58:30 +0000438 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
439 // hint here. Alternatively, we could walk the type-source information
440 // for NewParam to find the last source location in the type... but it
441 // isn't worth the effort right now. This is the kind of test case that
442 // is hard to get right:
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000443 // int f(int);
444 // void g(int (*fp)(int) = f);
445 // void g(int (*fp)(int) = &f);
Francois Pichet8d051e02011-04-10 03:03:52 +0000446 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000447 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000448
449 // Look for the function declaration where the default argument was
450 // actually written, which may be a declaration prior to Old.
Douglas Gregoref96ee02012-01-14 16:38:05 +0000451 for (FunctionDecl *Older = Old->getPreviousDecl();
452 Older; Older = Older->getPreviousDecl()) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000453 if (!Older->getParamDecl(p)->hasDefaultArg())
454 break;
455
456 OldParam = Older->getParamDecl(p);
457 }
458
459 Diag(OldParam->getLocation(), diag::note_previous_definition)
460 << OldParam->getDefaultArgRange();
James Molloy9cda03f2012-03-13 08:55:35 +0000461 } else if (OldParamHasDfl) {
John McCall3d6c1782010-05-04 01:53:42 +0000462 // Merge the old default argument into the new parameter.
463 // It's important to use getInit() here; getDefaultArg()
John McCall4765fa02010-12-06 08:20:24 +0000464 // strips off any top-level ExprWithCleanups.
John McCallbf73b352010-03-12 18:31:32 +0000465 NewParam->setHasInheritedDefaultArg();
Douglas Gregord85cef52009-09-17 19:51:30 +0000466 if (OldParam->hasUninstantiatedDefaultArg())
467 NewParam->setUninstantiatedDefaultArg(
468 OldParam->getUninstantiatedDefaultArg());
469 else
John McCall3d6c1782010-05-04 01:53:42 +0000470 NewParam->setDefaultArg(OldParam->getInit());
James Molloy9cda03f2012-03-13 08:55:35 +0000471 } else if (NewParamHasDfl) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000472 if (New->getDescribedFunctionTemplate()) {
473 // Paragraph 4, quoted above, only applies to non-template functions.
474 Diag(NewParam->getLocation(),
475 diag::err_param_default_argument_template_redecl)
476 << NewParam->getDefaultArgRange();
477 Diag(Old->getLocation(), diag::note_template_prev_declaration)
478 << false;
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000479 } else if (New->getTemplateSpecializationKind()
480 != TSK_ImplicitInstantiation &&
481 New->getTemplateSpecializationKind() != TSK_Undeclared) {
482 // C++ [temp.expr.spec]p21:
483 // Default function arguments shall not be specified in a declaration
484 // or a definition for one of the following explicit specializations:
485 // - the explicit specialization of a function template;
Douglas Gregor8c638ab2009-10-13 23:52:38 +0000486 // - the explicit specialization of a member function template;
487 // - the explicit specialization of a member function of a class
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000488 // template where the class template specialization to which the
489 // member function specialization belongs is implicitly
490 // instantiated.
491 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
492 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
493 << New->getDeclName()
494 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000495 } else if (New->getDeclContext()->isDependentContext()) {
496 // C++ [dcl.fct.default]p6 (DR217):
497 // Default arguments for a member function of a class template shall
498 // be specified on the initial declaration of the member function
499 // within the class template.
500 //
501 // Reading the tea leaves a bit in DR217 and its reference to DR205
502 // leads me to the conclusion that one cannot add default function
503 // arguments for an out-of-line definition of a member function of a
504 // dependent type.
505 int WhichKind = 2;
506 if (CXXRecordDecl *Record
507 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
508 if (Record->getDescribedClassTemplate())
509 WhichKind = 0;
510 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
511 WhichKind = 1;
512 else
513 WhichKind = 2;
514 }
515
516 Diag(NewParam->getLocation(),
517 diag::err_param_default_argument_member_template_redecl)
518 << WhichKind
519 << NewParam->getDefaultArgRange();
Sean Hunt9ae60d52011-05-26 01:26:05 +0000520 } else if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(New)) {
521 CXXSpecialMember NewSM = getSpecialMember(Ctor),
522 OldSM = getSpecialMember(cast<CXXConstructorDecl>(Old));
523 if (NewSM != OldSM) {
524 Diag(NewParam->getLocation(),diag::warn_default_arg_makes_ctor_special)
525 << NewParam->getDefaultArgRange() << NewSM;
526 Diag(Old->getLocation(), diag::note_previous_declaration_special)
527 << OldSM;
528 }
Douglas Gregor6cc15182009-09-11 18:44:32 +0000529 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000530 }
531 }
532
Richard Smithff234882012-02-20 23:28:05 +0000533 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
Richard Smith9f569cc2011-10-01 02:31:28 +0000534 // template has a constexpr specifier then all its declarations shall
Richard Smithff234882012-02-20 23:28:05 +0000535 // contain the constexpr specifier.
Richard Smith9f569cc2011-10-01 02:31:28 +0000536 if (New->isConstexpr() != Old->isConstexpr()) {
537 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
538 << New << New->isConstexpr();
539 Diag(Old->getLocation(), diag::note_previous_declaration);
540 Invalid = true;
541 }
542
Douglas Gregore13ad832010-02-12 07:32:17 +0000543 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000544 Invalid = true;
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000545
Douglas Gregorcda9c672009-02-16 17:45:42 +0000546 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000547}
548
Sebastian Redl60618fa2011-03-12 11:50:43 +0000549/// \brief Merge the exception specifications of two variable declarations.
550///
551/// This is called when there's a redeclaration of a VarDecl. The function
552/// checks if the redeclaration might have an exception specification and
553/// validates compatibility and merges the specs if necessary.
554void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
555 // Shortcut if exceptions are disabled.
David Blaikie4e4d0842012-03-11 07:00:24 +0000556 if (!getLangOpts().CXXExceptions)
Sebastian Redl60618fa2011-03-12 11:50:43 +0000557 return;
558
559 assert(Context.hasSameType(New->getType(), Old->getType()) &&
560 "Should only be called if types are otherwise the same.");
561
562 QualType NewType = New->getType();
563 QualType OldType = Old->getType();
564
565 // We're only interested in pointers and references to functions, as well
566 // as pointers to member functions.
567 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
568 NewType = R->getPointeeType();
569 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
570 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
571 NewType = P->getPointeeType();
572 OldType = OldType->getAs<PointerType>()->getPointeeType();
573 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
574 NewType = M->getPointeeType();
575 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
576 }
577
578 if (!NewType->isFunctionProtoType())
579 return;
580
581 // There's lots of special cases for functions. For function pointers, system
582 // libraries are hopefully not as broken so that we don't need these
583 // workarounds.
584 if (CheckEquivalentExceptionSpec(
585 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
586 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
587 New->setInvalidDecl();
588 }
589}
590
Chris Lattner3d1cee32008-04-08 05:04:30 +0000591/// CheckCXXDefaultArguments - Verify that the default arguments for a
592/// function declaration are well-formed according to C++
593/// [dcl.fct.default].
594void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
595 unsigned NumParams = FD->getNumParams();
596 unsigned p;
597
Douglas Gregorc6889e72012-02-14 22:28:59 +0000598 bool IsLambda = FD->getOverloadedOperator() == OO_Call &&
599 isa<CXXMethodDecl>(FD) &&
600 cast<CXXMethodDecl>(FD)->getParent()->isLambda();
601
Chris Lattner3d1cee32008-04-08 05:04:30 +0000602 // Find first parameter with a default argument
603 for (p = 0; p < NumParams; ++p) {
604 ParmVarDecl *Param = FD->getParamDecl(p);
Douglas Gregorc6889e72012-02-14 22:28:59 +0000605 if (Param->hasDefaultArg()) {
606 // C++11 [expr.prim.lambda]p5:
607 // [...] Default arguments (8.3.6) shall not be specified in the
608 // parameter-declaration-clause of a lambda-declarator.
609 //
610 // FIXME: Core issue 974 strikes this sentence, we only provide an
611 // extension warning.
612 if (IsLambda)
613 Diag(Param->getLocation(), diag::ext_lambda_default_arguments)
614 << Param->getDefaultArgRange();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000615 break;
Douglas Gregorc6889e72012-02-14 22:28:59 +0000616 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000617 }
618
619 // C++ [dcl.fct.default]p4:
620 // In a given function declaration, all parameters
621 // subsequent to a parameter with a default argument shall
622 // have default arguments supplied in this or previous
623 // declarations. A default argument shall not be redefined
624 // by a later declaration (not even to the same value).
625 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000626 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000627 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000628 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000629 if (Param->isInvalidDecl())
630 /* We already complained about this parameter. */;
631 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000632 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000633 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000634 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000635 else
Mike Stump1eb44332009-09-09 15:08:12 +0000636 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000637 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000638
Chris Lattner3d1cee32008-04-08 05:04:30 +0000639 LastMissingDefaultArg = p;
640 }
641 }
642
643 if (LastMissingDefaultArg > 0) {
644 // Some default arguments were missing. Clear out all of the
645 // default arguments up to (and including) the last missing
646 // default argument, so that we leave the function parameters
647 // in a semantically valid state.
648 for (p = 0; p <= LastMissingDefaultArg; ++p) {
649 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000650 if (Param->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000651 Param->setDefaultArg(0);
652 }
653 }
654 }
655}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000656
Richard Smith9f569cc2011-10-01 02:31:28 +0000657// CheckConstexprParameterTypes - Check whether a function's parameter types
658// are all literal types. If so, return true. If not, produce a suitable
Richard Smith86c3ae42012-02-13 03:54:03 +0000659// diagnostic and return false.
660static bool CheckConstexprParameterTypes(Sema &SemaRef,
661 const FunctionDecl *FD) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000662 unsigned ArgIndex = 0;
663 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
664 for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(),
665 e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) {
666 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
667 SourceLocation ParamLoc = PD->getLocation();
668 if (!(*i)->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000669 SemaRef.RequireLiteralType(ParamLoc, *i,
Douglas Gregorf502d8e2012-05-04 16:48:41 +0000670 diag::err_constexpr_non_literal_param,
671 ArgIndex+1, PD->getSourceRange(),
672 isa<CXXConstructorDecl>(FD)))
Richard Smith9f569cc2011-10-01 02:31:28 +0000673 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000674 }
Joao Matos17d35c32012-08-31 22:18:20 +0000675 return true;
676}
677
678/// \brief Get diagnostic %select index for tag kind for
679/// record diagnostic message.
680/// WARNING: Indexes apply to particular diagnostics only!
681///
682/// \returns diagnostic %select index.
683static unsigned getRecordDiagFromTagKind(TagTypeKind Tag)
684{
685 switch (Tag) {
686 case TTK_Struct: return 0;
687 case TTK_Interface: return 1;
688 case TTK_Class: return 2;
689 default: assert("Invalid tag kind for record diagnostic!");
690 }
691 return -1;
692}
693
694// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
695// the requirements of a constexpr function definition or a constexpr
696// constructor definition. If so, return true. If not, produce appropriate
Richard Smith86c3ae42012-02-13 03:54:03 +0000697// diagnostics and return false.
Richard Smith9f569cc2011-10-01 02:31:28 +0000698//
Richard Smith86c3ae42012-02-13 03:54:03 +0000699// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
700bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
Richard Smith35340502012-01-13 04:54:00 +0000701 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
702 if (MD && MD->isInstance()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000703 // C++11 [dcl.constexpr]p4:
704 // The definition of a constexpr constructor shall satisfy the following
705 // constraints:
Richard Smith9f569cc2011-10-01 02:31:28 +0000706 // - the class shall not have any virtual base classes;
Joao Matos17d35c32012-08-31 22:18:20 +0000707 const CXXRecordDecl *RD = MD->getParent();
708 if (RD->getNumVBases()) {
709 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
710 << isa<CXXConstructorDecl>(NewFD)
711 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
712 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
713 E = RD->vbases_end(); I != E; ++I)
714 Diag(I->getLocStart(),
Richard Smith86c3ae42012-02-13 03:54:03 +0000715 diag::note_constexpr_virtual_base_here) << I->getSourceRange();
Richard Smith9f569cc2011-10-01 02:31:28 +0000716 return false;
717 }
Richard Smith35340502012-01-13 04:54:00 +0000718 }
719
720 if (!isa<CXXConstructorDecl>(NewFD)) {
721 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +0000722 // The definition of a constexpr function shall satisfy the following
723 // constraints:
724 // - it shall not be virtual;
725 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
726 if (Method && Method->isVirtual()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000727 Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
Richard Smith9f569cc2011-10-01 02:31:28 +0000728
Richard Smith86c3ae42012-02-13 03:54:03 +0000729 // If it's not obvious why this function is virtual, find an overridden
730 // function which uses the 'virtual' keyword.
731 const CXXMethodDecl *WrittenVirtual = Method;
732 while (!WrittenVirtual->isVirtualAsWritten())
733 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
734 if (WrittenVirtual != Method)
735 Diag(WrittenVirtual->getLocation(),
736 diag::note_overridden_virtual_function);
Richard Smith9f569cc2011-10-01 02:31:28 +0000737 return false;
738 }
739
740 // - its return type shall be a literal type;
741 QualType RT = NewFD->getResultType();
742 if (!RT->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000743 RequireLiteralType(NewFD->getLocation(), RT,
Douglas Gregorf502d8e2012-05-04 16:48:41 +0000744 diag::err_constexpr_non_literal_return))
Richard Smith9f569cc2011-10-01 02:31:28 +0000745 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000746 }
747
Richard Smith35340502012-01-13 04:54:00 +0000748 // - each of its parameter types shall be a literal type;
Richard Smith86c3ae42012-02-13 03:54:03 +0000749 if (!CheckConstexprParameterTypes(*this, NewFD))
Richard Smith35340502012-01-13 04:54:00 +0000750 return false;
751
Richard Smith9f569cc2011-10-01 02:31:28 +0000752 return true;
753}
754
755/// Check the given declaration statement is legal within a constexpr function
756/// body. C++0x [dcl.constexpr]p3,p4.
757///
758/// \return true if the body is OK, false if we have diagnosed a problem.
759static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
760 DeclStmt *DS) {
761 // C++0x [dcl.constexpr]p3 and p4:
762 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
763 // contain only
764 for (DeclStmt::decl_iterator DclIt = DS->decl_begin(),
765 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
766 switch ((*DclIt)->getKind()) {
767 case Decl::StaticAssert:
768 case Decl::Using:
769 case Decl::UsingShadow:
770 case Decl::UsingDirective:
771 case Decl::UnresolvedUsingTypename:
772 // - static_assert-declarations
773 // - using-declarations,
774 // - using-directives,
775 continue;
776
777 case Decl::Typedef:
778 case Decl::TypeAlias: {
779 // - typedef declarations and alias-declarations that do not define
780 // classes or enumerations,
781 TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt);
782 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
783 // Don't allow variably-modified types in constexpr functions.
784 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
785 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
786 << TL.getSourceRange() << TL.getType()
787 << isa<CXXConstructorDecl>(Dcl);
788 return false;
789 }
790 continue;
791 }
792
793 case Decl::Enum:
794 case Decl::CXXRecord:
795 // As an extension, we allow the declaration (but not the definition) of
796 // classes and enumerations in all declarations, not just in typedef and
797 // alias declarations.
798 if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition()) {
799 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_type_definition)
800 << isa<CXXConstructorDecl>(Dcl);
801 return false;
802 }
803 continue;
804
805 case Decl::Var:
806 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_var_declaration)
807 << isa<CXXConstructorDecl>(Dcl);
808 return false;
809
810 default:
811 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
812 << isa<CXXConstructorDecl>(Dcl);
813 return false;
814 }
815 }
816
817 return true;
818}
819
820/// Check that the given field is initialized within a constexpr constructor.
821///
822/// \param Dcl The constexpr constructor being checked.
823/// \param Field The field being checked. This may be a member of an anonymous
824/// struct or union nested within the class being checked.
825/// \param Inits All declarations, including anonymous struct/union members and
826/// indirect members, for which any initialization was provided.
827/// \param Diagnosed Set to true if an error is produced.
828static void CheckConstexprCtorInitializer(Sema &SemaRef,
829 const FunctionDecl *Dcl,
830 FieldDecl *Field,
831 llvm::SmallSet<Decl*, 16> &Inits,
832 bool &Diagnosed) {
Douglas Gregord61db332011-10-10 17:22:13 +0000833 if (Field->isUnnamedBitfield())
834 return;
Richard Smith30ecfad2012-02-09 06:40:58 +0000835
836 if (Field->isAnonymousStructOrUnion() &&
837 Field->getType()->getAsCXXRecordDecl()->isEmpty())
838 return;
839
Richard Smith9f569cc2011-10-01 02:31:28 +0000840 if (!Inits.count(Field)) {
841 if (!Diagnosed) {
842 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
843 Diagnosed = true;
844 }
845 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
846 } else if (Field->isAnonymousStructOrUnion()) {
847 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
848 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
849 I != E; ++I)
850 // If an anonymous union contains an anonymous struct of which any member
851 // is initialized, all members must be initialized.
David Blaikie581deb32012-06-06 20:45:41 +0000852 if (!RD->isUnion() || Inits.count(*I))
853 CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed);
Richard Smith9f569cc2011-10-01 02:31:28 +0000854 }
855}
856
857/// Check the body for the given constexpr function declaration only contains
858/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
859///
860/// \return true if the body is OK, false if we have diagnosed a problem.
Richard Smith86c3ae42012-02-13 03:54:03 +0000861bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000862 if (isa<CXXTryStmt>(Body)) {
Richard Smith5ba73e12012-02-04 00:33:54 +0000863 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +0000864 // The definition of a constexpr function shall satisfy the following
865 // constraints: [...]
866 // - its function-body shall be = delete, = default, or a
867 // compound-statement
868 //
Richard Smith5ba73e12012-02-04 00:33:54 +0000869 // C++11 [dcl.constexpr]p4:
Richard Smith9f569cc2011-10-01 02:31:28 +0000870 // In the definition of a constexpr constructor, [...]
871 // - its function-body shall not be a function-try-block;
872 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
873 << isa<CXXConstructorDecl>(Dcl);
874 return false;
875 }
876
877 // - its function-body shall be [...] a compound-statement that contains only
878 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
879
880 llvm::SmallVector<SourceLocation, 4> ReturnStmts;
881 for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(),
882 BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) {
883 switch ((*BodyIt)->getStmtClass()) {
884 case Stmt::NullStmtClass:
885 // - null statements,
886 continue;
887
888 case Stmt::DeclStmtClass:
889 // - static_assert-declarations
890 // - using-declarations,
891 // - using-directives,
892 // - typedef declarations and alias-declarations that do not define
893 // classes or enumerations,
894 if (!CheckConstexprDeclStmt(*this, Dcl, cast<DeclStmt>(*BodyIt)))
895 return false;
896 continue;
897
898 case Stmt::ReturnStmtClass:
899 // - and exactly one return statement;
900 if (isa<CXXConstructorDecl>(Dcl))
901 break;
902
903 ReturnStmts.push_back((*BodyIt)->getLocStart());
Richard Smith9f569cc2011-10-01 02:31:28 +0000904 continue;
905
906 default:
907 break;
908 }
909
910 Diag((*BodyIt)->getLocStart(), diag::err_constexpr_body_invalid_stmt)
911 << isa<CXXConstructorDecl>(Dcl);
912 return false;
913 }
914
915 if (const CXXConstructorDecl *Constructor
916 = dyn_cast<CXXConstructorDecl>(Dcl)) {
917 const CXXRecordDecl *RD = Constructor->getParent();
Richard Smith30ecfad2012-02-09 06:40:58 +0000918 // DR1359:
919 // - every non-variant non-static data member and base class sub-object
920 // shall be initialized;
921 // - if the class is a non-empty union, or for each non-empty anonymous
922 // union member of a non-union class, exactly one non-static data member
923 // shall be initialized;
Richard Smith9f569cc2011-10-01 02:31:28 +0000924 if (RD->isUnion()) {
Richard Smith30ecfad2012-02-09 06:40:58 +0000925 if (Constructor->getNumCtorInitializers() == 0 && !RD->isEmpty()) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000926 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
927 return false;
928 }
Richard Smith6e433752011-10-10 16:38:04 +0000929 } else if (!Constructor->isDependentContext() &&
930 !Constructor->isDelegatingConstructor()) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000931 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
932
933 // Skip detailed checking if we have enough initializers, and we would
934 // allow at most one initializer per member.
935 bool AnyAnonStructUnionMembers = false;
936 unsigned Fields = 0;
937 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
938 E = RD->field_end(); I != E; ++I, ++Fields) {
David Blaikie262bc182012-04-30 02:36:29 +0000939 if (I->isAnonymousStructOrUnion()) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000940 AnyAnonStructUnionMembers = true;
941 break;
942 }
943 }
944 if (AnyAnonStructUnionMembers ||
945 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
946 // Check initialization of non-static data members. Base classes are
947 // always initialized so do not need to be checked. Dependent bases
948 // might not have initializers in the member initializer list.
949 llvm::SmallSet<Decl*, 16> Inits;
950 for (CXXConstructorDecl::init_const_iterator
951 I = Constructor->init_begin(), E = Constructor->init_end();
952 I != E; ++I) {
953 if (FieldDecl *FD = (*I)->getMember())
954 Inits.insert(FD);
955 else if (IndirectFieldDecl *ID = (*I)->getIndirectMember())
956 Inits.insert(ID->chain_begin(), ID->chain_end());
957 }
958
959 bool Diagnosed = false;
960 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
961 E = RD->field_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +0000962 CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed);
Richard Smith9f569cc2011-10-01 02:31:28 +0000963 if (Diagnosed)
964 return false;
965 }
966 }
Richard Smith9f569cc2011-10-01 02:31:28 +0000967 } else {
968 if (ReturnStmts.empty()) {
969 Diag(Dcl->getLocation(), diag::err_constexpr_body_no_return);
970 return false;
971 }
972 if (ReturnStmts.size() > 1) {
973 Diag(ReturnStmts.back(), diag::err_constexpr_body_multiple_return);
974 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
975 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
976 return false;
977 }
978 }
979
Richard Smith5ba73e12012-02-04 00:33:54 +0000980 // C++11 [dcl.constexpr]p5:
981 // if no function argument values exist such that the function invocation
982 // substitution would produce a constant expression, the program is
983 // ill-formed; no diagnostic required.
984 // C++11 [dcl.constexpr]p3:
985 // - every constructor call and implicit conversion used in initializing the
986 // return value shall be one of those allowed in a constant expression.
987 // C++11 [dcl.constexpr]p4:
988 // - every constructor involved in initializing non-static data members and
989 // base class sub-objects shall be a constexpr constructor.
Richard Smith745f5142012-01-27 01:14:48 +0000990 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith86c3ae42012-02-13 03:54:03 +0000991 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smith745f5142012-01-27 01:14:48 +0000992 Diag(Dcl->getLocation(), diag::err_constexpr_function_never_constant_expr)
993 << isa<CXXConstructorDecl>(Dcl);
994 for (size_t I = 0, N = Diags.size(); I != N; ++I)
995 Diag(Diags[I].first, Diags[I].second);
996 return false;
997 }
998
Richard Smith9f569cc2011-10-01 02:31:28 +0000999 return true;
1000}
1001
Douglas Gregorb48fe382008-10-31 09:07:45 +00001002/// isCurrentClassName - Determine whether the identifier II is the
1003/// name of the class type currently being defined. In the case of
1004/// nested classes, this will only return true if II is the name of
1005/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00001006bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1007 const CXXScopeSpec *SS) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001008 assert(getLangOpts().CPlusPlus && "No class names in C!");
Douglas Gregorb862b8f2010-01-11 23:29:10 +00001009
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001010 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +00001011 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +00001012 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001013 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1014 } else
1015 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1016
Douglas Gregor6f7a17b2010-02-05 06:12:42 +00001017 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregorb48fe382008-10-31 09:07:45 +00001018 return &II == CurDecl->getIdentifier();
1019 else
1020 return false;
1021}
1022
Mike Stump1eb44332009-09-09 15:08:12 +00001023/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001024///
1025/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1026/// and returns NULL otherwise.
1027CXXBaseSpecifier *
1028Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1029 SourceRange SpecifierRange,
1030 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001031 TypeSourceInfo *TInfo,
1032 SourceLocation EllipsisLoc) {
Nick Lewycky56062202010-07-26 16:56:01 +00001033 QualType BaseType = TInfo->getType();
1034
Douglas Gregor2943aed2009-03-03 04:44:36 +00001035 // C++ [class.union]p1:
1036 // A union shall not have base classes.
1037 if (Class->isUnion()) {
1038 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1039 << SpecifierRange;
1040 return 0;
1041 }
1042
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001043 if (EllipsisLoc.isValid() &&
1044 !TInfo->getType()->containsUnexpandedParameterPack()) {
1045 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1046 << TInfo->getTypeLoc().getSourceRange();
1047 EllipsisLoc = SourceLocation();
1048 }
1049
Douglas Gregor2943aed2009-03-03 04:44:36 +00001050 if (BaseType->isDependentType())
Mike Stump1eb44332009-09-09 15:08:12 +00001051 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001052 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001053 Access, TInfo, EllipsisLoc);
Nick Lewycky56062202010-07-26 16:56:01 +00001054
1055 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001056
1057 // Base specifiers must be record types.
1058 if (!BaseType->isRecordType()) {
1059 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1060 return 0;
1061 }
1062
1063 // C++ [class.union]p1:
1064 // A union shall not be used as a base class.
1065 if (BaseType->isUnionType()) {
1066 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1067 return 0;
1068 }
1069
1070 // C++ [class.derived]p2:
1071 // The class-name in a base-specifier shall not be an incompletely
1072 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +00001073 if (RequireCompleteType(BaseLoc, BaseType,
Douglas Gregord10099e2012-05-04 16:32:21 +00001074 diag::err_incomplete_base_class, SpecifierRange)) {
John McCall572fc622010-08-17 07:23:57 +00001075 Class->setInvalidDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001076 return 0;
John McCall572fc622010-08-17 07:23:57 +00001077 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001078
Eli Friedman1d954f62009-08-15 21:55:26 +00001079 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +00001080 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001081 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor952b0172010-02-11 01:04:33 +00001082 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001083 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedman1d954f62009-08-15 21:55:26 +00001084 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
1085 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +00001086
Anders Carlsson1d209272011-03-25 14:55:14 +00001087 // C++ [class]p3:
1088 // If a class is marked final and it appears as a base-type-specifier in
1089 // base-clause, the program is ill-formed.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001090 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
Anders Carlssondfc2f102011-01-22 17:51:53 +00001091 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1092 << CXXBaseDecl->getDeclName();
1093 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1094 << CXXBaseDecl->getDeclName();
1095 return 0;
1096 }
1097
John McCall572fc622010-08-17 07:23:57 +00001098 if (BaseDecl->isInvalidDecl())
1099 Class->setInvalidDecl();
Anders Carlsson51f94042009-12-03 17:49:57 +00001100
1101 // Create the base specifier.
Anders Carlsson51f94042009-12-03 17:49:57 +00001102 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001103 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001104 Access, TInfo, EllipsisLoc);
Anders Carlsson51f94042009-12-03 17:49:57 +00001105}
1106
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001107/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1108/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +00001109/// example:
1110/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001111/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallf312b1e2010-08-26 23:41:50 +00001112BaseResult
John McCalld226f652010-08-21 09:40:31 +00001113Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001114 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001115 ParsedType basetype, SourceLocation BaseLoc,
1116 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001117 if (!classdecl)
1118 return true;
1119
Douglas Gregor40808ce2009-03-09 23:48:35 +00001120 AdjustDeclIfTemplate(classdecl);
John McCalld226f652010-08-21 09:40:31 +00001121 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregor5fe8c042010-02-27 00:25:28 +00001122 if (!Class)
1123 return true;
1124
Nick Lewycky56062202010-07-26 16:56:01 +00001125 TypeSourceInfo *TInfo = 0;
1126 GetTypeFromParser(basetype, &TInfo);
Douglas Gregord0937222010-12-13 22:49:22 +00001127
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001128 if (EllipsisLoc.isInvalid() &&
1129 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregord0937222010-12-13 22:49:22 +00001130 UPPC_BaseType))
1131 return true;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001132
Douglas Gregor2943aed2009-03-03 04:44:36 +00001133 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001134 Virtual, Access, TInfo,
1135 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +00001136 return BaseSpec;
Douglas Gregor8a50fe02012-07-02 21:00:41 +00001137 else
1138 Class->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001139
Douglas Gregor2943aed2009-03-03 04:44:36 +00001140 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001141}
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001142
Douglas Gregor2943aed2009-03-03 04:44:36 +00001143/// \brief Performs the actual work of attaching the given base class
1144/// specifiers to a C++ class.
1145bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1146 unsigned NumBases) {
1147 if (NumBases == 0)
1148 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001149
1150 // Used to keep track of which base types we have already seen, so
1151 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +00001152 // that the key is always the unqualified canonical type of the base
1153 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001154 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1155
1156 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +00001157 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +00001158 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +00001159 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001160 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +00001161 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +00001162 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Benjamin Kramer52c16682012-03-05 17:20:04 +00001163
1164 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1165 if (KnownBase) {
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001166 // C++ [class.mi]p3:
1167 // A class shall not be specified as a direct base class of a
1168 // derived class more than once.
Daniel Dunbar96a00142012-03-09 18:35:03 +00001169 Diag(Bases[idx]->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001170 diag::err_duplicate_base_class)
Benjamin Kramer52c16682012-03-05 17:20:04 +00001171 << KnownBase->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +00001172 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +00001173
1174 // Delete the duplicate base class specifier; we're going to
1175 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001176 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001177
1178 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001179 } else {
1180 // Okay, add this new base class.
Benjamin Kramer52c16682012-03-05 17:20:04 +00001181 KnownBase = Bases[idx];
Douglas Gregor2943aed2009-03-03 04:44:36 +00001182 Bases[NumGoodBases++] = Bases[idx];
Fariborz Jahanian91589022011-10-24 17:30:45 +00001183 if (const RecordType *Record = NewBaseType->getAs<RecordType>())
Fariborz Jahanian13c7fcc2011-10-21 22:27:12 +00001184 if (const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()))
1185 if (RD->hasAttr<WeakAttr>())
1186 Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context));
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001187 }
1188 }
1189
1190 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +00001191 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +00001192
1193 // Delete the remaining (good) base class specifiers, since their
1194 // data has been copied into the CXXRecordDecl.
1195 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001196 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001197
1198 return Invalid;
1199}
1200
1201/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1202/// class, after checking whether there are any duplicate base
1203/// classes.
Richard Trieu90ab75b2011-09-09 03:18:59 +00001204void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001205 unsigned NumBases) {
1206 if (!ClassDecl || !Bases || !NumBases)
1207 return;
1208
1209 AdjustDeclIfTemplate(ClassDecl);
John McCalld226f652010-08-21 09:40:31 +00001210 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor2943aed2009-03-03 04:44:36 +00001211 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001212}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001213
John McCall3cb0ebd2010-03-10 03:28:59 +00001214static CXXRecordDecl *GetClassForType(QualType T) {
1215 if (const RecordType *RT = T->getAs<RecordType>())
1216 return cast<CXXRecordDecl>(RT->getDecl());
1217 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
1218 return ICT->getDecl();
1219 else
1220 return 0;
1221}
1222
Douglas Gregora8f32e02009-10-06 17:59:45 +00001223/// \brief Determine whether the type \p Derived is a C++ class that is
1224/// derived from the type \p Base.
1225bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001226 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001227 return false;
John McCall3cb0ebd2010-03-10 03:28:59 +00001228
1229 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1230 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001231 return false;
1232
John McCall3cb0ebd2010-03-10 03:28:59 +00001233 CXXRecordDecl *BaseRD = GetClassForType(Base);
1234 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001235 return false;
1236
John McCall86ff3082010-02-04 22:26:26 +00001237 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1238 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001239}
1240
1241/// \brief Determine whether the type \p Derived is a C++ class that is
1242/// derived from the type \p Base.
1243bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001244 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001245 return false;
1246
John McCall3cb0ebd2010-03-10 03:28:59 +00001247 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1248 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001249 return false;
1250
John McCall3cb0ebd2010-03-10 03:28:59 +00001251 CXXRecordDecl *BaseRD = GetClassForType(Base);
1252 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001253 return false;
1254
Douglas Gregora8f32e02009-10-06 17:59:45 +00001255 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1256}
1257
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001258void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallf871d0c2010-08-07 06:22:56 +00001259 CXXCastPath &BasePathArray) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001260 assert(BasePathArray.empty() && "Base path array must be empty!");
1261 assert(Paths.isRecordingPaths() && "Must record paths!");
1262
1263 const CXXBasePath &Path = Paths.front();
1264
1265 // We first go backward and check if we have a virtual base.
1266 // FIXME: It would be better if CXXBasePath had the base specifier for
1267 // the nearest virtual base.
1268 unsigned Start = 0;
1269 for (unsigned I = Path.size(); I != 0; --I) {
1270 if (Path[I - 1].Base->isVirtual()) {
1271 Start = I - 1;
1272 break;
1273 }
1274 }
1275
1276 // Now add all bases.
1277 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallf871d0c2010-08-07 06:22:56 +00001278 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001279}
1280
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001281/// \brief Determine whether the given base path includes a virtual
1282/// base class.
John McCallf871d0c2010-08-07 06:22:56 +00001283bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1284 for (CXXCastPath::const_iterator B = BasePath.begin(),
1285 BEnd = BasePath.end();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001286 B != BEnd; ++B)
1287 if ((*B)->isVirtual())
1288 return true;
1289
1290 return false;
1291}
1292
Douglas Gregora8f32e02009-10-06 17:59:45 +00001293/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1294/// conversion (where Derived and Base are class types) is
1295/// well-formed, meaning that the conversion is unambiguous (and
1296/// that all of the base classes are accessible). Returns true
1297/// and emits a diagnostic if the code is ill-formed, returns false
1298/// otherwise. Loc is the location where this routine should point to
1299/// if there is an error, and Range is the source range to highlight
1300/// if there is an error.
1301bool
1302Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall58e6f342010-03-16 05:22:47 +00001303 unsigned InaccessibleBaseID,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001304 unsigned AmbigiousBaseConvID,
1305 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001306 DeclarationName Name,
John McCallf871d0c2010-08-07 06:22:56 +00001307 CXXCastPath *BasePath) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001308 // First, determine whether the path from Derived to Base is
1309 // ambiguous. This is slightly more expensive than checking whether
1310 // the Derived to Base conversion exists, because here we need to
1311 // explore multiple paths to determine if there is an ambiguity.
1312 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1313 /*DetectVirtual=*/false);
1314 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1315 assert(DerivationOkay &&
1316 "Can only be used with a derived-to-base conversion");
1317 (void)DerivationOkay;
1318
1319 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001320 if (InaccessibleBaseID) {
1321 // Check that the base class can be accessed.
1322 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1323 InaccessibleBaseID)) {
1324 case AR_inaccessible:
1325 return true;
1326 case AR_accessible:
1327 case AR_dependent:
1328 case AR_delayed:
1329 break;
Anders Carlssone25a96c2010-04-24 17:11:09 +00001330 }
John McCall6b2accb2010-02-10 09:31:12 +00001331 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001332
1333 // Build a base path if necessary.
1334 if (BasePath)
1335 BuildBasePathArray(Paths, *BasePath);
1336 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001337 }
1338
1339 // We know that the derived-to-base conversion is ambiguous, and
1340 // we're going to produce a diagnostic. Perform the derived-to-base
1341 // search just one more time to compute all of the possible paths so
1342 // that we can print them out. This is more expensive than any of
1343 // the previous derived-to-base checks we've done, but at this point
1344 // performance isn't as much of an issue.
1345 Paths.clear();
1346 Paths.setRecordingPaths(true);
1347 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1348 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1349 (void)StillOkay;
1350
1351 // Build up a textual representation of the ambiguous paths, e.g.,
1352 // D -> B -> A, that will be used to illustrate the ambiguous
1353 // conversions in the diagnostic. We only print one of the paths
1354 // to each base class subobject.
1355 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1356
1357 Diag(Loc, AmbigiousBaseConvID)
1358 << Derived << Base << PathDisplayStr << Range << Name;
1359 return true;
1360}
1361
1362bool
1363Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001364 SourceLocation Loc, SourceRange Range,
John McCallf871d0c2010-08-07 06:22:56 +00001365 CXXCastPath *BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001366 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001367 return CheckDerivedToBaseConversion(Derived, Base,
John McCall58e6f342010-03-16 05:22:47 +00001368 IgnoreAccess ? 0
1369 : diag::err_upcast_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001370 diag::err_ambiguous_derived_to_base_conv,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001371 Loc, Range, DeclarationName(),
1372 BasePath);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001373}
1374
1375
1376/// @brief Builds a string representing ambiguous paths from a
1377/// specific derived class to different subobjects of the same base
1378/// class.
1379///
1380/// This function builds a string that can be used in error messages
1381/// to show the different paths that one can take through the
1382/// inheritance hierarchy to go from the derived class to different
1383/// subobjects of a base class. The result looks something like this:
1384/// @code
1385/// struct D -> struct B -> struct A
1386/// struct D -> struct C -> struct A
1387/// @endcode
1388std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1389 std::string PathDisplayStr;
1390 std::set<unsigned> DisplayedPaths;
1391 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1392 Path != Paths.end(); ++Path) {
1393 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1394 // We haven't displayed a path to this particular base
1395 // class subobject yet.
1396 PathDisplayStr += "\n ";
1397 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1398 for (CXXBasePath::const_iterator Element = Path->begin();
1399 Element != Path->end(); ++Element)
1400 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1401 }
1402 }
1403
1404 return PathDisplayStr;
1405}
1406
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001407//===----------------------------------------------------------------------===//
1408// C++ class member Handling
1409//===----------------------------------------------------------------------===//
1410
Abramo Bagnara6206d532010-06-05 05:09:32 +00001411/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001412bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1413 SourceLocation ASLoc,
1414 SourceLocation ColonLoc,
1415 AttributeList *Attrs) {
Abramo Bagnara6206d532010-06-05 05:09:32 +00001416 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCalld226f652010-08-21 09:40:31 +00001417 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnara6206d532010-06-05 05:09:32 +00001418 ASLoc, ColonLoc);
1419 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001420 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnara6206d532010-06-05 05:09:32 +00001421}
1422
Richard Smitha4b39652012-08-06 03:25:17 +00001423/// CheckOverrideControl - Check C++11 override control semantics.
1424void Sema::CheckOverrideControl(Decl *D) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001425 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001426
Richard Smitha4b39652012-08-06 03:25:17 +00001427 // Do we know which functions this declaration might be overriding?
1428 bool OverridesAreKnown = !MD ||
1429 (!MD->getParent()->hasAnyDependentBases() &&
1430 !MD->getType()->isDependentType());
Anders Carlsson3ffe1832011-01-20 06:33:26 +00001431
Richard Smitha4b39652012-08-06 03:25:17 +00001432 if (!MD || !MD->isVirtual()) {
1433 if (OverridesAreKnown) {
1434 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1435 Diag(OA->getLocation(),
1436 diag::override_keyword_only_allowed_on_virtual_member_functions)
1437 << "override" << FixItHint::CreateRemoval(OA->getLocation());
1438 D->dropAttr<OverrideAttr>();
1439 }
1440 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1441 Diag(FA->getLocation(),
1442 diag::override_keyword_only_allowed_on_virtual_member_functions)
1443 << "final" << FixItHint::CreateRemoval(FA->getLocation());
1444 D->dropAttr<FinalAttr>();
1445 }
1446 }
Anders Carlsson9e682d92011-01-20 05:57:14 +00001447 return;
1448 }
Richard Smitha4b39652012-08-06 03:25:17 +00001449
1450 if (!OverridesAreKnown)
1451 return;
1452
1453 // C++11 [class.virtual]p5:
1454 // If a virtual function is marked with the virt-specifier override and
1455 // does not override a member function of a base class, the program is
1456 // ill-formed.
1457 bool HasOverriddenMethods =
1458 MD->begin_overridden_methods() != MD->end_overridden_methods();
1459 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1460 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1461 << MD->getDeclName();
Anders Carlsson9e682d92011-01-20 05:57:14 +00001462}
1463
Richard Smitha4b39652012-08-06 03:25:17 +00001464/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001465/// function overrides a virtual member function marked 'final', according to
Richard Smitha4b39652012-08-06 03:25:17 +00001466/// C++11 [class.virtual]p4.
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001467bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1468 const CXXMethodDecl *Old) {
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001469 if (!Old->hasAttr<FinalAttr>())
Anders Carlssonf89e0422011-01-23 21:07:30 +00001470 return false;
1471
1472 Diag(New->getLocation(), diag::err_final_function_overridden)
1473 << New->getDeclName();
1474 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1475 return true;
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001476}
1477
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001478static bool InitializationHasSideEffects(const FieldDecl &FD) {
Richard Smith0b8220a2012-08-07 21:30:42 +00001479 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1480 // FIXME: Destruction of ObjC lifetime types has side-effects.
1481 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1482 return !RD->isCompleteDefinition() ||
1483 !RD->hasTrivialDefaultConstructor() ||
1484 !RD->hasTrivialDestructor();
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001485 return false;
1486}
1487
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001488/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1489/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith7a614d82011-06-11 17:19:42 +00001490/// bitfield width if there is one, 'InitExpr' specifies the initializer if
Richard Smithca523302012-06-10 03:12:00 +00001491/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1492/// present (but parsing it has been deferred).
John McCalld226f652010-08-21 09:40:31 +00001493Decl *
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001494Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +00001495 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001496 Expr *BW, const VirtSpecifiers &VS,
Richard Smithca523302012-06-10 03:12:00 +00001497 InClassInitStyle InitStyle) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001498 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00001499 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1500 DeclarationName Name = NameInfo.getName();
1501 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001502
1503 // For anonymous bitfields, the location should point to the type.
1504 if (Loc.isInvalid())
Daniel Dunbar96a00142012-03-09 18:35:03 +00001505 Loc = D.getLocStart();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001506
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001507 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001508
John McCall4bde1e12010-06-04 08:34:12 +00001509 assert(isa<CXXRecordDecl>(CurContext));
John McCall67d1a672009-08-06 02:15:43 +00001510 assert(!DS.isFriendSpecified());
1511
Richard Smith1ab0d902011-06-25 02:28:38 +00001512 bool isFunc = D.isDeclarationOfFunction();
John McCall4bde1e12010-06-04 08:34:12 +00001513
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001514 // C++ 9.2p6: A member shall not be declared to have automatic storage
1515 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001516 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1517 // data members and cannot be applied to names declared const or static,
1518 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001519 switch (DS.getStorageClassSpec()) {
1520 case DeclSpec::SCS_unspecified:
1521 case DeclSpec::SCS_typedef:
1522 case DeclSpec::SCS_static:
1523 // FALL THROUGH.
1524 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +00001525 case DeclSpec::SCS_mutable:
1526 if (isFunc) {
1527 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001528 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +00001529 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001530 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +00001531
Sebastian Redla11f42f2008-11-17 23:24:37 +00001532 // FIXME: It would be nicer if the keyword was ignored only for this
1533 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001534 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redl669d5d72008-11-14 23:42:31 +00001535 }
1536 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001537 default:
1538 if (DS.getStorageClassSpecLoc().isValid())
1539 Diag(DS.getStorageClassSpecLoc(),
1540 diag::err_storageclass_invalid_for_member);
1541 else
1542 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
1543 D.getMutableDeclSpec().ClearStorageClassSpecs();
1544 }
1545
Sebastian Redl669d5d72008-11-14 23:42:31 +00001546 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1547 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +00001548 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001549
1550 Decl *Member;
Chris Lattner24793662009-03-05 22:45:59 +00001551 if (isInstField) {
Douglas Gregor922fff22010-10-13 22:19:53 +00001552 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorb5a01872011-10-09 18:55:59 +00001553
1554 // Data members must have identifiers for names.
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001555 if (!Name.isIdentifier()) {
Douglas Gregorb5a01872011-10-09 18:55:59 +00001556 Diag(Loc, diag::err_bad_variable_name)
1557 << Name;
1558 return 0;
1559 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001560
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001561 IdentifierInfo *II = Name.getAsIdentifierInfo();
1562
Douglas Gregorf2503652011-09-21 14:40:46 +00001563 // Member field could not be with "template" keyword.
1564 // So TemplateParameterLists should be empty in this case.
1565 if (TemplateParameterLists.size()) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001566 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
Douglas Gregorf2503652011-09-21 14:40:46 +00001567 if (TemplateParams->size()) {
1568 // There is no such thing as a member field template.
1569 Diag(D.getIdentifierLoc(), diag::err_template_member)
1570 << II
1571 << SourceRange(TemplateParams->getTemplateLoc(),
1572 TemplateParams->getRAngleLoc());
1573 } else {
1574 // There is an extraneous 'template<>' for this member.
1575 Diag(TemplateParams->getTemplateLoc(),
1576 diag::err_template_member_noparams)
1577 << II
1578 << SourceRange(TemplateParams->getTemplateLoc(),
1579 TemplateParams->getRAngleLoc());
1580 }
1581 return 0;
1582 }
1583
Douglas Gregor922fff22010-10-13 22:19:53 +00001584 if (SS.isSet() && !SS.isInvalid()) {
1585 // The user provided a superfluous scope specifier inside a class
1586 // definition:
1587 //
1588 // class X {
1589 // int X::member;
1590 // };
Douglas Gregor69605872012-03-28 16:01:27 +00001591 if (DeclContext *DC = computeDeclContext(SS, false))
1592 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
Douglas Gregor922fff22010-10-13 22:19:53 +00001593 else
1594 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1595 << Name << SS.getRange();
Douglas Gregor5d8419c2011-11-01 22:13:30 +00001596
Douglas Gregor922fff22010-10-13 22:19:53 +00001597 SS.clear();
1598 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001599
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001600 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
Richard Smithca523302012-06-10 03:12:00 +00001601 InitStyle, AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001602 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +00001603 } else {
Richard Smithca523302012-06-10 03:12:00 +00001604 assert(InitStyle == ICIS_NoInit);
Richard Smith7a614d82011-06-11 17:19:42 +00001605
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001606 Member = HandleDeclarator(S, D, TemplateParameterLists);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001607 if (!Member) {
John McCalld226f652010-08-21 09:40:31 +00001608 return 0;
Chris Lattner6f8ce142009-03-05 23:03:49 +00001609 }
Chris Lattner8b963ef2009-03-05 23:01:03 +00001610
1611 // Non-instance-fields can't have a bitfield.
1612 if (BitWidth) {
1613 if (Member->isInvalidDecl()) {
1614 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00001615 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00001616 // C++ 9.6p3: A bit-field shall not be a static member.
1617 // "static member 'A' cannot be a bit-field"
1618 Diag(Loc, diag::err_static_not_bitfield)
1619 << Name << BitWidth->getSourceRange();
1620 } else if (isa<TypedefDecl>(Member)) {
1621 // "typedef member 'x' cannot be a bit-field"
1622 Diag(Loc, diag::err_typedef_not_bitfield)
1623 << Name << BitWidth->getSourceRange();
1624 } else {
1625 // A function typedef ("typedef int f(); f a;").
1626 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1627 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +00001628 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +00001629 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +00001630 }
Mike Stump1eb44332009-09-09 15:08:12 +00001631
Chris Lattner8b963ef2009-03-05 23:01:03 +00001632 BitWidth = 0;
1633 Member->setInvalidDecl();
1634 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001635
1636 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +00001637
Douglas Gregor37b372b2009-08-20 22:52:58 +00001638 // If we have declared a member function template, set the access of the
1639 // templated declaration as well.
1640 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1641 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +00001642 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001643
Richard Smitha4b39652012-08-06 03:25:17 +00001644 if (VS.isOverrideSpecified())
1645 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
1646 if (VS.isFinalSpecified())
1647 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlsson9e682d92011-01-20 05:57:14 +00001648
Douglas Gregorf5251602011-03-08 17:10:18 +00001649 if (VS.getLastLocation().isValid()) {
1650 // Update the end location of a method that has a virt-specifiers.
1651 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1652 MD->setRangeEnd(VS.getLastLocation());
1653 }
Richard Smitha4b39652012-08-06 03:25:17 +00001654
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001655 CheckOverrideControl(Member);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001656
Douglas Gregor10bd3682008-11-17 22:58:34 +00001657 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001658
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001659 if (isInstField) {
1660 FieldDecl *FD = cast<FieldDecl>(Member);
1661 FieldCollector->Add(FD);
1662
1663 if (Diags.getDiagnosticLevel(diag::warn_unused_private_field,
1664 FD->getLocation())
1665 != DiagnosticsEngine::Ignored) {
1666 // Remember all explicit private FieldDecls that have a name, no side
1667 // effects and are not part of a dependent type declaration.
1668 if (!FD->isImplicit() && FD->getDeclName() &&
1669 FD->getAccess() == AS_private &&
Daniel Jasper568eae42012-06-13 18:31:09 +00001670 !FD->hasAttr<UnusedAttr>() &&
Richard Smith0b8220a2012-08-07 21:30:42 +00001671 !FD->getParent()->isDependentContext() &&
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001672 !InitializationHasSideEffects(*FD))
1673 UnusedPrivateFields.insert(FD);
1674 }
1675 }
1676
John McCalld226f652010-08-21 09:40:31 +00001677 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001678}
1679
Richard Smith7a614d82011-06-11 17:19:42 +00001680/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
Richard Smith0ff6f8f2011-07-20 00:12:52 +00001681/// in-class initializer for a non-static C++ class member, and after
1682/// instantiating an in-class initializer in a class template. Such actions
1683/// are deferred until the class is complete.
Richard Smith7a614d82011-06-11 17:19:42 +00001684void
Richard Smithca523302012-06-10 03:12:00 +00001685Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation InitLoc,
Richard Smith7a614d82011-06-11 17:19:42 +00001686 Expr *InitExpr) {
1687 FieldDecl *FD = cast<FieldDecl>(D);
Richard Smithca523302012-06-10 03:12:00 +00001688 assert(FD->getInClassInitStyle() != ICIS_NoInit &&
1689 "must set init style when field is created");
Richard Smith7a614d82011-06-11 17:19:42 +00001690
1691 if (!InitExpr) {
1692 FD->setInvalidDecl();
1693 FD->removeInClassInitializer();
1694 return;
1695 }
1696
Peter Collingbournefef21892011-10-23 18:59:44 +00001697 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
1698 FD->setInvalidDecl();
1699 FD->removeInClassInitializer();
1700 return;
1701 }
1702
Richard Smith7a614d82011-06-11 17:19:42 +00001703 ExprResult Init = InitExpr;
1704 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
Sebastian Redl772291a2012-02-19 16:31:05 +00001705 if (isa<InitListExpr>(InitExpr) && isStdInitializerList(FD->getType(), 0)) {
Sebastian Redl33deb352012-02-22 10:50:08 +00001706 Diag(FD->getLocation(), diag::warn_dangling_std_initializer_list)
Sebastian Redl772291a2012-02-19 16:31:05 +00001707 << /*at end of ctor*/1 << InitExpr->getSourceRange();
1708 }
Sebastian Redl33deb352012-02-22 10:50:08 +00001709 Expr **Inits = &InitExpr;
1710 unsigned NumInits = 1;
1711 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
Richard Smithca523302012-06-10 03:12:00 +00001712 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
Sebastian Redl33deb352012-02-22 10:50:08 +00001713 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
Richard Smithca523302012-06-10 03:12:00 +00001714 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
Sebastian Redl33deb352012-02-22 10:50:08 +00001715 InitializationSequence Seq(*this, Entity, Kind, Inits, NumInits);
1716 Init = Seq.Perform(*this, Entity, Kind, MultiExprArg(Inits, NumInits));
Richard Smith7a614d82011-06-11 17:19:42 +00001717 if (Init.isInvalid()) {
1718 FD->setInvalidDecl();
1719 return;
1720 }
1721
Richard Smithca523302012-06-10 03:12:00 +00001722 CheckImplicitConversions(Init.get(), InitLoc);
Richard Smith7a614d82011-06-11 17:19:42 +00001723 }
1724
1725 // C++0x [class.base.init]p7:
1726 // The initialization of each base and member constitutes a
1727 // full-expression.
1728 Init = MaybeCreateExprWithCleanups(Init);
1729 if (Init.isInvalid()) {
1730 FD->setInvalidDecl();
1731 return;
1732 }
1733
1734 InitExpr = Init.release();
1735
1736 FD->setInClassInitializer(InitExpr);
1737}
1738
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001739/// \brief Find the direct and/or virtual base specifiers that
1740/// correspond to the given base type, for use in base initialization
1741/// within a constructor.
1742static bool FindBaseInitializer(Sema &SemaRef,
1743 CXXRecordDecl *ClassDecl,
1744 QualType BaseType,
1745 const CXXBaseSpecifier *&DirectBaseSpec,
1746 const CXXBaseSpecifier *&VirtualBaseSpec) {
1747 // First, check for a direct base class.
1748 DirectBaseSpec = 0;
1749 for (CXXRecordDecl::base_class_const_iterator Base
1750 = ClassDecl->bases_begin();
1751 Base != ClassDecl->bases_end(); ++Base) {
1752 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1753 // We found a direct base of this type. That's what we're
1754 // initializing.
1755 DirectBaseSpec = &*Base;
1756 break;
1757 }
1758 }
1759
1760 // Check for a virtual base class.
1761 // FIXME: We might be able to short-circuit this if we know in advance that
1762 // there are no virtual bases.
1763 VirtualBaseSpec = 0;
1764 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1765 // We haven't found a base yet; search the class hierarchy for a
1766 // virtual base class.
1767 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1768 /*DetectVirtual=*/false);
1769 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1770 BaseType, Paths)) {
1771 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1772 Path != Paths.end(); ++Path) {
1773 if (Path->back().Base->isVirtual()) {
1774 VirtualBaseSpec = Path->back().Base;
1775 break;
1776 }
1777 }
1778 }
1779 }
1780
1781 return DirectBaseSpec || VirtualBaseSpec;
1782}
1783
Sebastian Redl6df65482011-09-24 17:48:25 +00001784/// \brief Handle a C++ member initializer using braced-init-list syntax.
1785MemInitResult
1786Sema::ActOnMemInitializer(Decl *ConstructorD,
1787 Scope *S,
1788 CXXScopeSpec &SS,
1789 IdentifierInfo *MemberOrBase,
1790 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00001791 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00001792 SourceLocation IdLoc,
1793 Expr *InitList,
1794 SourceLocation EllipsisLoc) {
1795 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001796 DS, IdLoc, InitList,
David Blaikief2116622012-01-24 06:03:59 +00001797 EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00001798}
1799
1800/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallf312b1e2010-08-26 23:41:50 +00001801MemInitResult
John McCalld226f652010-08-21 09:40:31 +00001802Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001803 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001804 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001805 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00001806 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00001807 const DeclSpec &DS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001808 SourceLocation IdLoc,
1809 SourceLocation LParenLoc,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001810 Expr **Args, unsigned NumArgs,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001811 SourceLocation RParenLoc,
1812 SourceLocation EllipsisLoc) {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00001813 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
1814 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001815 RParenLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00001816 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001817 DS, IdLoc, List, EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00001818}
1819
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001820namespace {
1821
Kaelyn Uhraindc98cd02012-01-11 21:17:51 +00001822// Callback to only accept typo corrections that can be a valid C++ member
1823// intializer: either a non-static field member or a base class.
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001824class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
1825 public:
1826 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
1827 : ClassDecl(ClassDecl) {}
1828
1829 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
1830 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
1831 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
1832 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
1833 else
1834 return isa<TypeDecl>(ND);
1835 }
1836 return false;
1837 }
1838
1839 private:
1840 CXXRecordDecl *ClassDecl;
1841};
1842
1843}
1844
Sebastian Redl6df65482011-09-24 17:48:25 +00001845/// \brief Handle a C++ member initializer.
1846MemInitResult
1847Sema::BuildMemInitializer(Decl *ConstructorD,
1848 Scope *S,
1849 CXXScopeSpec &SS,
1850 IdentifierInfo *MemberOrBase,
1851 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00001852 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00001853 SourceLocation IdLoc,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001854 Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00001855 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001856 if (!ConstructorD)
1857 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001858
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001859 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00001860
1861 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00001862 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001863 if (!Constructor) {
1864 // The user wrote a constructor initializer on a function that is
1865 // not a C++ constructor. Ignore the error for now, because we may
1866 // have more member initializers coming; we'll diagnose it just
1867 // once in ActOnMemInitializers.
1868 return true;
1869 }
1870
1871 CXXRecordDecl *ClassDecl = Constructor->getParent();
1872
1873 // C++ [class.base.init]p2:
1874 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky7663f392010-11-20 01:29:55 +00001875 // constructor's class and, if not found in that scope, are looked
1876 // up in the scope containing the constructor's definition.
1877 // [Note: if the constructor's class contains a member with the
1878 // same name as a direct or virtual base class of the class, a
1879 // mem-initializer-id naming the member or base class and composed
1880 // of a single identifier refers to the class member. A
Douglas Gregor7ad83902008-11-05 04:29:56 +00001881 // mem-initializer-id for the hidden base class may be specified
1882 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00001883 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001884 // Look for a member, first.
Mike Stump1eb44332009-09-09 15:08:12 +00001885 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001886 = ClassDecl->lookup(MemberOrBase);
Francois Pichet87c2e122010-11-21 06:08:52 +00001887 if (Result.first != Result.second) {
Peter Collingbournedc69be22011-10-23 18:59:37 +00001888 ValueDecl *Member;
1889 if ((Member = dyn_cast<FieldDecl>(*Result.first)) ||
1890 (Member = dyn_cast<IndirectFieldDecl>(*Result.first))) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001891 if (EllipsisLoc.isValid())
1892 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001893 << MemberOrBase
1894 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00001895
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001896 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001897 }
Francois Pichet00eb3f92010-12-04 09:14:42 +00001898 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001899 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001900 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00001901 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00001902 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00001903
1904 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00001905 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikief2116622012-01-24 06:03:59 +00001906 } else if (DS.getTypeSpecType() == TST_decltype) {
1907 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCall2b194412009-12-21 10:41:20 +00001908 } else {
1909 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1910 LookupParsedName(R, S, &SS);
1911
1912 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1913 if (!TyD) {
1914 if (R.isAmbiguous()) return true;
1915
John McCallfd225442010-04-09 19:01:14 +00001916 // We don't want access-control diagnostics here.
1917 R.suppressDiagnostics();
1918
Douglas Gregor7a886e12010-01-19 06:46:48 +00001919 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1920 bool NotUnknownSpecialization = false;
1921 DeclContext *DC = computeDeclContext(SS, false);
1922 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1923 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1924
1925 if (!NotUnknownSpecialization) {
1926 // When the scope specifier can refer to a member of an unknown
1927 // specialization, we take it as a type name.
Douglas Gregore29425b2011-02-28 22:42:13 +00001928 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
1929 SS.getWithLocInContext(Context),
1930 *MemberOrBase, IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00001931 if (BaseType.isNull())
1932 return true;
1933
Douglas Gregor7a886e12010-01-19 06:46:48 +00001934 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00001935 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001936 }
1937 }
1938
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001939 // If no results were found, try to correct typos.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001940 TypoCorrection Corr;
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001941 MemInitializerValidatorCCC Validator(ClassDecl);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001942 if (R.empty() && BaseType.isNull() &&
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001943 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00001944 Validator, ClassDecl))) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001945 std::string CorrectedStr(Corr.getAsString(getLangOpts()));
1946 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOpts()));
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001947 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001948 // We have found a non-static data member with a similar
1949 // name to what was typed; complain and initialize that
1950 // member.
1951 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1952 << MemberOrBase << true << CorrectedQuotedStr
1953 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1954 Diag(Member->getLocation(), diag::note_previous_decl)
1955 << CorrectedQuotedStr;
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001956
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001957 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001958 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001959 const CXXBaseSpecifier *DirectBaseSpec;
1960 const CXXBaseSpecifier *VirtualBaseSpec;
1961 if (FindBaseInitializer(*this, ClassDecl,
1962 Context.getTypeDeclType(Type),
1963 DirectBaseSpec, VirtualBaseSpec)) {
1964 // We have found a direct or virtual base class with a
1965 // similar name to what was typed; complain and initialize
1966 // that base class.
1967 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001968 << MemberOrBase << false << CorrectedQuotedStr
1969 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor0d535c82010-01-07 00:26:25 +00001970
1971 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1972 : VirtualBaseSpec;
Daniel Dunbar96a00142012-03-09 18:35:03 +00001973 Diag(BaseSpec->getLocStart(),
Douglas Gregor0d535c82010-01-07 00:26:25 +00001974 diag::note_base_class_specified_here)
1975 << BaseSpec->getType()
1976 << BaseSpec->getSourceRange();
1977
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001978 TyD = Type;
1979 }
1980 }
1981 }
1982
Douglas Gregor7a886e12010-01-19 06:46:48 +00001983 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001984 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001985 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001986 return true;
1987 }
John McCall2b194412009-12-21 10:41:20 +00001988 }
1989
Douglas Gregor7a886e12010-01-19 06:46:48 +00001990 if (BaseType.isNull()) {
1991 BaseType = Context.getTypeDeclType(TyD);
1992 if (SS.isSet()) {
1993 NestedNameSpecifier *Qualifier =
1994 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00001995
Douglas Gregor7a886e12010-01-19 06:46:48 +00001996 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001997 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001998 }
John McCall2b194412009-12-21 10:41:20 +00001999 }
2000 }
Mike Stump1eb44332009-09-09 15:08:12 +00002001
John McCalla93c9342009-12-07 02:54:59 +00002002 if (!TInfo)
2003 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002004
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002005 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00002006}
2007
Chandler Carruth81c64772011-09-03 01:14:15 +00002008/// Checks a member initializer expression for cases where reference (or
2009/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth81c64772011-09-03 01:14:15 +00002010static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2011 Expr *Init,
2012 SourceLocation IdLoc) {
2013 QualType MemberTy = Member->getType();
2014
2015 // We only handle pointers and references currently.
2016 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2017 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2018 return;
2019
2020 const bool IsPointer = MemberTy->isPointerType();
2021 if (IsPointer) {
2022 if (const UnaryOperator *Op
2023 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2024 // The only case we're worried about with pointers requires taking the
2025 // address.
2026 if (Op->getOpcode() != UO_AddrOf)
2027 return;
2028
2029 Init = Op->getSubExpr();
2030 } else {
2031 // We only handle address-of expression initializers for pointers.
2032 return;
2033 }
2034 }
2035
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002036 if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) {
2037 // Taking the address of a temporary will be diagnosed as a hard error.
2038 if (IsPointer)
2039 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002040
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002041 S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary)
2042 << Member << Init->getSourceRange();
2043 } else if (const DeclRefExpr *DRE
2044 = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
2045 // We only warn when referring to a non-reference parameter declaration.
2046 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2047 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth81c64772011-09-03 01:14:15 +00002048 return;
2049
2050 S.Diag(Init->getExprLoc(),
2051 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2052 : diag::warn_bind_ref_member_to_parameter)
2053 << Member << Parameter << Init->getSourceRange();
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002054 } else {
2055 // Other initializers are fine.
2056 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002057 }
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002058
2059 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2060 << (unsigned)IsPointer;
Chandler Carruth81c64772011-09-03 01:14:15 +00002061}
2062
Richard Trieude5e75c2012-06-14 23:11:34 +00002063namespace {
2064 class UninitializedFieldVisitor
2065 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2066 Sema &S;
2067 ValueDecl *VD;
2068 public:
2069 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
2070 UninitializedFieldVisitor(Sema &S, ValueDecl *VD) : Inherited(S.Context),
2071 S(S), VD(VD) {
Anders Carlsson175ffbf2010-10-06 02:43:25 +00002072 }
2073
Richard Trieude5e75c2012-06-14 23:11:34 +00002074 void HandleExpr(Expr *E) {
2075 if (!E) return;
2076
2077 // Expressions like x(x) sometimes lack the surrounding expressions
2078 // but need to be checked anyways.
2079 HandleValue(E);
2080 Visit(E);
2081 }
2082
2083 void HandleValue(Expr *E) {
2084 E = E->IgnoreParens();
2085
Richard Trieue0991252012-06-14 23:18:09 +00002086 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
Richard Trieude5e75c2012-06-14 23:11:34 +00002087 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
2088 return;
Richard Trieue0991252012-06-14 23:18:09 +00002089 Expr *Base = E;
Richard Trieude5e75c2012-06-14 23:11:34 +00002090 while (isa<MemberExpr>(Base)) {
2091 ME = dyn_cast<MemberExpr>(Base);
2092 if (VarDecl *VarD = dyn_cast<VarDecl>(ME->getMemberDecl()))
2093 if (VarD->hasGlobalStorage())
2094 return;
2095 Base = ME->getBase();
2096 }
2097
2098 if (VD == ME->getMemberDecl() && isa<CXXThisExpr>(Base)) {
Hans Wennborg5965b7c2012-08-20 08:52:22 +00002099 unsigned diag = VD->getType()->isReferenceType()
2100 ? diag::warn_reference_field_is_uninit
2101 : diag::warn_field_is_uninit;
2102 S.Diag(ME->getExprLoc(), diag);
Richard Trieude5e75c2012-06-14 23:11:34 +00002103 return;
2104 }
John McCallb4190042009-11-04 23:02:40 +00002105 }
Richard Trieude5e75c2012-06-14 23:11:34 +00002106
2107 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2108 HandleValue(CO->getTrueExpr());
2109 HandleValue(CO->getFalseExpr());
2110 return;
2111 }
2112
2113 if (BinaryConditionalOperator *BCO =
2114 dyn_cast<BinaryConditionalOperator>(E)) {
2115 HandleValue(BCO->getCommon());
2116 HandleValue(BCO->getFalseExpr());
2117 return;
2118 }
2119
2120 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2121 switch (BO->getOpcode()) {
2122 default:
2123 return;
2124 case(BO_PtrMemD):
2125 case(BO_PtrMemI):
2126 HandleValue(BO->getLHS());
2127 return;
2128 case(BO_Comma):
2129 HandleValue(BO->getRHS());
2130 return;
2131 }
2132 }
John McCallb4190042009-11-04 23:02:40 +00002133 }
Richard Trieude5e75c2012-06-14 23:11:34 +00002134
2135 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
2136 if (E->getCastKind() == CK_LValueToRValue)
2137 HandleValue(E->getSubExpr());
2138
2139 Inherited::VisitImplicitCastExpr(E);
John McCallb4190042009-11-04 23:02:40 +00002140 }
Richard Trieude5e75c2012-06-14 23:11:34 +00002141
2142 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2143 Expr *Callee = E->getCallee();
2144 if (isa<MemberExpr>(Callee))
2145 HandleValue(Callee);
2146
2147 Inherited::VisitCXXMemberCallExpr(E);
2148 }
2149 };
2150 static void CheckInitExprContainsUninitializedFields(Sema &S, Expr *E,
2151 ValueDecl *VD) {
2152 UninitializedFieldVisitor(S, VD).HandleExpr(E);
John McCallb4190042009-11-04 23:02:40 +00002153 }
Richard Trieude5e75c2012-06-14 23:11:34 +00002154} // namespace
John McCallb4190042009-11-04 23:02:40 +00002155
John McCallf312b1e2010-08-26 23:41:50 +00002156MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002157Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002158 SourceLocation IdLoc) {
Chandler Carruth894aed92010-12-06 09:23:57 +00002159 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2160 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2161 assert((DirectMember || IndirectMember) &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00002162 "Member must be a FieldDecl or IndirectFieldDecl");
2163
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002164 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbournefef21892011-10-23 18:59:44 +00002165 return true;
2166
Douglas Gregor464b2f02010-11-05 22:21:31 +00002167 if (Member->isInvalidDecl())
2168 return true;
Chandler Carruth894aed92010-12-06 09:23:57 +00002169
John McCallb4190042009-11-04 23:02:40 +00002170 // Diagnose value-uses of fields to initialize themselves, e.g.
2171 // foo(foo)
2172 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00002173 // TODO: implement -Wuninitialized and fold this into that framework.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002174 Expr **Args;
2175 unsigned NumArgs;
2176 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2177 Args = ParenList->getExprs();
2178 NumArgs = ParenList->getNumExprs();
2179 } else {
2180 InitListExpr *InitList = cast<InitListExpr>(Init);
2181 Args = InitList->getInits();
2182 NumArgs = InitList->getNumInits();
2183 }
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002184
Richard Trieude5e75c2012-06-14 23:11:34 +00002185 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, IdLoc)
2186 != DiagnosticsEngine::Ignored)
2187 for (unsigned i = 0; i < NumArgs; ++i)
2188 // FIXME: Warn about the case when other fields are used before being
John McCallb4190042009-11-04 23:02:40 +00002189 // uninitialized. For example, let this field be the i'th field. When
2190 // initializing the i'th field, throw a warning if any of the >= i'th
2191 // fields are used, as they are not yet initialized.
2192 // Right now we are only handling the case where the i'th field uses
2193 // itself in its initializer.
Richard Trieude5e75c2012-06-14 23:11:34 +00002194 CheckInitExprContainsUninitializedFields(*this, Args[i], Member);
John McCallb4190042009-11-04 23:02:40 +00002195
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002196 SourceRange InitRange = Init->getSourceRange();
Eli Friedman59c04372009-07-29 19:44:27 +00002197
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002198 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002199 // Can't check initialization for a member of dependent type or when
2200 // any of the arguments are type-dependent expressions.
John McCallf85e1932011-06-15 23:02:42 +00002201 DiscardCleanupsInEvaluationContext();
Chandler Carruth894aed92010-12-06 09:23:57 +00002202 } else {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002203 bool InitList = false;
2204 if (isa<InitListExpr>(Init)) {
2205 InitList = true;
2206 Args = &Init;
2207 NumArgs = 1;
Sebastian Redl772291a2012-02-19 16:31:05 +00002208
2209 if (isStdInitializerList(Member->getType(), 0)) {
2210 Diag(IdLoc, diag::warn_dangling_std_initializer_list)
2211 << /*at end of ctor*/1 << InitRange;
2212 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002213 }
2214
Chandler Carruth894aed92010-12-06 09:23:57 +00002215 // Initialize the member.
2216 InitializedEntity MemberEntity =
2217 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2218 : InitializedEntity::InitializeMember(IndirectMember, 0);
2219 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002220 InitList ? InitializationKind::CreateDirectList(IdLoc)
2221 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2222 InitRange.getEnd());
John McCallb4eb64d2010-10-08 02:01:28 +00002223
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002224 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
2225 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind,
Benjamin Kramer5354e772012-08-23 23:38:35 +00002226 MultiExprArg(Args, NumArgs),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002227 0);
Chandler Carruth894aed92010-12-06 09:23:57 +00002228 if (MemberInit.isInvalid())
2229 return true;
2230
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002231 CheckImplicitConversions(MemberInit.get(),
2232 InitRange.getBegin());
Chandler Carruth894aed92010-12-06 09:23:57 +00002233
2234 // C++0x [class.base.init]p7:
2235 // The initialization of each base and member constitutes a
2236 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00002237 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Chandler Carruth894aed92010-12-06 09:23:57 +00002238 if (MemberInit.isInvalid())
2239 return true;
2240
2241 // If we are in a dependent context, template instantiation will
2242 // perform this type-checking again. Just save the arguments that we
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002243 // received.
Chandler Carruth894aed92010-12-06 09:23:57 +00002244 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2245 // of the information that we have about the member
2246 // initializer. However, deconstructing the ASTs is a dicey process,
2247 // and this approach is far more likely to get the corner cases right.
Chandler Carruth81c64772011-09-03 01:14:15 +00002248 if (CurContext->isDependentContext()) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002249 // The existing Init will do fine.
Chandler Carruth81c64772011-09-03 01:14:15 +00002250 } else {
Chandler Carruth894aed92010-12-06 09:23:57 +00002251 Init = MemberInit.get();
Chandler Carruth81c64772011-09-03 01:14:15 +00002252 CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc);
2253 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002254 }
2255
Chandler Carruth894aed92010-12-06 09:23:57 +00002256 if (DirectMember) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002257 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2258 InitRange.getBegin(), Init,
2259 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002260 } else {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002261 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2262 InitRange.getBegin(), Init,
2263 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002264 }
Eli Friedman59c04372009-07-29 19:44:27 +00002265}
2266
John McCallf312b1e2010-08-26 23:41:50 +00002267MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002268Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Sean Hunt41717662011-02-26 19:13:13 +00002269 CXXRecordDecl *ClassDecl) {
Douglas Gregor76852c22011-11-01 01:16:03 +00002270 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sean Hunt97fcc492011-01-08 19:20:43 +00002271 if (!LangOpts.CPlusPlus0x)
Douglas Gregor76852c22011-11-01 01:16:03 +00002272 return Diag(NameLoc, diag::err_delegating_ctor)
Sean Hunt97fcc492011-01-08 19:20:43 +00002273 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor76852c22011-11-01 01:16:03 +00002274 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redlf9c32eb2011-03-12 13:53:51 +00002275
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002276 bool InitList = true;
2277 Expr **Args = &Init;
2278 unsigned NumArgs = 1;
2279 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2280 InitList = false;
2281 Args = ParenList->getExprs();
2282 NumArgs = ParenList->getNumExprs();
2283 }
2284
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002285 SourceRange InitRange = Init->getSourceRange();
Sean Hunt41717662011-02-26 19:13:13 +00002286 // Initialize the object.
2287 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2288 QualType(ClassDecl->getTypeForDecl(), 0));
2289 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002290 InitList ? InitializationKind::CreateDirectList(NameLoc)
2291 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2292 InitRange.getEnd());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002293 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs);
2294 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
Benjamin Kramer5354e772012-08-23 23:38:35 +00002295 MultiExprArg(Args, NumArgs),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002296 0);
Sean Hunt41717662011-02-26 19:13:13 +00002297 if (DelegationInit.isInvalid())
2298 return true;
2299
Matt Beaumont-Gay2eb0ce32011-11-01 18:10:22 +00002300 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2301 "Delegating constructor with no target?");
Sean Hunt41717662011-02-26 19:13:13 +00002302
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002303 CheckImplicitConversions(DelegationInit.get(), InitRange.getBegin());
Sean Hunt41717662011-02-26 19:13:13 +00002304
2305 // C++0x [class.base.init]p7:
2306 // The initialization of each base and member constitutes a
2307 // full-expression.
2308 DelegationInit = MaybeCreateExprWithCleanups(DelegationInit);
2309 if (DelegationInit.isInvalid())
2310 return true;
2311
Eli Friedmand21016f2012-05-19 23:35:23 +00002312 // If we are in a dependent context, template instantiation will
2313 // perform this type-checking again. Just save the arguments that we
2314 // received in a ParenListExpr.
2315 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2316 // of the information that we have about the base
2317 // initializer. However, deconstructing the ASTs is a dicey process,
2318 // and this approach is far more likely to get the corner cases right.
2319 if (CurContext->isDependentContext())
2320 DelegationInit = Owned(Init);
2321
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002322 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Sean Hunt41717662011-02-26 19:13:13 +00002323 DelegationInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002324 InitRange.getEnd());
Sean Hunt97fcc492011-01-08 19:20:43 +00002325}
2326
2327MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00002328Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002329 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002330 SourceLocation EllipsisLoc) {
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002331 SourceLocation BaseLoc
2332 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redl6df65482011-09-24 17:48:25 +00002333
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002334 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2335 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2336 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2337
2338 // C++ [class.base.init]p2:
2339 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00002340 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002341 // of that class, the mem-initializer is ill-formed. A
2342 // mem-initializer-list can initialize a base class using any
2343 // name that denotes that base class type.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002344 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002345
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002346 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002347 if (EllipsisLoc.isValid()) {
2348 // This is a pack expansion.
2349 if (!BaseType->containsUnexpandedParameterPack()) {
2350 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002351 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002352
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002353 EllipsisLoc = SourceLocation();
2354 }
2355 } else {
2356 // Check for any unexpanded parameter packs.
2357 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2358 return true;
Sebastian Redl6df65482011-09-24 17:48:25 +00002359
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002360 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redl6df65482011-09-24 17:48:25 +00002361 return true;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002362 }
Sebastian Redl6df65482011-09-24 17:48:25 +00002363
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002364 // Check for direct and virtual base classes.
2365 const CXXBaseSpecifier *DirectBaseSpec = 0;
2366 const CXXBaseSpecifier *VirtualBaseSpec = 0;
2367 if (!Dependent) {
Sean Hunt97fcc492011-01-08 19:20:43 +00002368 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2369 BaseType))
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002370 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Sean Hunt97fcc492011-01-08 19:20:43 +00002371
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002372 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2373 VirtualBaseSpec);
2374
2375 // C++ [base.class.init]p2:
2376 // Unless the mem-initializer-id names a nonstatic data member of the
2377 // constructor's class or a direct or virtual base of that class, the
2378 // mem-initializer is ill-formed.
2379 if (!DirectBaseSpec && !VirtualBaseSpec) {
2380 // If the class has any dependent bases, then it's possible that
2381 // one of those types will resolve to the same type as
2382 // BaseType. Therefore, just treat this as a dependent base
2383 // class initialization. FIXME: Should we try to check the
2384 // initialization anyway? It seems odd.
2385 if (ClassDecl->hasAnyDependentBases())
2386 Dependent = true;
2387 else
2388 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2389 << BaseType << Context.getTypeDeclType(ClassDecl)
2390 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2391 }
2392 }
2393
2394 if (Dependent) {
John McCallf85e1932011-06-15 23:02:42 +00002395 DiscardCleanupsInEvaluationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002396
Sebastian Redl6df65482011-09-24 17:48:25 +00002397 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2398 /*IsVirtual=*/false,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002399 InitRange.getBegin(), Init,
2400 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002401 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002402
2403 // C++ [base.class.init]p2:
2404 // If a mem-initializer-id is ambiguous because it designates both
2405 // a direct non-virtual base class and an inherited virtual base
2406 // class, the mem-initializer is ill-formed.
2407 if (DirectBaseSpec && VirtualBaseSpec)
2408 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002409 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002410
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002411 CXXBaseSpecifier *BaseSpec = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002412 if (!BaseSpec)
2413 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
2414
2415 // Initialize the base.
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002416 bool InitList = true;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002417 Expr **Args = &Init;
2418 unsigned NumArgs = 1;
2419 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002420 InitList = false;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002421 Args = ParenList->getExprs();
2422 NumArgs = ParenList->getNumExprs();
2423 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002424
2425 InitializedEntity BaseEntity =
2426 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2427 InitializationKind Kind =
2428 InitList ? InitializationKind::CreateDirectList(BaseLoc)
2429 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2430 InitRange.getEnd());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002431 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
2432 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind,
Benjamin Kramer5354e772012-08-23 23:38:35 +00002433 MultiExprArg(Args, NumArgs), 0);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002434 if (BaseInit.isInvalid())
2435 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00002436
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002437 CheckImplicitConversions(BaseInit.get(), InitRange.getBegin());
Sebastian Redl6df65482011-09-24 17:48:25 +00002438
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002439 // C++0x [class.base.init]p7:
2440 // The initialization of each base and member constitutes a
2441 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00002442 BaseInit = MaybeCreateExprWithCleanups(BaseInit);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002443 if (BaseInit.isInvalid())
2444 return true;
2445
2446 // If we are in a dependent context, template instantiation will
2447 // perform this type-checking again. Just save the arguments that we
2448 // received in a ParenListExpr.
2449 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2450 // of the information that we have about the base
2451 // initializer. However, deconstructing the ASTs is a dicey process,
2452 // and this approach is far more likely to get the corner cases right.
Sebastian Redl6df65482011-09-24 17:48:25 +00002453 if (CurContext->isDependentContext())
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002454 BaseInit = Owned(Init);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002455
Sean Huntcbb67482011-01-08 20:30:50 +00002456 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00002457 BaseSpec->isVirtual(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002458 InitRange.getBegin(),
Sebastian Redl6df65482011-09-24 17:48:25 +00002459 BaseInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002460 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002461}
2462
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002463// Create a static_cast\<T&&>(expr).
2464static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
2465 QualType ExprType = E->getType();
2466 QualType TargetType = SemaRef.Context.getRValueReferenceType(ExprType);
2467 SourceLocation ExprLoc = E->getLocStart();
2468 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2469 TargetType, ExprLoc);
2470
2471 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2472 SourceRange(ExprLoc, ExprLoc),
2473 E->getSourceRange()).take();
2474}
2475
Anders Carlssone5ef7402010-04-23 03:10:23 +00002476/// ImplicitInitializerKind - How an implicit base or member initializer should
2477/// initialize its base or member.
2478enum ImplicitInitializerKind {
2479 IIK_Default,
2480 IIK_Copy,
2481 IIK_Move
2482};
2483
Anders Carlssondefefd22010-04-23 02:00:02 +00002484static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002485BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002486 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002487 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00002488 bool IsInheritedVirtualBase,
Sean Huntcbb67482011-01-08 20:30:50 +00002489 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00002490 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00002491 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2492 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00002493
John McCall60d7b3a2010-08-24 06:29:42 +00002494 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002495
2496 switch (ImplicitInitKind) {
2497 case IIK_Default: {
2498 InitializationKind InitKind
2499 = InitializationKind::CreateDefault(Constructor->getLocation());
2500 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
Benjamin Kramer5354e772012-08-23 23:38:35 +00002501 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
Anders Carlssone5ef7402010-04-23 03:10:23 +00002502 break;
2503 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002504
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002505 case IIK_Move:
Anders Carlssone5ef7402010-04-23 03:10:23 +00002506 case IIK_Copy: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002507 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002508 ParmVarDecl *Param = Constructor->getParamDecl(0);
2509 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedmancf7c14c2012-01-16 21:00:51 +00002510
Anders Carlssone5ef7402010-04-23 03:10:23 +00002511 Expr *CopyCtorArg =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002512 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002513 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002514 Constructor->getLocation(), ParamType,
2515 VK_LValue, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002516
Eli Friedman5f2987c2012-02-02 03:46:19 +00002517 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
2518
Anders Carlssonc7957502010-04-24 22:02:54 +00002519 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00002520 QualType ArgTy =
2521 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2522 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00002523
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002524 if (Moving) {
2525 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2526 }
2527
John McCallf871d0c2010-08-07 06:22:56 +00002528 CXXCastPath BasePath;
2529 BasePath.push_back(BaseSpec);
John Wiegley429bb272011-04-08 18:41:53 +00002530 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2531 CK_UncheckedDerivedToBase,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002532 Moving ? VK_XValue : VK_LValue,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002533 &BasePath).take();
Anders Carlssonc7957502010-04-24 22:02:54 +00002534
Anders Carlssone5ef7402010-04-23 03:10:23 +00002535 InitializationKind InitKind
2536 = InitializationKind::CreateDirect(Constructor->getLocation(),
2537 SourceLocation(), SourceLocation());
2538 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
2539 &CopyCtorArg, 1);
2540 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00002541 MultiExprArg(&CopyCtorArg, 1));
Anders Carlssone5ef7402010-04-23 03:10:23 +00002542 break;
2543 }
Anders Carlssone5ef7402010-04-23 03:10:23 +00002544 }
John McCall9ae2f072010-08-23 23:25:46 +00002545
Douglas Gregor53c374f2010-12-07 00:41:46 +00002546 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00002547 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00002548 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00002549
Anders Carlssondefefd22010-04-23 02:00:02 +00002550 CXXBaseInit =
Sean Huntcbb67482011-01-08 20:30:50 +00002551 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlsson84688f22010-04-20 23:11:20 +00002552 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2553 SourceLocation()),
2554 BaseSpec->isVirtual(),
2555 SourceLocation(),
2556 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002557 SourceLocation(),
Anders Carlsson84688f22010-04-20 23:11:20 +00002558 SourceLocation());
2559
Anders Carlssondefefd22010-04-23 02:00:02 +00002560 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00002561}
2562
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002563static bool RefersToRValueRef(Expr *MemRef) {
2564 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2565 return Referenced->getType()->isRValueReferenceType();
2566}
2567
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002568static bool
2569BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002570 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002571 FieldDecl *Field, IndirectFieldDecl *Indirect,
Sean Huntcbb67482011-01-08 20:30:50 +00002572 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002573 if (Field->isInvalidDecl())
2574 return true;
2575
Chandler Carruthf186b542010-06-29 23:50:44 +00002576 SourceLocation Loc = Constructor->getLocation();
2577
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002578 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2579 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002580 ParmVarDecl *Param = Constructor->getParamDecl(0);
2581 QualType ParamType = Param->getType().getNonReferenceType();
John McCallb77115d2011-06-17 00:18:42 +00002582
2583 // Suppress copying zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002584 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
2585 return false;
Douglas Gregorddb21472011-11-02 23:04:16 +00002586
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002587 Expr *MemberExprBase =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002588 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002589 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002590 Loc, ParamType, VK_LValue, 0);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002591
Eli Friedman5f2987c2012-02-02 03:46:19 +00002592 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
2593
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002594 if (Moving) {
2595 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2596 }
2597
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002598 // Build a reference to this field within the parameter.
2599 CXXScopeSpec SS;
2600 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2601 Sema::LookupMemberName);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002602 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2603 : cast<ValueDecl>(Field), AS_public);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002604 MemberLookup.resolveKind();
Sebastian Redl74e611a2011-09-04 18:14:28 +00002605 ExprResult CtorArg
John McCall9ae2f072010-08-23 23:25:46 +00002606 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002607 ParamType, Loc,
2608 /*IsArrow=*/false,
2609 SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002610 /*TemplateKWLoc=*/SourceLocation(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002611 /*FirstQualifierInScope=*/0,
2612 MemberLookup,
2613 /*TemplateArgs=*/0);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002614 if (CtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002615 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002616
2617 // C++11 [class.copy]p15:
2618 // - if a member m has rvalue reference type T&&, it is direct-initialized
2619 // with static_cast<T&&>(x.m);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002620 if (RefersToRValueRef(CtorArg.get())) {
2621 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002622 }
2623
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002624 // When the field we are copying is an array, create index variables for
2625 // each dimension of the array. We use these index variables to subscript
2626 // the source array, and other clients (e.g., CodeGen) will perform the
2627 // necessary iteration with these index variables.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002628 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002629 QualType BaseType = Field->getType();
2630 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002631 bool InitializingArray = false;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002632 while (const ConstantArrayType *Array
2633 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002634 InitializingArray = true;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002635 // Create the iteration variable for this array index.
2636 IdentifierInfo *IterationVarName = 0;
2637 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002638 SmallString<8> Str;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002639 llvm::raw_svector_ostream OS(Str);
2640 OS << "__i" << IndexVariables.size();
2641 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
2642 }
2643 VarDecl *IterationVar
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002644 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002645 IterationVarName, SizeType,
2646 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00002647 SC_None, SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002648 IndexVariables.push_back(IterationVar);
2649
2650 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00002651 ExprResult IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00002652 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002653 assert(!IterationVarRef.isInvalid() &&
2654 "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00002655 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
2656 assert(!IterationVarRef.isInvalid() &&
2657 "Conversion of invented variable cannot fail!");
Sebastian Redl74e611a2011-09-04 18:14:28 +00002658
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002659 // Subscript the array with this iteration variable.
Sebastian Redl74e611a2011-09-04 18:14:28 +00002660 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCall9ae2f072010-08-23 23:25:46 +00002661 IterationVarRef.take(),
Sebastian Redl74e611a2011-09-04 18:14:28 +00002662 Loc);
2663 if (CtorArg.isInvalid())
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002664 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002665
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002666 BaseType = Array->getElementType();
2667 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002668
2669 // The array subscript expression is an lvalue, which is wrong for moving.
2670 if (Moving && InitializingArray)
Sebastian Redl74e611a2011-09-04 18:14:28 +00002671 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002672
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002673 // Construct the entity that we will be initializing. For an array, this
2674 // will be first element in the array, which may require several levels
2675 // of array-subscript entities.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002676 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002677 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002678 if (Indirect)
2679 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
2680 else
2681 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002682 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
2683 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
2684 0,
2685 Entities.back()));
2686
2687 // Direct-initialize to use the copy constructor.
2688 InitializationKind InitKind =
2689 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
2690
Sebastian Redl74e611a2011-09-04 18:14:28 +00002691 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002692 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002693 &CtorArgE, 1);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002694
John McCall60d7b3a2010-08-24 06:29:42 +00002695 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002696 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002697 MultiExprArg(&CtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00002698 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002699 if (MemberInit.isInvalid())
2700 return true;
2701
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002702 if (Indirect) {
2703 assert(IndexVariables.size() == 0 &&
2704 "Indirect field improperly initialized");
2705 CXXMemberInit
2706 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2707 Loc, Loc,
2708 MemberInit.takeAs<Expr>(),
2709 Loc);
2710 } else
2711 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
2712 Loc, MemberInit.takeAs<Expr>(),
2713 Loc,
2714 IndexVariables.data(),
2715 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00002716 return false;
2717 }
2718
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002719 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
2720
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002721 QualType FieldBaseElementType =
2722 SemaRef.Context.getBaseElementType(Field->getType());
2723
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002724 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002725 InitializedEntity InitEntity
2726 = Indirect? InitializedEntity::InitializeMember(Indirect)
2727 : InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002728 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00002729 InitializationKind::CreateDefault(Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002730
2731 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00002732 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00002733 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCall9ae2f072010-08-23 23:25:46 +00002734
Douglas Gregor53c374f2010-12-07 00:41:46 +00002735 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002736 if (MemberInit.isInvalid())
2737 return true;
2738
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002739 if (Indirect)
2740 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2741 Indirect, Loc,
2742 Loc,
2743 MemberInit.get(),
2744 Loc);
2745 else
2746 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2747 Field, Loc, Loc,
2748 MemberInit.get(),
2749 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002750 return false;
2751 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002752
Sean Hunt1f2f3842011-05-17 00:19:05 +00002753 if (!Field->getParent()->isUnion()) {
2754 if (FieldBaseElementType->isReferenceType()) {
2755 SemaRef.Diag(Constructor->getLocation(),
2756 diag::err_uninitialized_member_in_ctor)
2757 << (int)Constructor->isImplicit()
2758 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2759 << 0 << Field->getDeclName();
2760 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2761 return true;
2762 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002763
Sean Hunt1f2f3842011-05-17 00:19:05 +00002764 if (FieldBaseElementType.isConstQualified()) {
2765 SemaRef.Diag(Constructor->getLocation(),
2766 diag::err_uninitialized_member_in_ctor)
2767 << (int)Constructor->isImplicit()
2768 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2769 << 1 << Field->getDeclName();
2770 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2771 return true;
2772 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002773 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002774
David Blaikie4e4d0842012-03-11 07:00:24 +00002775 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00002776 FieldBaseElementType->isObjCRetainableType() &&
2777 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
2778 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
Douglas Gregor3fe52ff2012-07-23 04:23:39 +00002779 // ARC:
John McCallf85e1932011-06-15 23:02:42 +00002780 // Default-initialize Objective-C pointers to NULL.
2781 CXXMemberInit
2782 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2783 Loc, Loc,
2784 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
2785 Loc);
2786 return false;
2787 }
2788
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002789 // Nothing to initialize.
2790 CXXMemberInit = 0;
2791 return false;
2792}
John McCallf1860e52010-05-20 23:23:51 +00002793
2794namespace {
2795struct BaseAndFieldInfo {
2796 Sema &S;
2797 CXXConstructorDecl *Ctor;
2798 bool AnyErrorsInInits;
2799 ImplicitInitializerKind IIK;
Sean Huntcbb67482011-01-08 20:30:50 +00002800 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002801 SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallf1860e52010-05-20 23:23:51 +00002802
2803 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
2804 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002805 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
2806 if (Generated && Ctor->isCopyConstructor())
John McCallf1860e52010-05-20 23:23:51 +00002807 IIK = IIK_Copy;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002808 else if (Generated && Ctor->isMoveConstructor())
2809 IIK = IIK_Move;
John McCallf1860e52010-05-20 23:23:51 +00002810 else
2811 IIK = IIK_Default;
2812 }
Douglas Gregorf4853882011-11-28 20:03:15 +00002813
2814 bool isImplicitCopyOrMove() const {
2815 switch (IIK) {
2816 case IIK_Copy:
2817 case IIK_Move:
2818 return true;
2819
2820 case IIK_Default:
2821 return false;
2822 }
David Blaikie30263482012-01-20 21:50:17 +00002823
2824 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregorf4853882011-11-28 20:03:15 +00002825 }
Richard Smith0b8220a2012-08-07 21:30:42 +00002826
2827 bool addFieldInitializer(CXXCtorInitializer *Init) {
2828 AllToInit.push_back(Init);
2829
2830 // Check whether this initializer makes the field "used".
2831 if (Init->getInit() && Init->getInit()->HasSideEffects(S.Context))
2832 S.UnusedPrivateFields.remove(Init->getAnyMember());
2833
2834 return false;
2835 }
John McCallf1860e52010-05-20 23:23:51 +00002836};
2837}
2838
Richard Smitha4950662011-09-19 13:34:43 +00002839/// \brief Determine whether the given indirect field declaration is somewhere
2840/// within an anonymous union.
2841static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
2842 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
2843 CEnd = F->chain_end();
2844 C != CEnd; ++C)
2845 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
2846 if (Record->isUnion())
2847 return true;
2848
2849 return false;
2850}
2851
Douglas Gregorddb21472011-11-02 23:04:16 +00002852/// \brief Determine whether the given type is an incomplete or zero-lenfgth
2853/// array type.
2854static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
2855 if (T->isIncompleteArrayType())
2856 return true;
2857
2858 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
2859 if (!ArrayT->getSize())
2860 return true;
2861
2862 T = ArrayT->getElementType();
2863 }
2864
2865 return false;
2866}
2867
Richard Smith7a614d82011-06-11 17:19:42 +00002868static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002869 FieldDecl *Field,
2870 IndirectFieldDecl *Indirect = 0) {
John McCallf1860e52010-05-20 23:23:51 +00002871
Chandler Carruthe861c602010-06-30 02:59:29 +00002872 // Overwhelmingly common case: we have a direct initializer for this field.
Richard Smith0b8220a2012-08-07 21:30:42 +00002873 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field))
2874 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00002875
Richard Smith0b8220a2012-08-07 21:30:42 +00002876 // C++11 [class.base.init]p8: if the entity is a non-static data member that
Richard Smith7a614d82011-06-11 17:19:42 +00002877 // has a brace-or-equal-initializer, the entity is initialized as specified
2878 // in [dcl.init].
Douglas Gregorf4853882011-11-28 20:03:15 +00002879 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002880 CXXCtorInitializer *Init;
2881 if (Indirect)
2882 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2883 SourceLocation(),
2884 SourceLocation(), 0,
2885 SourceLocation());
2886 else
2887 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2888 SourceLocation(),
2889 SourceLocation(), 0,
2890 SourceLocation());
Richard Smith0b8220a2012-08-07 21:30:42 +00002891 return Info.addFieldInitializer(Init);
Richard Smith7a614d82011-06-11 17:19:42 +00002892 }
2893
Richard Smithc115f632011-09-18 11:14:50 +00002894 // Don't build an implicit initializer for union members if none was
2895 // explicitly specified.
Richard Smitha4950662011-09-19 13:34:43 +00002896 if (Field->getParent()->isUnion() ||
2897 (Indirect && isWithinAnonymousUnion(Indirect)))
Richard Smithc115f632011-09-18 11:14:50 +00002898 return false;
2899
Douglas Gregorddb21472011-11-02 23:04:16 +00002900 // Don't initialize incomplete or zero-length arrays.
2901 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
2902 return false;
2903
John McCallf1860e52010-05-20 23:23:51 +00002904 // Don't try to build an implicit initializer if there were semantic
2905 // errors in any of the initializers (and therefore we might be
2906 // missing some that the user actually wrote).
Richard Smith7a614d82011-06-11 17:19:42 +00002907 if (Info.AnyErrorsInInits || Field->isInvalidDecl())
John McCallf1860e52010-05-20 23:23:51 +00002908 return false;
2909
Sean Huntcbb67482011-01-08 20:30:50 +00002910 CXXCtorInitializer *Init = 0;
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002911 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
2912 Indirect, Init))
John McCallf1860e52010-05-20 23:23:51 +00002913 return true;
John McCallf1860e52010-05-20 23:23:51 +00002914
Richard Smith0b8220a2012-08-07 21:30:42 +00002915 if (!Init)
2916 return false;
Francois Pichet00eb3f92010-12-04 09:14:42 +00002917
Richard Smith0b8220a2012-08-07 21:30:42 +00002918 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00002919}
Sean Hunt059ce0d2011-05-01 07:04:31 +00002920
2921bool
2922Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
2923 CXXCtorInitializer *Initializer) {
Sean Huntfe57eef2011-05-04 05:57:24 +00002924 assert(Initializer->isDelegatingInitializer());
Sean Hunt01aacc02011-05-03 20:43:02 +00002925 Constructor->setNumCtorInitializers(1);
2926 CXXCtorInitializer **initializer =
2927 new (Context) CXXCtorInitializer*[1];
2928 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
2929 Constructor->setCtorInitializers(initializer);
2930
Sean Huntb76af9c2011-05-03 23:05:34 +00002931 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00002932 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Sean Huntb76af9c2011-05-03 23:05:34 +00002933 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
2934 }
2935
Sean Huntc1598702011-05-05 00:05:47 +00002936 DelegatingCtorDecls.push_back(Constructor);
Sean Huntfe57eef2011-05-04 05:57:24 +00002937
Sean Hunt059ce0d2011-05-01 07:04:31 +00002938 return false;
2939}
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002940
John McCallb77115d2011-06-17 00:18:42 +00002941bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
2942 CXXCtorInitializer **Initializers,
2943 unsigned NumInitializers,
2944 bool AnyErrors) {
Douglas Gregord836c0d2011-09-22 23:04:35 +00002945 if (Constructor->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002946 // Just store the initializers as written, they will be checked during
2947 // instantiation.
2948 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00002949 Constructor->setNumCtorInitializers(NumInitializers);
2950 CXXCtorInitializer **baseOrMemberInitializers =
2951 new (Context) CXXCtorInitializer*[NumInitializers];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002952 memcpy(baseOrMemberInitializers, Initializers,
Sean Huntcbb67482011-01-08 20:30:50 +00002953 NumInitializers * sizeof(CXXCtorInitializer*));
2954 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002955 }
2956
2957 return false;
2958 }
2959
John McCallf1860e52010-05-20 23:23:51 +00002960 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00002961
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002962 // We need to build the initializer AST according to order of construction
2963 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00002964 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00002965 if (!ClassDecl)
2966 return true;
2967
Eli Friedman80c30da2009-11-09 19:20:36 +00002968 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002969
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002970 for (unsigned i = 0; i < NumInitializers; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00002971 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002972
2973 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00002974 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002975 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00002976 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002977 }
2978
Anders Carlsson711f34a2010-04-21 19:52:01 +00002979 // Keep track of the direct virtual bases.
2980 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
2981 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
2982 E = ClassDecl->bases_end(); I != E; ++I) {
2983 if (I->isVirtual())
2984 DirectVBases.insert(I);
2985 }
2986
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002987 // Push virtual bases before others.
2988 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2989 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2990
Sean Huntcbb67482011-01-08 20:30:50 +00002991 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00002992 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
2993 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002994 } else if (!AnyErrors) {
Anders Carlsson711f34a2010-04-21 19:52:01 +00002995 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00002996 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00002997 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002998 VBase, IsInheritedVirtualBase,
2999 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003000 HadError = true;
3001 continue;
3002 }
Anders Carlsson84688f22010-04-20 23:11:20 +00003003
John McCallf1860e52010-05-20 23:23:51 +00003004 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003005 }
3006 }
Mike Stump1eb44332009-09-09 15:08:12 +00003007
John McCallf1860e52010-05-20 23:23:51 +00003008 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003009 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3010 E = ClassDecl->bases_end(); Base != E; ++Base) {
3011 // Virtuals are in the virtual base list and already constructed.
3012 if (Base->isVirtual())
3013 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00003014
Sean Huntcbb67482011-01-08 20:30:50 +00003015 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00003016 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
3017 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003018 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00003019 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003020 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003021 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00003022 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003023 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003024 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003025 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00003026
John McCallf1860e52010-05-20 23:23:51 +00003027 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003028 }
3029 }
Mike Stump1eb44332009-09-09 15:08:12 +00003030
John McCallf1860e52010-05-20 23:23:51 +00003031 // Fields.
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003032 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
3033 MemEnd = ClassDecl->decls_end();
3034 Mem != MemEnd; ++Mem) {
3035 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
Douglas Gregord61db332011-10-10 17:22:13 +00003036 // C++ [class.bit]p2:
3037 // A declaration for a bit-field that omits the identifier declares an
3038 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
3039 // initialized.
3040 if (F->isUnnamedBitfield())
3041 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003042
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003043 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003044 // handle anonymous struct/union fields based on their individual
3045 // indirect fields.
3046 if (F->isAnonymousStructOrUnion() && Info.IIK == IIK_Default)
3047 continue;
3048
3049 if (CollectFieldInitializer(*this, Info, F))
3050 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003051 continue;
3052 }
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003053
3054 // Beyond this point, we only consider default initialization.
3055 if (Info.IIK != IIK_Default)
3056 continue;
3057
3058 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
3059 if (F->getType()->isIncompleteArrayType()) {
3060 assert(ClassDecl->hasFlexibleArrayMember() &&
3061 "Incomplete array type is not valid");
3062 continue;
3063 }
3064
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003065 // Initialize each field of an anonymous struct individually.
3066 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3067 HadError = true;
3068
3069 continue;
3070 }
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003071 }
Mike Stump1eb44332009-09-09 15:08:12 +00003072
John McCallf1860e52010-05-20 23:23:51 +00003073 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003074 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00003075 Constructor->setNumCtorInitializers(NumInitializers);
3076 CXXCtorInitializer **baseOrMemberInitializers =
3077 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00003078 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00003079 NumInitializers * sizeof(CXXCtorInitializer*));
3080 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00003081
John McCallef027fe2010-03-16 21:39:52 +00003082 // Constructors implicitly reference the base and member
3083 // destructors.
3084 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3085 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003086 }
Eli Friedman80c30da2009-11-09 19:20:36 +00003087
3088 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003089}
3090
Eli Friedman6347f422009-07-21 19:28:10 +00003091static void *GetKeyForTopLevelField(FieldDecl *Field) {
3092 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00003093 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00003094 if (RT->getDecl()->isAnonymousStructOrUnion())
3095 return static_cast<void *>(RT->getDecl());
3096 }
3097 return static_cast<void *>(Field);
3098}
3099
Anders Carlssonea356fb2010-04-02 05:42:15 +00003100static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCallf4c73712011-01-19 06:33:43 +00003101 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssoncdc83c72009-09-01 06:22:14 +00003102}
3103
Anders Carlssonea356fb2010-04-02 05:42:15 +00003104static void *GetKeyForMember(ASTContext &Context,
Sean Huntcbb67482011-01-08 20:30:50 +00003105 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003106 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00003107 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00003108
Eli Friedman6347f422009-07-21 19:28:10 +00003109 // For fields injected into the class via declaration of an anonymous union,
3110 // use its anonymous union class declaration as the unique key.
Francois Pichet00eb3f92010-12-04 09:14:42 +00003111 FieldDecl *Field = Member->getAnyMember();
3112
John McCall3c3ccdb2010-04-10 09:28:51 +00003113 // If the field is a member of an anonymous struct or union, our key
3114 // is the anonymous record decl that's a direct child of the class.
Anders Carlssonee11b2d2010-03-30 16:19:37 +00003115 RecordDecl *RD = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003116 if (RD->isAnonymousStructOrUnion()) {
3117 while (true) {
3118 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
3119 if (Parent->isAnonymousStructOrUnion())
3120 RD = Parent;
3121 else
3122 break;
3123 }
3124
Anders Carlssonee11b2d2010-03-30 16:19:37 +00003125 return static_cast<void *>(RD);
John McCall3c3ccdb2010-04-10 09:28:51 +00003126 }
Mike Stump1eb44332009-09-09 15:08:12 +00003127
Anders Carlsson8f1a2402010-03-30 15:39:27 +00003128 return static_cast<void *>(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00003129}
3130
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003131static void
3132DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson071d6102010-04-02 03:38:04 +00003133 const CXXConstructorDecl *Constructor,
Sean Huntcbb67482011-01-08 20:30:50 +00003134 CXXCtorInitializer **Inits,
John McCalld6ca8da2010-04-10 07:37:23 +00003135 unsigned NumInits) {
3136 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00003137 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003138
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003139 // Don't check initializers order unless the warning is enabled at the
3140 // location of at least one initializer.
3141 bool ShouldCheckOrder = false;
3142 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003143 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003144 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3145 Init->getSourceLocation())
David Blaikied6471f72011-09-25 23:23:43 +00003146 != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003147 ShouldCheckOrder = true;
3148 break;
3149 }
3150 }
3151 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003152 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003153
John McCalld6ca8da2010-04-10 07:37:23 +00003154 // Build the list of bases and members in the order that they'll
3155 // actually be initialized. The explicit initializers should be in
3156 // this same order but may be missing things.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003157 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00003158
Anders Carlsson071d6102010-04-02 03:38:04 +00003159 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3160
John McCalld6ca8da2010-04-10 07:37:23 +00003161 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003162 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003163 ClassDecl->vbases_begin(),
3164 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00003165 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003166
John McCalld6ca8da2010-04-10 07:37:23 +00003167 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003168 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003169 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003170 if (Base->isVirtual())
3171 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00003172 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003173 }
Mike Stump1eb44332009-09-09 15:08:12 +00003174
John McCalld6ca8da2010-04-10 07:37:23 +00003175 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003176 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Douglas Gregord61db332011-10-10 17:22:13 +00003177 E = ClassDecl->field_end(); Field != E; ++Field) {
3178 if (Field->isUnnamedBitfield())
3179 continue;
3180
David Blaikie581deb32012-06-06 20:45:41 +00003181 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Douglas Gregord61db332011-10-10 17:22:13 +00003182 }
3183
John McCalld6ca8da2010-04-10 07:37:23 +00003184 unsigned NumIdealInits = IdealInitKeys.size();
3185 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00003186
Sean Huntcbb67482011-01-08 20:30:50 +00003187 CXXCtorInitializer *PrevInit = 0;
John McCalld6ca8da2010-04-10 07:37:23 +00003188 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003189 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichet00eb3f92010-12-04 09:14:42 +00003190 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00003191
3192 // Scan forward to try to find this initializer in the idealized
3193 // initializers list.
3194 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3195 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003196 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003197
3198 // If we didn't find this initializer, it must be because we
3199 // scanned past it on a previous iteration. That can only
3200 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00003201 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00003202 Sema::SemaDiagnosticBuilder D =
3203 SemaRef.Diag(PrevInit->getSourceLocation(),
3204 diag::warn_initializer_out_of_order);
3205
Francois Pichet00eb3f92010-12-04 09:14:42 +00003206 if (PrevInit->isAnyMemberInitializer())
3207 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003208 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003209 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003210
Francois Pichet00eb3f92010-12-04 09:14:42 +00003211 if (Init->isAnyMemberInitializer())
3212 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003213 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003214 D << 1 << Init->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003215
3216 // Move back to the initializer's location in the ideal list.
3217 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3218 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003219 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003220
3221 assert(IdealIndex != NumIdealInits &&
3222 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003223 }
John McCalld6ca8da2010-04-10 07:37:23 +00003224
3225 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003226 }
Anders Carlssona7b35212009-03-25 02:58:17 +00003227}
3228
John McCall3c3ccdb2010-04-10 09:28:51 +00003229namespace {
3230bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003231 CXXCtorInitializer *Init,
3232 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003233 if (!PrevInit) {
3234 PrevInit = Init;
3235 return false;
3236 }
3237
3238 if (FieldDecl *Field = Init->getMember())
3239 S.Diag(Init->getSourceLocation(),
3240 diag::err_multiple_mem_initialization)
3241 << Field->getDeclName()
3242 << Init->getSourceRange();
3243 else {
John McCallf4c73712011-01-19 06:33:43 +00003244 const Type *BaseClass = Init->getBaseClass();
John McCall3c3ccdb2010-04-10 09:28:51 +00003245 assert(BaseClass && "neither field nor base");
3246 S.Diag(Init->getSourceLocation(),
3247 diag::err_multiple_base_initialization)
3248 << QualType(BaseClass, 0)
3249 << Init->getSourceRange();
3250 }
3251 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3252 << 0 << PrevInit->getSourceRange();
3253
3254 return true;
3255}
3256
Sean Huntcbb67482011-01-08 20:30:50 +00003257typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00003258typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3259
3260bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003261 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00003262 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003263 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003264 RecordDecl *Parent = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003265 NamedDecl *Child = Field;
David Blaikie6fe29652011-11-17 06:01:57 +00003266
3267 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003268 if (Parent->isUnion()) {
3269 UnionEntry &En = Unions[Parent];
3270 if (En.first && En.first != Child) {
3271 S.Diag(Init->getSourceLocation(),
3272 diag::err_multiple_mem_union_initialization)
3273 << Field->getDeclName()
3274 << Init->getSourceRange();
3275 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3276 << 0 << En.second->getSourceRange();
3277 return true;
David Blaikie5bbe8162011-11-12 20:54:14 +00003278 }
3279 if (!En.first) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003280 En.first = Child;
3281 En.second = Init;
3282 }
David Blaikie6fe29652011-11-17 06:01:57 +00003283 if (!Parent->isAnonymousStructOrUnion())
3284 return false;
John McCall3c3ccdb2010-04-10 09:28:51 +00003285 }
3286
3287 Child = Parent;
3288 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie6fe29652011-11-17 06:01:57 +00003289 }
John McCall3c3ccdb2010-04-10 09:28:51 +00003290
3291 return false;
3292}
3293}
3294
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003295/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00003296void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003297 SourceLocation ColonLoc,
Richard Trieu90ab75b2011-09-09 03:18:59 +00003298 CXXCtorInitializer **meminits,
3299 unsigned NumMemInits,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003300 bool AnyErrors) {
3301 if (!ConstructorDecl)
3302 return;
3303
3304 AdjustDeclIfTemplate(ConstructorDecl);
3305
3306 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003307 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003308
3309 if (!Constructor) {
3310 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3311 return;
3312 }
3313
Sean Huntcbb67482011-01-08 20:30:50 +00003314 CXXCtorInitializer **MemInits =
3315 reinterpret_cast<CXXCtorInitializer **>(meminits);
John McCall3c3ccdb2010-04-10 09:28:51 +00003316
3317 // Mapping for the duplicate initializers check.
3318 // For member initializers, this is keyed with a FieldDecl*.
3319 // For base initializers, this is keyed with a Type*.
Sean Huntcbb67482011-01-08 20:30:50 +00003320 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00003321
3322 // Mapping for the inconsistent anonymous-union initializers check.
3323 RedundantUnionMap MemberUnions;
3324
Anders Carlssonea356fb2010-04-02 05:42:15 +00003325 bool HadError = false;
3326 for (unsigned i = 0; i < NumMemInits; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003327 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003328
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00003329 // Set the source order index.
3330 Init->setSourceOrder(i);
3331
Francois Pichet00eb3f92010-12-04 09:14:42 +00003332 if (Init->isAnyMemberInitializer()) {
3333 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003334 if (CheckRedundantInit(*this, Init, Members[Field]) ||
3335 CheckRedundantUnionInit(*this, Init, MemberUnions))
3336 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003337 } else if (Init->isBaseInitializer()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003338 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
3339 if (CheckRedundantInit(*this, Init, Members[Key]))
3340 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003341 } else {
3342 assert(Init->isDelegatingInitializer());
3343 // This must be the only initializer
3344 if (i != 0 || NumMemInits > 1) {
3345 Diag(MemInits[0]->getSourceLocation(),
3346 diag::err_delegating_initializer_alone)
3347 << MemInits[0]->getSourceRange();
3348 HadError = true;
Sean Hunt059ce0d2011-05-01 07:04:31 +00003349 // We will treat this as being the only initializer.
Sean Hunt41717662011-02-26 19:13:13 +00003350 }
Sean Huntfe57eef2011-05-04 05:57:24 +00003351 SetDelegatingInitializer(Constructor, MemInits[i]);
Sean Hunt059ce0d2011-05-01 07:04:31 +00003352 // Return immediately as the initializer is set.
3353 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003354 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003355 }
3356
Anders Carlssonea356fb2010-04-02 05:42:15 +00003357 if (HadError)
3358 return;
3359
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003360 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00003361
Sean Huntcbb67482011-01-08 20:30:50 +00003362 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003363}
3364
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003365void
John McCallef027fe2010-03-16 21:39:52 +00003366Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3367 CXXRecordDecl *ClassDecl) {
Richard Smith416f63e2011-09-18 12:11:43 +00003368 // Ignore dependent contexts. Also ignore unions, since their members never
3369 // have destructors implicitly called.
3370 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003371 return;
John McCall58e6f342010-03-16 05:22:47 +00003372
3373 // FIXME: all the access-control diagnostics are positioned on the
3374 // field/base declaration. That's probably good; that said, the
3375 // user might reasonably want to know why the destructor is being
3376 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003377
Anders Carlsson9f853df2009-11-17 04:44:12 +00003378 // Non-static data members.
3379 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3380 E = ClassDecl->field_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00003381 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00003382 if (Field->isInvalidDecl())
3383 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003384
3385 // Don't destroy incomplete or zero-length arrays.
3386 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3387 continue;
3388
Anders Carlsson9f853df2009-11-17 04:44:12 +00003389 QualType FieldType = Context.getBaseElementType(Field->getType());
3390
3391 const RecordType* RT = FieldType->getAs<RecordType>();
3392 if (!RT)
3393 continue;
3394
3395 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003396 if (FieldClassDecl->isInvalidDecl())
3397 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003398 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003399 continue;
Richard Smith9a561d52012-02-26 09:11:52 +00003400 // The destructor for an implicit anonymous union member is never invoked.
3401 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3402 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00003403
Douglas Gregordb89f282010-07-01 22:47:18 +00003404 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003405 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003406 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003407 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00003408 << Field->getDeclName()
3409 << FieldType);
3410
Eli Friedman5f2987c2012-02-02 03:46:19 +00003411 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003412 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003413 }
3414
John McCall58e6f342010-03-16 05:22:47 +00003415 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3416
Anders Carlsson9f853df2009-11-17 04:44:12 +00003417 // Bases.
3418 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3419 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00003420 // Bases are always records in a well-formed non-dependent class.
3421 const RecordType *RT = Base->getType()->getAs<RecordType>();
3422
3423 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003424 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00003425 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003426
John McCall58e6f342010-03-16 05:22:47 +00003427 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003428 // If our base class is invalid, we probably can't get its dtor anyway.
3429 if (BaseClassDecl->isInvalidDecl())
3430 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003431 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003432 continue;
John McCall58e6f342010-03-16 05:22:47 +00003433
Douglas Gregordb89f282010-07-01 22:47:18 +00003434 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003435 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003436
3437 // FIXME: caret should be on the start of the class name
Daniel Dunbar96a00142012-03-09 18:35:03 +00003438 CheckDestructorAccess(Base->getLocStart(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003439 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00003440 << Base->getType()
John McCallb9abd8722012-04-07 03:04:20 +00003441 << Base->getSourceRange(),
3442 Context.getTypeDeclType(ClassDecl));
Anders Carlsson9f853df2009-11-17 04:44:12 +00003443
Eli Friedman5f2987c2012-02-02 03:46:19 +00003444 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003445 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003446 }
3447
3448 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003449 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3450 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00003451
3452 // Bases are always records in a well-formed non-dependent class.
John McCall63f55782012-04-09 21:51:56 +00003453 const RecordType *RT = VBase->getType()->castAs<RecordType>();
John McCall58e6f342010-03-16 05:22:47 +00003454
3455 // Ignore direct virtual bases.
3456 if (DirectVirtualBases.count(RT))
3457 continue;
3458
John McCall58e6f342010-03-16 05:22:47 +00003459 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003460 // If our base class is invalid, we probably can't get its dtor anyway.
3461 if (BaseClassDecl->isInvalidDecl())
3462 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003463 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003464 continue;
John McCall58e6f342010-03-16 05:22:47 +00003465
Douglas Gregordb89f282010-07-01 22:47:18 +00003466 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003467 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003468 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003469 PDiag(diag::err_access_dtor_vbase)
John McCall63f55782012-04-09 21:51:56 +00003470 << VBase->getType(),
3471 Context.getTypeDeclType(ClassDecl));
John McCall58e6f342010-03-16 05:22:47 +00003472
Eli Friedman5f2987c2012-02-02 03:46:19 +00003473 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003474 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003475 }
3476}
3477
John McCalld226f652010-08-21 09:40:31 +00003478void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00003479 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003480 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003481
Mike Stump1eb44332009-09-09 15:08:12 +00003482 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003483 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Sean Huntcbb67482011-01-08 20:30:50 +00003484 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003485}
3486
Mike Stump1eb44332009-09-09 15:08:12 +00003487bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00003488 unsigned DiagID, AbstractDiagSelID SelID) {
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003489 class NonAbstractTypeDiagnoser : public TypeDiagnoser {
3490 unsigned DiagID;
3491 AbstractDiagSelID SelID;
3492
3493 public:
3494 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
3495 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
3496
3497 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
Eli Friedman2217f852012-08-14 02:06:07 +00003498 if (Suppressed) return;
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003499 if (SelID == -1)
3500 S.Diag(Loc, DiagID) << T;
3501 else
3502 S.Diag(Loc, DiagID) << SelID << T;
3503 }
3504 } Diagnoser(DiagID, SelID);
3505
3506 return RequireNonAbstractType(Loc, T, Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00003507}
3508
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003509bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003510 TypeDiagnoser &Diagnoser) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003511 if (!getLangOpts().CPlusPlus)
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003512 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003513
Anders Carlsson11f21a02009-03-23 19:10:31 +00003514 if (const ArrayType *AT = Context.getAsArrayType(T))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003515 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00003516
Ted Kremenek6217b802009-07-29 21:53:49 +00003517 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003518 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00003519 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003520 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00003521
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003522 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003523 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003524 }
Mike Stump1eb44332009-09-09 15:08:12 +00003525
Ted Kremenek6217b802009-07-29 21:53:49 +00003526 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003527 if (!RT)
3528 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003529
John McCall86ff3082010-02-04 22:26:26 +00003530 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003531
John McCall94c3b562010-08-18 09:41:07 +00003532 // We can't answer whether something is abstract until it has a
3533 // definition. If it's currently being defined, we'll walk back
3534 // over all the declarations when we have a full definition.
3535 const CXXRecordDecl *Def = RD->getDefinition();
3536 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00003537 return false;
3538
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003539 if (!RD->isAbstract())
3540 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003541
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003542 Diagnoser.diagnose(*this, Loc, T);
John McCall94c3b562010-08-18 09:41:07 +00003543 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00003544
John McCall94c3b562010-08-18 09:41:07 +00003545 return true;
3546}
3547
3548void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
3549 // Check if we've already emitted the list of pure virtual functions
3550 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003551 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00003552 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003553
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003554 CXXFinalOverriderMap FinalOverriders;
3555 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00003556
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003557 // Keep a set of seen pure methods so we won't diagnose the same method
3558 // more than once.
3559 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
3560
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003561 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
3562 MEnd = FinalOverriders.end();
3563 M != MEnd;
3564 ++M) {
3565 for (OverridingMethods::iterator SO = M->second.begin(),
3566 SOEnd = M->second.end();
3567 SO != SOEnd; ++SO) {
3568 // C++ [class.abstract]p4:
3569 // A class is abstract if it contains or inherits at least one
3570 // pure virtual function for which the final overrider is pure
3571 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00003572
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003573 //
3574 if (SO->second.size() != 1)
3575 continue;
3576
3577 if (!SO->second.front().Method->isPure())
3578 continue;
3579
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003580 if (!SeenPureMethods.insert(SO->second.front().Method))
3581 continue;
3582
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003583 Diag(SO->second.front().Method->getLocation(),
3584 diag::note_pure_virtual_function)
Chandler Carruth45f11b72011-02-18 23:59:51 +00003585 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003586 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003587 }
3588
3589 if (!PureVirtualClassDiagSet)
3590 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
3591 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003592}
3593
Anders Carlsson8211eff2009-03-24 01:19:16 +00003594namespace {
John McCall94c3b562010-08-18 09:41:07 +00003595struct AbstractUsageInfo {
3596 Sema &S;
3597 CXXRecordDecl *Record;
3598 CanQualType AbstractType;
3599 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00003600
John McCall94c3b562010-08-18 09:41:07 +00003601 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
3602 : S(S), Record(Record),
3603 AbstractType(S.Context.getCanonicalType(
3604 S.Context.getTypeDeclType(Record))),
3605 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00003606
John McCall94c3b562010-08-18 09:41:07 +00003607 void DiagnoseAbstractType() {
3608 if (Invalid) return;
3609 S.DiagnoseAbstractType(Record);
3610 Invalid = true;
3611 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00003612
John McCall94c3b562010-08-18 09:41:07 +00003613 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
3614};
3615
3616struct CheckAbstractUsage {
3617 AbstractUsageInfo &Info;
3618 const NamedDecl *Ctx;
3619
3620 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
3621 : Info(Info), Ctx(Ctx) {}
3622
3623 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3624 switch (TL.getTypeLocClass()) {
3625#define ABSTRACT_TYPELOC(CLASS, PARENT)
3626#define TYPELOC(CLASS, PARENT) \
3627 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
3628#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00003629 }
John McCall94c3b562010-08-18 09:41:07 +00003630 }
Mike Stump1eb44332009-09-09 15:08:12 +00003631
John McCall94c3b562010-08-18 09:41:07 +00003632 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3633 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
3634 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor70191862011-02-22 23:21:06 +00003635 if (!TL.getArg(I))
3636 continue;
3637
John McCall94c3b562010-08-18 09:41:07 +00003638 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
3639 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003640 }
John McCall94c3b562010-08-18 09:41:07 +00003641 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003642
John McCall94c3b562010-08-18 09:41:07 +00003643 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3644 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
3645 }
Mike Stump1eb44332009-09-09 15:08:12 +00003646
John McCall94c3b562010-08-18 09:41:07 +00003647 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3648 // Visit the type parameters from a permissive context.
3649 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3650 TemplateArgumentLoc TAL = TL.getArgLoc(I);
3651 if (TAL.getArgument().getKind() == TemplateArgument::Type)
3652 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
3653 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
3654 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00003655 }
John McCall94c3b562010-08-18 09:41:07 +00003656 }
Mike Stump1eb44332009-09-09 15:08:12 +00003657
John McCall94c3b562010-08-18 09:41:07 +00003658 // Visit pointee types from a permissive context.
3659#define CheckPolymorphic(Type) \
3660 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
3661 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
3662 }
3663 CheckPolymorphic(PointerTypeLoc)
3664 CheckPolymorphic(ReferenceTypeLoc)
3665 CheckPolymorphic(MemberPointerTypeLoc)
3666 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedmanb001de72011-10-06 23:00:33 +00003667 CheckPolymorphic(AtomicTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00003668
John McCall94c3b562010-08-18 09:41:07 +00003669 /// Handle all the types we haven't given a more specific
3670 /// implementation for above.
3671 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3672 // Every other kind of type that we haven't called out already
3673 // that has an inner type is either (1) sugar or (2) contains that
3674 // inner type in some way as a subobject.
3675 if (TypeLoc Next = TL.getNextTypeLoc())
3676 return Visit(Next, Sel);
3677
3678 // If there's no inner type and we're in a permissive context,
3679 // don't diagnose.
3680 if (Sel == Sema::AbstractNone) return;
3681
3682 // Check whether the type matches the abstract type.
3683 QualType T = TL.getType();
3684 if (T->isArrayType()) {
3685 Sel = Sema::AbstractArrayType;
3686 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003687 }
John McCall94c3b562010-08-18 09:41:07 +00003688 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
3689 if (CT != Info.AbstractType) return;
3690
3691 // It matched; do some magic.
3692 if (Sel == Sema::AbstractArrayType) {
3693 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
3694 << T << TL.getSourceRange();
3695 } else {
3696 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
3697 << Sel << T << TL.getSourceRange();
3698 }
3699 Info.DiagnoseAbstractType();
3700 }
3701};
3702
3703void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
3704 Sema::AbstractDiagSelID Sel) {
3705 CheckAbstractUsage(*this, D).Visit(TL, Sel);
3706}
3707
3708}
3709
3710/// Check for invalid uses of an abstract type in a method declaration.
3711static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3712 CXXMethodDecl *MD) {
3713 // No need to do the check on definitions, which require that
3714 // the return/param types be complete.
Sean Hunt10620eb2011-05-06 20:44:56 +00003715 if (MD->doesThisDeclarationHaveABody())
John McCall94c3b562010-08-18 09:41:07 +00003716 return;
3717
3718 // For safety's sake, just ignore it if we don't have type source
3719 // information. This should never happen for non-implicit methods,
3720 // but...
3721 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
3722 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
3723}
3724
3725/// Check for invalid uses of an abstract type within a class definition.
3726static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3727 CXXRecordDecl *RD) {
3728 for (CXXRecordDecl::decl_iterator
3729 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
3730 Decl *D = *I;
3731 if (D->isImplicit()) continue;
3732
3733 // Methods and method templates.
3734 if (isa<CXXMethodDecl>(D)) {
3735 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
3736 } else if (isa<FunctionTemplateDecl>(D)) {
3737 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
3738 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
3739
3740 // Fields and static variables.
3741 } else if (isa<FieldDecl>(D)) {
3742 FieldDecl *FD = cast<FieldDecl>(D);
3743 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
3744 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
3745 } else if (isa<VarDecl>(D)) {
3746 VarDecl *VD = cast<VarDecl>(D);
3747 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
3748 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
3749
3750 // Nested classes and class templates.
3751 } else if (isa<CXXRecordDecl>(D)) {
3752 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
3753 } else if (isa<ClassTemplateDecl>(D)) {
3754 CheckAbstractClassUsage(Info,
3755 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
3756 }
3757 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003758}
3759
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003760/// \brief Perform semantic checks on a class definition that has been
3761/// completing, introducing implicitly-declared members, checking for
3762/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00003763void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00003764 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003765 return;
3766
John McCall94c3b562010-08-18 09:41:07 +00003767 if (Record->isAbstract() && !Record->isInvalidDecl()) {
3768 AbstractUsageInfo Info(*this, Record);
3769 CheckAbstractClassUsage(Info, Record);
3770 }
Douglas Gregor325e5932010-04-15 00:00:53 +00003771
3772 // If this is not an aggregate type and has no user-declared constructor,
3773 // complain about any non-static data members of reference or const scalar
3774 // type, since they will never get initializers.
3775 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregor5e058eb2012-02-09 02:20:38 +00003776 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
3777 !Record->isLambda()) {
Douglas Gregor325e5932010-04-15 00:00:53 +00003778 bool Complained = false;
3779 for (RecordDecl::field_iterator F = Record->field_begin(),
3780 FEnd = Record->field_end();
3781 F != FEnd; ++F) {
Douglas Gregord61db332011-10-10 17:22:13 +00003782 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith7a614d82011-06-11 17:19:42 +00003783 continue;
3784
Douglas Gregor325e5932010-04-15 00:00:53 +00003785 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00003786 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00003787 if (!Complained) {
3788 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
3789 << Record->getTagKind() << Record;
3790 Complained = true;
3791 }
3792
3793 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
3794 << F->getType()->isReferenceType()
3795 << F->getDeclName();
3796 }
3797 }
3798 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003799
Anders Carlssona5c6c2a2011-01-25 18:08:22 +00003800 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003801 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00003802
3803 if (Record->getIdentifier()) {
3804 // C++ [class.mem]p13:
3805 // If T is the name of a class, then each of the following shall have a
3806 // name different from T:
3807 // - every member of every anonymous union that is a member of class T.
3808 //
3809 // C++ [class.mem]p14:
3810 // In addition, if class T has a user-declared constructor (12.1), every
3811 // non-static data member of class T shall have a name different from T.
3812 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
Francois Pichet87c2e122010-11-21 06:08:52 +00003813 R.first != R.second; ++R.first) {
3814 NamedDecl *D = *R.first;
3815 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
3816 isa<IndirectFieldDecl>(D)) {
3817 Diag(D->getLocation(), diag::err_member_name_of_class)
3818 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00003819 break;
3820 }
Francois Pichet87c2e122010-11-21 06:08:52 +00003821 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00003822 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003823
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003824 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregorf4b793c2011-02-19 19:14:36 +00003825 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003826 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003827 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003828 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
3829 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
3830 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003831
3832 // See if a method overloads virtual methods in a base
3833 /// class without overriding any.
3834 if (!Record->isDependentType()) {
3835 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3836 MEnd = Record->method_end();
3837 M != MEnd; ++M) {
David Blaikie262bc182012-04-30 02:36:29 +00003838 if (!M->isStatic())
David Blaikie581deb32012-06-06 20:45:41 +00003839 DiagnoseHiddenVirtualMethods(Record, *M);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003840 }
3841 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00003842
Richard Smith9f569cc2011-10-01 02:31:28 +00003843 // C++0x [dcl.constexpr]p8: A constexpr specifier for a non-static member
3844 // function that is not a constructor declares that member function to be
3845 // const. [...] The class of which that function is a member shall be
3846 // a literal type.
3847 //
Richard Smith9f569cc2011-10-01 02:31:28 +00003848 // If the class has virtual bases, any constexpr members will already have
3849 // been diagnosed by the checks performed on the member declaration, so
3850 // suppress this (less useful) diagnostic.
3851 if (LangOpts.CPlusPlus0x && !Record->isDependentType() &&
3852 !Record->isLiteral() && !Record->getNumVBases()) {
3853 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3854 MEnd = Record->method_end();
3855 M != MEnd; ++M) {
Richard Smith86c3ae42012-02-13 03:54:03 +00003856 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) {
Richard Smith9f569cc2011-10-01 02:31:28 +00003857 switch (Record->getTemplateSpecializationKind()) {
3858 case TSK_ImplicitInstantiation:
3859 case TSK_ExplicitInstantiationDeclaration:
3860 case TSK_ExplicitInstantiationDefinition:
3861 // If a template instantiates to a non-literal type, but its members
3862 // instantiate to constexpr functions, the template is technically
Richard Smith86c3ae42012-02-13 03:54:03 +00003863 // ill-formed, but we allow it for sanity.
Richard Smith9f569cc2011-10-01 02:31:28 +00003864 continue;
3865
3866 case TSK_Undeclared:
3867 case TSK_ExplicitSpecialization:
David Blaikie262bc182012-04-30 02:36:29 +00003868 RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
Douglas Gregorf502d8e2012-05-04 16:48:41 +00003869 diag::err_constexpr_method_non_literal);
Richard Smith9f569cc2011-10-01 02:31:28 +00003870 break;
3871 }
3872
3873 // Only produce one error per class.
3874 break;
3875 }
3876 }
3877 }
3878
Sebastian Redlf677ea32011-02-05 19:23:19 +00003879 // Declare inherited constructors. We do this eagerly here because:
3880 // - The standard requires an eager diagnostic for conflicting inherited
3881 // constructors from different classes.
3882 // - The lazy declaration of the other implicit constructors is so as to not
3883 // waste space and performance on classes that are not meant to be
3884 // instantiated (e.g. meta-functions). This doesn't apply to classes that
3885 // have inherited constructors.
Sebastian Redlcaa35e42011-03-12 13:44:32 +00003886 DeclareInheritedConstructors(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00003887}
3888
3889void Sema::CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00003890 for (CXXRecordDecl::method_iterator MI = Record->method_begin(),
3891 ME = Record->method_end();
Richard Smith3003e1d2012-05-15 04:39:51 +00003892 MI != ME; ++MI)
3893 if (!MI->isInvalidDecl() && MI->isExplicitlyDefaulted())
David Blaikie581deb32012-06-06 20:45:41 +00003894 CheckExplicitlyDefaultedSpecialMember(*MI);
Sean Hunt001cad92011-05-10 00:49:42 +00003895}
3896
Richard Smith7756afa2012-06-10 05:43:50 +00003897/// Is the special member function which would be selected to perform the
3898/// specified operation on the specified class type a constexpr constructor?
3899static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
3900 Sema::CXXSpecialMember CSM,
3901 bool ConstArg) {
3902 Sema::SpecialMemberOverloadResult *SMOR =
3903 S.LookupSpecialMember(ClassDecl, CSM, ConstArg,
3904 false, false, false, false);
3905 if (!SMOR || !SMOR->getMethod())
3906 // A constructor we wouldn't select can't be "involved in initializing"
3907 // anything.
3908 return true;
3909 return SMOR->getMethod()->isConstexpr();
3910}
3911
3912/// Determine whether the specified special member function would be constexpr
3913/// if it were implicitly defined.
3914static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
3915 Sema::CXXSpecialMember CSM,
3916 bool ConstArg) {
3917 if (!S.getLangOpts().CPlusPlus0x)
3918 return false;
3919
3920 // C++11 [dcl.constexpr]p4:
3921 // In the definition of a constexpr constructor [...]
3922 switch (CSM) {
3923 case Sema::CXXDefaultConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00003924 // Since default constructor lookup is essentially trivial (and cannot
3925 // involve, for instance, template instantiation), we compute whether a
3926 // defaulted default constructor is constexpr directly within CXXRecordDecl.
3927 //
3928 // This is important for performance; we need to know whether the default
3929 // constructor is constexpr to determine whether the type is a literal type.
3930 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
3931
Richard Smith7756afa2012-06-10 05:43:50 +00003932 case Sema::CXXCopyConstructor:
3933 case Sema::CXXMoveConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00003934 // For copy or move constructors, we need to perform overload resolution.
Richard Smith7756afa2012-06-10 05:43:50 +00003935 break;
3936
3937 case Sema::CXXCopyAssignment:
3938 case Sema::CXXMoveAssignment:
3939 case Sema::CXXDestructor:
3940 case Sema::CXXInvalid:
3941 return false;
3942 }
3943
3944 // -- if the class is a non-empty union, or for each non-empty anonymous
3945 // union member of a non-union class, exactly one non-static data member
3946 // shall be initialized; [DR1359]
Richard Smithd3861ce2012-06-10 07:07:24 +00003947 //
3948 // If we squint, this is guaranteed, since exactly one non-static data member
3949 // will be initialized (if the constructor isn't deleted), we just don't know
3950 // which one.
Richard Smith7756afa2012-06-10 05:43:50 +00003951 if (ClassDecl->isUnion())
Richard Smithd3861ce2012-06-10 07:07:24 +00003952 return true;
Richard Smith7756afa2012-06-10 05:43:50 +00003953
3954 // -- the class shall not have any virtual base classes;
3955 if (ClassDecl->getNumVBases())
3956 return false;
3957
3958 // -- every constructor involved in initializing [...] base class
3959 // sub-objects shall be a constexpr constructor;
3960 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
3961 BEnd = ClassDecl->bases_end();
3962 B != BEnd; ++B) {
3963 const RecordType *BaseType = B->getType()->getAs<RecordType>();
3964 if (!BaseType) continue;
3965
3966 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
3967 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, ConstArg))
3968 return false;
3969 }
3970
3971 // -- every constructor involved in initializing non-static data members
3972 // [...] shall be a constexpr constructor;
3973 // -- every non-static data member and base class sub-object shall be
3974 // initialized
3975 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
3976 FEnd = ClassDecl->field_end();
3977 F != FEnd; ++F) {
3978 if (F->isInvalidDecl())
3979 continue;
Richard Smithd3861ce2012-06-10 07:07:24 +00003980 if (const RecordType *RecordTy =
3981 S.Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Richard Smith7756afa2012-06-10 05:43:50 +00003982 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
3983 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, ConstArg))
3984 return false;
Richard Smith7756afa2012-06-10 05:43:50 +00003985 }
3986 }
3987
3988 // All OK, it's constexpr!
3989 return true;
3990}
3991
Richard Smithb9d0b762012-07-27 04:22:15 +00003992static Sema::ImplicitExceptionSpecification
3993computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
3994 switch (S.getSpecialMember(MD)) {
3995 case Sema::CXXDefaultConstructor:
3996 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
3997 case Sema::CXXCopyConstructor:
3998 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
3999 case Sema::CXXCopyAssignment:
4000 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4001 case Sema::CXXMoveConstructor:
4002 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
4003 case Sema::CXXMoveAssignment:
4004 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
4005 case Sema::CXXDestructor:
4006 return S.ComputeDefaultedDtorExceptionSpec(MD);
4007 case Sema::CXXInvalid:
4008 break;
4009 }
4010 llvm_unreachable("only special members have implicit exception specs");
4011}
4012
Richard Smithdd25e802012-07-30 23:48:14 +00004013static void
4014updateExceptionSpec(Sema &S, FunctionDecl *FD, const FunctionProtoType *FPT,
4015 const Sema::ImplicitExceptionSpecification &ExceptSpec) {
4016 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
4017 ExceptSpec.getEPI(EPI);
4018 const FunctionProtoType *NewFPT = cast<FunctionProtoType>(
4019 S.Context.getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
4020 FPT->getNumArgs(), EPI));
4021 FD->setType(QualType(NewFPT, 0));
4022}
4023
Richard Smithb9d0b762012-07-27 04:22:15 +00004024void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4025 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4026 if (FPT->getExceptionSpecType() != EST_Unevaluated)
4027 return;
4028
Richard Smithdd25e802012-07-30 23:48:14 +00004029 // Evaluate the exception specification.
4030 ImplicitExceptionSpecification ExceptSpec =
4031 computeImplicitExceptionSpec(*this, Loc, MD);
4032
4033 // Update the type of the special member to use it.
4034 updateExceptionSpec(*this, MD, FPT, ExceptSpec);
4035
4036 // A user-provided destructor can be defined outside the class. When that
4037 // happens, be sure to update the exception specification on both
4038 // declarations.
4039 const FunctionProtoType *CanonicalFPT =
4040 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4041 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
4042 updateExceptionSpec(*this, MD->getCanonicalDecl(),
4043 CanonicalFPT, ExceptSpec);
Richard Smithb9d0b762012-07-27 04:22:15 +00004044}
4045
4046static bool isImplicitCopyCtorArgConst(Sema &S, CXXRecordDecl *ClassDecl);
4047static bool isImplicitCopyAssignmentArgConst(Sema &S, CXXRecordDecl *ClassDecl);
4048
Richard Smith3003e1d2012-05-15 04:39:51 +00004049void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4050 CXXRecordDecl *RD = MD->getParent();
4051 CXXSpecialMember CSM = getSpecialMember(MD);
Sean Hunt001cad92011-05-10 00:49:42 +00004052
Richard Smith3003e1d2012-05-15 04:39:51 +00004053 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4054 "not an explicitly-defaulted special member");
Sean Hunt49634cf2011-05-13 06:10:58 +00004055
4056 // Whether this was the first-declared instance of the constructor.
Richard Smith3003e1d2012-05-15 04:39:51 +00004057 // This affects whether we implicitly add an exception spec and constexpr.
Sean Hunt2b188082011-05-14 05:23:28 +00004058 bool First = MD == MD->getCanonicalDecl();
4059
4060 bool HadError = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004061
4062 // C++11 [dcl.fct.def.default]p1:
4063 // A function that is explicitly defaulted shall
4064 // -- be a special member function (checked elsewhere),
4065 // -- have the same type (except for ref-qualifiers, and except that a
4066 // copy operation can take a non-const reference) as an implicit
4067 // declaration, and
4068 // -- not have default arguments.
4069 unsigned ExpectedParams = 1;
4070 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4071 ExpectedParams = 0;
4072 if (MD->getNumParams() != ExpectedParams) {
4073 // This also checks for default arguments: a copy or move constructor with a
4074 // default argument is classified as a default constructor, and assignment
4075 // operations and destructors can't have default arguments.
4076 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4077 << CSM << MD->getSourceRange();
Sean Hunt2b188082011-05-14 05:23:28 +00004078 HadError = true;
4079 }
4080
Richard Smith3003e1d2012-05-15 04:39:51 +00004081 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
Sean Hunt2b188082011-05-14 05:23:28 +00004082
Richard Smithb9d0b762012-07-27 04:22:15 +00004083 // Compute argument constness, constexpr, and triviality.
Richard Smith7756afa2012-06-10 05:43:50 +00004084 bool CanHaveConstParam = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004085 bool Trivial;
4086 switch (CSM) {
4087 case CXXDefaultConstructor:
Richard Smith3003e1d2012-05-15 04:39:51 +00004088 Trivial = RD->hasTrivialDefaultConstructor();
4089 break;
4090 case CXXCopyConstructor:
Richard Smithb9d0b762012-07-27 04:22:15 +00004091 CanHaveConstParam = isImplicitCopyCtorArgConst(*this, RD);
Richard Smith3003e1d2012-05-15 04:39:51 +00004092 Trivial = RD->hasTrivialCopyConstructor();
4093 break;
4094 case CXXCopyAssignment:
Richard Smithb9d0b762012-07-27 04:22:15 +00004095 CanHaveConstParam = isImplicitCopyAssignmentArgConst(*this, RD);
Richard Smith3003e1d2012-05-15 04:39:51 +00004096 Trivial = RD->hasTrivialCopyAssignment();
4097 break;
4098 case CXXMoveConstructor:
Richard Smith3003e1d2012-05-15 04:39:51 +00004099 Trivial = RD->hasTrivialMoveConstructor();
4100 break;
4101 case CXXMoveAssignment:
Richard Smith3003e1d2012-05-15 04:39:51 +00004102 Trivial = RD->hasTrivialMoveAssignment();
4103 break;
4104 case CXXDestructor:
Richard Smith3003e1d2012-05-15 04:39:51 +00004105 Trivial = RD->hasTrivialDestructor();
4106 break;
4107 case CXXInvalid:
4108 llvm_unreachable("non-special member explicitly defaulted!");
4109 }
Sean Hunt2b188082011-05-14 05:23:28 +00004110
Richard Smith3003e1d2012-05-15 04:39:51 +00004111 QualType ReturnType = Context.VoidTy;
4112 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4113 // Check for return type matching.
4114 ReturnType = Type->getResultType();
4115 QualType ExpectedReturnType =
4116 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4117 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4118 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4119 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4120 HadError = true;
4121 }
4122
4123 // A defaulted special member cannot have cv-qualifiers.
4124 if (Type->getTypeQuals()) {
4125 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
4126 << (CSM == CXXMoveAssignment);
4127 HadError = true;
4128 }
4129 }
4130
4131 // Check for parameter type matching.
4132 QualType ArgType = ExpectedParams ? Type->getArgType(0) : QualType();
Richard Smith7756afa2012-06-10 05:43:50 +00004133 bool HasConstParam = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004134 if (ExpectedParams && ArgType->isReferenceType()) {
4135 // Argument must be reference to possibly-const T.
4136 QualType ReferentType = ArgType->getPointeeType();
Richard Smith7756afa2012-06-10 05:43:50 +00004137 HasConstParam = ReferentType.isConstQualified();
Richard Smith3003e1d2012-05-15 04:39:51 +00004138
4139 if (ReferentType.isVolatileQualified()) {
4140 Diag(MD->getLocation(),
4141 diag::err_defaulted_special_member_volatile_param) << CSM;
4142 HadError = true;
4143 }
4144
Richard Smith7756afa2012-06-10 05:43:50 +00004145 if (HasConstParam && !CanHaveConstParam) {
Richard Smith3003e1d2012-05-15 04:39:51 +00004146 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4147 Diag(MD->getLocation(),
4148 diag::err_defaulted_special_member_copy_const_param)
4149 << (CSM == CXXCopyAssignment);
4150 // FIXME: Explain why this special member can't be const.
4151 } else {
4152 Diag(MD->getLocation(),
4153 diag::err_defaulted_special_member_move_const_param)
4154 << (CSM == CXXMoveAssignment);
4155 }
4156 HadError = true;
4157 }
4158
4159 // If a function is explicitly defaulted on its first declaration, it shall
4160 // have the same parameter type as if it had been implicitly declared.
4161 // (Presumably this is to prevent it from being trivial?)
Richard Smith7756afa2012-06-10 05:43:50 +00004162 if (!HasConstParam && CanHaveConstParam && First)
Richard Smith3003e1d2012-05-15 04:39:51 +00004163 Diag(MD->getLocation(),
4164 diag::err_defaulted_special_member_copy_non_const_param)
4165 << (CSM == CXXCopyAssignment);
4166 } else if (ExpectedParams) {
4167 // A copy assignment operator can take its argument by value, but a
4168 // defaulted one cannot.
4169 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Sean Huntbe631222011-05-17 20:44:43 +00004170 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Sean Hunt2b188082011-05-14 05:23:28 +00004171 HadError = true;
4172 }
Sean Huntbe631222011-05-17 20:44:43 +00004173
Richard Smithb9d0b762012-07-27 04:22:15 +00004174 // Rebuild the type with the implicit exception specification added, if we
4175 // are going to need it.
4176 const FunctionProtoType *ImplicitType = 0;
4177 if (First || Type->hasExceptionSpec()) {
4178 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
4179 computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI);
4180 ImplicitType = cast<FunctionProtoType>(
4181 Context.getFunctionType(ReturnType, &ArgType, ExpectedParams, EPI));
4182 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004183
Richard Smith61802452011-12-22 02:22:31 +00004184 // C++11 [dcl.fct.def.default]p2:
4185 // An explicitly-defaulted function may be declared constexpr only if it
4186 // would have been implicitly declared as constexpr,
Richard Smith3003e1d2012-05-15 04:39:51 +00004187 // Do not apply this rule to members of class templates, since core issue 1358
4188 // makes such functions always instantiate to constexpr functions. For
4189 // non-constructors, this is checked elsewhere.
Richard Smith7756afa2012-06-10 05:43:50 +00004190 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4191 HasConstParam);
Richard Smith3003e1d2012-05-15 04:39:51 +00004192 if (isa<CXXConstructorDecl>(MD) && MD->isConstexpr() && !Constexpr &&
4193 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4194 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
Richard Smith7756afa2012-06-10 05:43:50 +00004195 // FIXME: Explain why the constructor can't be constexpr.
Richard Smith3003e1d2012-05-15 04:39:51 +00004196 HadError = true;
Richard Smith61802452011-12-22 02:22:31 +00004197 }
4198 // and may have an explicit exception-specification only if it is compatible
4199 // with the exception-specification on the implicit declaration.
Richard Smith3003e1d2012-05-15 04:39:51 +00004200 if (Type->hasExceptionSpec() &&
4201 CheckEquivalentExceptionSpec(
4202 PDiag(diag::err_incorrect_defaulted_exception_spec) << CSM,
4203 PDiag(), ImplicitType, SourceLocation(), Type, MD->getLocation()))
4204 HadError = true;
Richard Smith61802452011-12-22 02:22:31 +00004205
4206 // If a function is explicitly defaulted on its first declaration,
4207 if (First) {
4208 // -- it is implicitly considered to be constexpr if the implicit
4209 // definition would be,
Richard Smith3003e1d2012-05-15 04:39:51 +00004210 MD->setConstexpr(Constexpr);
Richard Smith61802452011-12-22 02:22:31 +00004211
Richard Smith3003e1d2012-05-15 04:39:51 +00004212 // -- it is implicitly considered to have the same exception-specification
4213 // as if it had been implicitly declared,
4214 MD->setType(QualType(ImplicitType, 0));
Richard Smithe653ba22012-02-26 00:31:33 +00004215
4216 // Such a function is also trivial if the implicitly-declared function
4217 // would have been.
Richard Smith3003e1d2012-05-15 04:39:51 +00004218 MD->setTrivial(Trivial);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004219 }
4220
Richard Smith3003e1d2012-05-15 04:39:51 +00004221 if (ShouldDeleteSpecialMember(MD, CSM)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004222 if (First) {
4223 MD->setDeletedAsWritten();
4224 } else {
Richard Smith3003e1d2012-05-15 04:39:51 +00004225 // C++11 [dcl.fct.def.default]p4:
4226 // [For a] user-provided explicitly-defaulted function [...] if such a
4227 // function is implicitly defined as deleted, the program is ill-formed.
4228 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
4229 HadError = true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004230 }
4231 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004232
Richard Smith3003e1d2012-05-15 04:39:51 +00004233 if (HadError)
4234 MD->setInvalidDecl();
Sean Huntcb45a0f2011-05-12 22:46:25 +00004235}
4236
Richard Smith7d5088a2012-02-18 02:02:13 +00004237namespace {
4238struct SpecialMemberDeletionInfo {
4239 Sema &S;
4240 CXXMethodDecl *MD;
4241 Sema::CXXSpecialMember CSM;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004242 bool Diagnose;
Richard Smith7d5088a2012-02-18 02:02:13 +00004243
4244 // Properties of the special member, computed for convenience.
4245 bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg;
4246 SourceLocation Loc;
4247
4248 bool AllFieldsAreConst;
4249
4250 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith6c4c36c2012-03-30 20:53:28 +00004251 Sema::CXXSpecialMember CSM, bool Diagnose)
4252 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
Richard Smith7d5088a2012-02-18 02:02:13 +00004253 IsConstructor(false), IsAssignment(false), IsMove(false),
4254 ConstArg(false), VolatileArg(false), Loc(MD->getLocation()),
4255 AllFieldsAreConst(true) {
4256 switch (CSM) {
4257 case Sema::CXXDefaultConstructor:
4258 case Sema::CXXCopyConstructor:
4259 IsConstructor = true;
4260 break;
4261 case Sema::CXXMoveConstructor:
4262 IsConstructor = true;
4263 IsMove = true;
4264 break;
4265 case Sema::CXXCopyAssignment:
4266 IsAssignment = true;
4267 break;
4268 case Sema::CXXMoveAssignment:
4269 IsAssignment = true;
4270 IsMove = true;
4271 break;
4272 case Sema::CXXDestructor:
4273 break;
4274 case Sema::CXXInvalid:
4275 llvm_unreachable("invalid special member kind");
4276 }
4277
4278 if (MD->getNumParams()) {
4279 ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4280 VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified();
4281 }
4282 }
4283
4284 bool inUnion() const { return MD->getParent()->isUnion(); }
4285
4286 /// Look up the corresponding special member in the given class.
Richard Smith517bb842012-07-18 03:51:16 +00004287 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
4288 unsigned Quals) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004289 unsigned TQ = MD->getTypeQualifiers();
Richard Smith517bb842012-07-18 03:51:16 +00004290 // cv-qualifiers on class members don't affect default ctor / dtor calls.
4291 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4292 Quals = 0;
4293 return S.LookupSpecialMember(Class, CSM,
4294 ConstArg || (Quals & Qualifiers::Const),
4295 VolatileArg || (Quals & Qualifiers::Volatile),
Richard Smith7d5088a2012-02-18 02:02:13 +00004296 MD->getRefQualifier() == RQ_RValue,
4297 TQ & Qualifiers::Const,
4298 TQ & Qualifiers::Volatile);
4299 }
4300
Richard Smith6c4c36c2012-03-30 20:53:28 +00004301 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
Richard Smith9a561d52012-02-26 09:11:52 +00004302
Richard Smith6c4c36c2012-03-30 20:53:28 +00004303 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smith7d5088a2012-02-18 02:02:13 +00004304 bool shouldDeleteForField(FieldDecl *FD);
4305 bool shouldDeleteForAllConstMembers();
Richard Smith6c4c36c2012-03-30 20:53:28 +00004306
Richard Smith517bb842012-07-18 03:51:16 +00004307 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
4308 unsigned Quals);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004309 bool shouldDeleteForSubobjectCall(Subobject Subobj,
4310 Sema::SpecialMemberOverloadResult *SMOR,
4311 bool IsDtorCallInCtor);
John McCall12d8d802012-04-09 20:53:23 +00004312
4313 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smith7d5088a2012-02-18 02:02:13 +00004314};
4315}
4316
John McCall12d8d802012-04-09 20:53:23 +00004317/// Is the given special member inaccessible when used on the given
4318/// sub-object.
4319bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
4320 CXXMethodDecl *target) {
4321 /// If we're operating on a base class, the object type is the
4322 /// type of this special member.
4323 QualType objectTy;
4324 AccessSpecifier access = target->getAccess();;
4325 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
4326 objectTy = S.Context.getTypeDeclType(MD->getParent());
4327 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
4328
4329 // If we're operating on a field, the object type is the type of the field.
4330 } else {
4331 objectTy = S.Context.getTypeDeclType(target->getParent());
4332 }
4333
4334 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
4335}
4336
Richard Smith6c4c36c2012-03-30 20:53:28 +00004337/// Check whether we should delete a special member due to the implicit
4338/// definition containing a call to a special member of a subobject.
4339bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
4340 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
4341 bool IsDtorCallInCtor) {
4342 CXXMethodDecl *Decl = SMOR->getMethod();
4343 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
4344
4345 int DiagKind = -1;
4346
4347 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
4348 DiagKind = !Decl ? 0 : 1;
4349 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
4350 DiagKind = 2;
John McCall12d8d802012-04-09 20:53:23 +00004351 else if (!isAccessible(Subobj, Decl))
Richard Smith6c4c36c2012-03-30 20:53:28 +00004352 DiagKind = 3;
4353 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
4354 !Decl->isTrivial()) {
4355 // A member of a union must have a trivial corresponding special member.
4356 // As a weird special case, a destructor call from a union's constructor
4357 // must be accessible and non-deleted, but need not be trivial. Such a
4358 // destructor is never actually called, but is semantically checked as
4359 // if it were.
4360 DiagKind = 4;
4361 }
4362
4363 if (DiagKind == -1)
4364 return false;
4365
4366 if (Diagnose) {
4367 if (Field) {
4368 S.Diag(Field->getLocation(),
4369 diag::note_deleted_special_member_class_subobject)
4370 << CSM << MD->getParent() << /*IsField*/true
4371 << Field << DiagKind << IsDtorCallInCtor;
4372 } else {
4373 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
4374 S.Diag(Base->getLocStart(),
4375 diag::note_deleted_special_member_class_subobject)
4376 << CSM << MD->getParent() << /*IsField*/false
4377 << Base->getType() << DiagKind << IsDtorCallInCtor;
4378 }
4379
4380 if (DiagKind == 1)
4381 S.NoteDeletedFunction(Decl);
4382 // FIXME: Explain inaccessibility if DiagKind == 3.
4383 }
4384
4385 return true;
4386}
4387
Richard Smith9a561d52012-02-26 09:11:52 +00004388/// Check whether we should delete a special member function due to having a
Richard Smith517bb842012-07-18 03:51:16 +00004389/// direct or virtual base class or non-static data member of class type M.
Richard Smith9a561d52012-02-26 09:11:52 +00004390bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smith517bb842012-07-18 03:51:16 +00004391 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
Richard Smith6c4c36c2012-03-30 20:53:28 +00004392 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Richard Smith7d5088a2012-02-18 02:02:13 +00004393
4394 // C++11 [class.ctor]p5:
Richard Smithdf8dc862012-03-29 19:00:10 +00004395 // -- any direct or virtual base class, or non-static data member with no
4396 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smith7d5088a2012-02-18 02:02:13 +00004397 // either M has no default constructor or overload resolution as applied
4398 // to M's default constructor results in an ambiguity or in a function
4399 // that is deleted or inaccessible
4400 // C++11 [class.copy]p11, C++11 [class.copy]p23:
4401 // -- a direct or virtual base class B that cannot be copied/moved because
4402 // overload resolution, as applied to B's corresponding special member,
4403 // results in an ambiguity or a function that is deleted or inaccessible
4404 // from the defaulted special member
Richard Smith6c4c36c2012-03-30 20:53:28 +00004405 // C++11 [class.dtor]p5:
4406 // -- any direct or virtual base class [...] has a type with a destructor
4407 // that is deleted or inaccessible
4408 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smith1c931be2012-04-02 18:40:40 +00004409 Field && Field->hasInClassInitializer()) &&
Richard Smith517bb842012-07-18 03:51:16 +00004410 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals), false))
Richard Smith1c931be2012-04-02 18:40:40 +00004411 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004412
Richard Smith6c4c36c2012-03-30 20:53:28 +00004413 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
4414 // -- any direct or virtual base class or non-static data member has a
4415 // type with a destructor that is deleted or inaccessible
4416 if (IsConstructor) {
4417 Sema::SpecialMemberOverloadResult *SMOR =
4418 S.LookupSpecialMember(Class, Sema::CXXDestructor,
4419 false, false, false, false, false);
4420 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
4421 return true;
4422 }
4423
Richard Smith9a561d52012-02-26 09:11:52 +00004424 return false;
4425}
4426
4427/// Check whether we should delete a special member function due to the class
4428/// having a particular direct or virtual base class.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004429bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smith1c931be2012-04-02 18:40:40 +00004430 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
Richard Smith517bb842012-07-18 03:51:16 +00004431 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
Richard Smith7d5088a2012-02-18 02:02:13 +00004432}
4433
4434/// Check whether we should delete a special member function due to the class
4435/// having a particular non-static data member.
4436bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
4437 QualType FieldType = S.Context.getBaseElementType(FD->getType());
4438 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4439
4440 if (CSM == Sema::CXXDefaultConstructor) {
4441 // For a default constructor, all references must be initialized in-class
4442 // and, if a union, it must have a non-const member.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004443 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
4444 if (Diagnose)
4445 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
4446 << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004447 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004448 }
Richard Smith79363f52012-02-27 06:07:25 +00004449 // C++11 [class.ctor]p5: any non-variant non-static data member of
4450 // const-qualified type (or array thereof) with no
4451 // brace-or-equal-initializer does not have a user-provided default
4452 // constructor.
4453 if (!inUnion() && FieldType.isConstQualified() &&
4454 !FD->hasInClassInitializer() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004455 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
4456 if (Diagnose)
4457 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00004458 << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith79363f52012-02-27 06:07:25 +00004459 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004460 }
4461
4462 if (inUnion() && !FieldType.isConstQualified())
4463 AllFieldsAreConst = false;
Richard Smith7d5088a2012-02-18 02:02:13 +00004464 } else if (CSM == Sema::CXXCopyConstructor) {
4465 // For a copy constructor, data members must not be of rvalue reference
4466 // type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004467 if (FieldType->isRValueReferenceType()) {
4468 if (Diagnose)
4469 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
4470 << MD->getParent() << FD << FieldType;
Richard Smith7d5088a2012-02-18 02:02:13 +00004471 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004472 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004473 } else if (IsAssignment) {
4474 // For an assignment operator, data members must not be of reference type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004475 if (FieldType->isReferenceType()) {
4476 if (Diagnose)
4477 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
4478 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004479 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004480 }
4481 if (!FieldRecord && FieldType.isConstQualified()) {
4482 // C++11 [class.copy]p23:
4483 // -- a non-static data member of const non-class type (or array thereof)
4484 if (Diagnose)
4485 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00004486 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004487 return true;
4488 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004489 }
4490
4491 if (FieldRecord) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004492 // Some additional restrictions exist on the variant members.
4493 if (!inUnion() && FieldRecord->isUnion() &&
4494 FieldRecord->isAnonymousStructOrUnion()) {
4495 bool AllVariantFieldsAreConst = true;
4496
Richard Smithdf8dc862012-03-29 19:00:10 +00004497 // FIXME: Handle anonymous unions declared within anonymous unions.
Richard Smith7d5088a2012-02-18 02:02:13 +00004498 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4499 UE = FieldRecord->field_end();
4500 UI != UE; ++UI) {
4501 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smith7d5088a2012-02-18 02:02:13 +00004502
4503 if (!UnionFieldType.isConstQualified())
4504 AllVariantFieldsAreConst = false;
4505
Richard Smith9a561d52012-02-26 09:11:52 +00004506 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
4507 if (UnionFieldRecord &&
Richard Smith517bb842012-07-18 03:51:16 +00004508 shouldDeleteForClassSubobject(UnionFieldRecord, *UI,
4509 UnionFieldType.getCVRQualifiers()))
Richard Smith9a561d52012-02-26 09:11:52 +00004510 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004511 }
4512
4513 // At least one member in each anonymous union must be non-const
Douglas Gregor221c27f2012-02-24 21:25:53 +00004514 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004515 FieldRecord->field_begin() != FieldRecord->field_end()) {
4516 if (Diagnose)
4517 S.Diag(FieldRecord->getLocation(),
4518 diag::note_deleted_default_ctor_all_const)
4519 << MD->getParent() << /*anonymous union*/1;
Richard Smith7d5088a2012-02-18 02:02:13 +00004520 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004521 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004522
Richard Smithdf8dc862012-03-29 19:00:10 +00004523 // Don't check the implicit member of the anonymous union type.
Richard Smith7d5088a2012-02-18 02:02:13 +00004524 // This is technically non-conformant, but sanity demands it.
4525 return false;
4526 }
4527
Richard Smith517bb842012-07-18 03:51:16 +00004528 if (shouldDeleteForClassSubobject(FieldRecord, FD,
4529 FieldType.getCVRQualifiers()))
Richard Smithdf8dc862012-03-29 19:00:10 +00004530 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004531 }
4532
4533 return false;
4534}
4535
4536/// C++11 [class.ctor] p5:
4537/// A defaulted default constructor for a class X is defined as deleted if
4538/// X is a union and all of its variant members are of const-qualified type.
4539bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor221c27f2012-02-24 21:25:53 +00004540 // This is a silly definition, because it gives an empty union a deleted
4541 // default constructor. Don't do that.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004542 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
4543 (MD->getParent()->field_begin() != MD->getParent()->field_end())) {
4544 if (Diagnose)
4545 S.Diag(MD->getParent()->getLocation(),
4546 diag::note_deleted_default_ctor_all_const)
4547 << MD->getParent() << /*not anonymous union*/0;
4548 return true;
4549 }
4550 return false;
Richard Smith7d5088a2012-02-18 02:02:13 +00004551}
4552
4553/// Determine whether a defaulted special member function should be defined as
4554/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
4555/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004556bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
4557 bool Diagnose) {
Richard Smitheef00292012-08-06 02:25:10 +00004558 if (MD->isInvalidDecl())
4559 return false;
Sean Hunte16da072011-10-10 06:18:57 +00004560 CXXRecordDecl *RD = MD->getParent();
Sean Huntcdee3fe2011-05-11 22:34:38 +00004561 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaracdb80762011-07-11 08:52:40 +00004562 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004563 return false;
4564
Richard Smith7d5088a2012-02-18 02:02:13 +00004565 // C++11 [expr.lambda.prim]p19:
4566 // The closure type associated with a lambda-expression has a
4567 // deleted (8.4.3) default constructor and a deleted copy
4568 // assignment operator.
4569 if (RD->isLambda() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004570 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
4571 if (Diagnose)
4572 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smith7d5088a2012-02-18 02:02:13 +00004573 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004574 }
4575
Richard Smith5bdaac52012-04-02 20:59:25 +00004576 // For an anonymous struct or union, the copy and assignment special members
4577 // will never be used, so skip the check. For an anonymous union declared at
4578 // namespace scope, the constructor and destructor are used.
4579 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
4580 RD->isAnonymousStructOrUnion())
4581 return false;
4582
Richard Smith6c4c36c2012-03-30 20:53:28 +00004583 // C++11 [class.copy]p7, p18:
4584 // If the class definition declares a move constructor or move assignment
4585 // operator, an implicitly declared copy constructor or copy assignment
4586 // operator is defined as deleted.
4587 if (MD->isImplicit() &&
4588 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
4589 CXXMethodDecl *UserDeclaredMove = 0;
4590
4591 // In Microsoft mode, a user-declared move only causes the deletion of the
4592 // corresponding copy operation, not both copy operations.
4593 if (RD->hasUserDeclaredMoveConstructor() &&
4594 (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) {
4595 if (!Diagnose) return true;
4596 UserDeclaredMove = RD->getMoveConstructor();
Richard Smith1c931be2012-04-02 18:40:40 +00004597 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004598 } else if (RD->hasUserDeclaredMoveAssignment() &&
4599 (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) {
4600 if (!Diagnose) return true;
4601 UserDeclaredMove = RD->getMoveAssignmentOperator();
Richard Smith1c931be2012-04-02 18:40:40 +00004602 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004603 }
4604
4605 if (UserDeclaredMove) {
4606 Diag(UserDeclaredMove->getLocation(),
4607 diag::note_deleted_copy_user_declared_move)
Richard Smithe6af6602012-04-02 21:07:48 +00004608 << (CSM == CXXCopyAssignment) << RD
Richard Smith6c4c36c2012-03-30 20:53:28 +00004609 << UserDeclaredMove->isMoveAssignmentOperator();
4610 return true;
4611 }
4612 }
Sean Hunte16da072011-10-10 06:18:57 +00004613
Richard Smith5bdaac52012-04-02 20:59:25 +00004614 // Do access control from the special member function
4615 ContextRAII MethodContext(*this, MD);
4616
Richard Smith9a561d52012-02-26 09:11:52 +00004617 // C++11 [class.dtor]p5:
4618 // -- for a virtual destructor, lookup of the non-array deallocation function
4619 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith6c4c36c2012-03-30 20:53:28 +00004620 if (CSM == CXXDestructor && MD->isVirtual()) {
Richard Smith9a561d52012-02-26 09:11:52 +00004621 FunctionDecl *OperatorDelete = 0;
4622 DeclarationName Name =
4623 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
4624 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smith6c4c36c2012-03-30 20:53:28 +00004625 OperatorDelete, false)) {
4626 if (Diagnose)
4627 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith9a561d52012-02-26 09:11:52 +00004628 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004629 }
Richard Smith9a561d52012-02-26 09:11:52 +00004630 }
4631
Richard Smith6c4c36c2012-03-30 20:53:28 +00004632 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
Sean Huntcdee3fe2011-05-11 22:34:38 +00004633
Sean Huntcdee3fe2011-05-11 22:34:38 +00004634 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004635 BE = RD->bases_end(); BI != BE; ++BI)
4636 if (!BI->isVirtual() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004637 SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00004638 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004639
4640 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004641 BE = RD->vbases_end(); BI != BE; ++BI)
Richard Smith6c4c36c2012-03-30 20:53:28 +00004642 if (SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00004643 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004644
4645 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004646 FE = RD->field_end(); FI != FE; ++FI)
4647 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
David Blaikie581deb32012-06-06 20:45:41 +00004648 SMI.shouldDeleteForField(*FI))
Sean Hunte3406822011-05-20 21:43:47 +00004649 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004650
Richard Smith7d5088a2012-02-18 02:02:13 +00004651 if (SMI.shouldDeleteForAllConstMembers())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004652 return true;
4653
4654 return false;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004655}
4656
4657/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramerc54061a2011-03-04 13:12:48 +00004658namespace {
4659 struct FindHiddenVirtualMethodData {
4660 Sema *S;
4661 CXXMethodDecl *Method;
4662 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004663 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramerc54061a2011-03-04 13:12:48 +00004664 };
4665}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004666
4667/// \brief Member lookup function that determines whether a given C++
4668/// method overloads virtual methods in a base class without overriding any,
4669/// to be used with CXXRecordDecl::lookupInBases().
4670static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
4671 CXXBasePath &Path,
4672 void *UserData) {
4673 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
4674
4675 FindHiddenVirtualMethodData &Data
4676 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
4677
4678 DeclarationName Name = Data.Method->getDeclName();
4679 assert(Name.getNameKind() == DeclarationName::Identifier);
4680
4681 bool foundSameNameMethod = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004682 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004683 for (Path.Decls = BaseRecord->lookup(Name);
4684 Path.Decls.first != Path.Decls.second;
4685 ++Path.Decls.first) {
4686 NamedDecl *D = *Path.Decls.first;
4687 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00004688 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004689 foundSameNameMethod = true;
4690 // Interested only in hidden virtual methods.
4691 if (!MD->isVirtual())
4692 continue;
4693 // If the method we are checking overrides a method from its base
4694 // don't warn about the other overloaded methods.
4695 if (!Data.S->IsOverload(Data.Method, MD, false))
4696 return true;
4697 // Collect the overload only if its hidden.
4698 if (!Data.OverridenAndUsingBaseMethods.count(MD))
4699 overloadedMethods.push_back(MD);
4700 }
4701 }
4702
4703 if (foundSameNameMethod)
4704 Data.OverloadedMethods.append(overloadedMethods.begin(),
4705 overloadedMethods.end());
4706 return foundSameNameMethod;
4707}
4708
4709/// \brief See if a method overloads virtual methods in a base class without
4710/// overriding any.
4711void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
4712 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
David Blaikied6471f72011-09-25 23:23:43 +00004713 MD->getLocation()) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004714 return;
Benjamin Kramerc4704422012-05-19 16:03:58 +00004715 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004716 return;
4717
4718 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
4719 /*bool RecordPaths=*/false,
4720 /*bool DetectVirtual=*/false);
4721 FindHiddenVirtualMethodData Data;
4722 Data.Method = MD;
4723 Data.S = this;
4724
4725 // Keep the base methods that were overriden or introduced in the subclass
4726 // by 'using' in a set. A base method not in this set is hidden.
4727 for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
4728 res.first != res.second; ++res.first) {
4729 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first))
4730 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
4731 E = MD->end_overridden_methods();
4732 I != E; ++I)
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00004733 Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004734 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
4735 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl()))
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00004736 Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004737 }
4738
4739 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
4740 !Data.OverloadedMethods.empty()) {
4741 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
4742 << MD << (Data.OverloadedMethods.size() > 1);
4743
4744 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
4745 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
4746 Diag(overloadedMD->getLocation(),
4747 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
4748 }
4749 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004750}
4751
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00004752void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00004753 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00004754 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00004755 SourceLocation RBrac,
4756 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00004757 if (!TagDecl)
4758 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004759
Douglas Gregor42af25f2009-05-11 19:58:34 +00004760 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004761
Rafael Espindolaf729ce02012-07-12 04:32:30 +00004762 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
4763 if (l->getKind() != AttributeList::AT_Visibility)
4764 continue;
4765 l->setInvalid();
4766 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
4767 l->getName();
4768 }
4769
David Blaikie77b6de02011-09-22 02:58:26 +00004770 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCalld226f652010-08-21 09:40:31 +00004771 // strict aliasing violation!
4772 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie77b6de02011-09-22 02:58:26 +00004773 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00004774
Douglas Gregor23c94db2010-07-02 17:43:08 +00004775 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00004776 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00004777}
4778
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004779/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
4780/// special functions, such as the default constructor, copy
4781/// constructor, or destructor, to the given C++ class (C++
4782/// [special]p1). This routine can only be executed just before the
4783/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00004784void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00004785 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00004786 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004787
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00004788 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregor22584312010-07-02 23:41:54 +00004789 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004790
David Blaikie4e4d0842012-03-11 07:00:24 +00004791 if (getLangOpts().CPlusPlus0x && ClassDecl->needsImplicitMoveConstructor())
Richard Smithb701d3d2011-12-24 21:56:24 +00004792 ++ASTContext::NumImplicitMoveConstructors;
4793
Douglas Gregora376d102010-07-02 21:50:04 +00004794 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
4795 ++ASTContext::NumImplicitCopyAssignmentOperators;
4796
4797 // If we have a dynamic class, then the copy assignment operator may be
4798 // virtual, so we have to declare it immediately. This ensures that, e.g.,
4799 // it shows up in the right place in the vtable and that we diagnose
4800 // problems with the implicit exception specification.
4801 if (ClassDecl->isDynamicClass())
4802 DeclareImplicitCopyAssignment(ClassDecl);
4803 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00004804
Richard Smith1c931be2012-04-02 18:40:40 +00004805 if (getLangOpts().CPlusPlus0x && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00004806 ++ASTContext::NumImplicitMoveAssignmentOperators;
4807
4808 // Likewise for the move assignment operator.
4809 if (ClassDecl->isDynamicClass())
4810 DeclareImplicitMoveAssignment(ClassDecl);
4811 }
4812
Douglas Gregor4923aa22010-07-02 20:37:36 +00004813 if (!ClassDecl->hasUserDeclaredDestructor()) {
4814 ++ASTContext::NumImplicitDestructors;
4815
4816 // If we have a dynamic class, then the destructor may be virtual, so we
4817 // have to declare the destructor immediately. This ensures that, e.g., it
4818 // shows up in the right place in the vtable and that we diagnose problems
4819 // with the implicit exception specification.
4820 if (ClassDecl->isDynamicClass())
4821 DeclareImplicitDestructor(ClassDecl);
4822 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004823}
4824
Francois Pichet8387e2a2011-04-22 22:18:13 +00004825void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
4826 if (!D)
4827 return;
4828
4829 int NumParamList = D->getNumTemplateParameterLists();
4830 for (int i = 0; i < NumParamList; i++) {
4831 TemplateParameterList* Params = D->getTemplateParameterList(i);
4832 for (TemplateParameterList::iterator Param = Params->begin(),
4833 ParamEnd = Params->end();
4834 Param != ParamEnd; ++Param) {
4835 NamedDecl *Named = cast<NamedDecl>(*Param);
4836 if (Named->getDeclName()) {
4837 S->AddDecl(Named);
4838 IdResolver.AddDecl(Named);
4839 }
4840 }
4841 }
4842}
4843
John McCalld226f652010-08-21 09:40:31 +00004844void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00004845 if (!D)
4846 return;
4847
4848 TemplateParameterList *Params = 0;
4849 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
4850 Params = Template->getTemplateParameters();
4851 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
4852 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
4853 Params = PartialSpec->getTemplateParameters();
4854 else
Douglas Gregor6569d682009-05-27 23:11:45 +00004855 return;
4856
Douglas Gregor6569d682009-05-27 23:11:45 +00004857 for (TemplateParameterList::iterator Param = Params->begin(),
4858 ParamEnd = Params->end();
4859 Param != ParamEnd; ++Param) {
4860 NamedDecl *Named = cast<NamedDecl>(*Param);
4861 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00004862 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00004863 IdResolver.AddDecl(Named);
4864 }
4865 }
4866}
4867
John McCalld226f652010-08-21 09:40:31 +00004868void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00004869 if (!RecordD) return;
4870 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00004871 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00004872 PushDeclContext(S, Record);
4873}
4874
John McCalld226f652010-08-21 09:40:31 +00004875void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00004876 if (!RecordD) return;
4877 PopDeclContext();
4878}
4879
Douglas Gregor72b505b2008-12-16 21:30:33 +00004880/// ActOnStartDelayedCXXMethodDeclaration - We have completed
4881/// parsing a top-level (non-nested) C++ class, and we are now
4882/// parsing those parts of the given Method declaration that could
4883/// not be parsed earlier (C++ [class.mem]p2), such as default
4884/// arguments. This action should enter the scope of the given
4885/// Method declaration as if we had just parsed the qualified method
4886/// name. However, it should not bring the parameters into scope;
4887/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00004888void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00004889}
4890
4891/// ActOnDelayedCXXMethodParameter - We've already started a delayed
4892/// C++ method declaration. We're (re-)introducing the given
4893/// function parameter into scope for use in parsing later parts of
4894/// the method declaration. For example, we could see an
4895/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00004896void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00004897 if (!ParamD)
4898 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004899
John McCalld226f652010-08-21 09:40:31 +00004900 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00004901
4902 // If this parameter has an unparsed default argument, clear it out
4903 // to make way for the parsed default argument.
4904 if (Param->hasUnparsedDefaultArg())
4905 Param->setDefaultArg(0);
4906
John McCalld226f652010-08-21 09:40:31 +00004907 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00004908 if (Param->getDeclName())
4909 IdResolver.AddDecl(Param);
4910}
4911
4912/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
4913/// processing the delayed method declaration for Method. The method
4914/// declaration is now considered finished. There may be a separate
4915/// ActOnStartOfFunctionDef action later (not necessarily
4916/// immediately!) for this method, if it was also defined inside the
4917/// class body.
John McCalld226f652010-08-21 09:40:31 +00004918void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00004919 if (!MethodD)
4920 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004921
Douglas Gregorefd5bda2009-08-24 11:57:43 +00004922 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00004923
John McCalld226f652010-08-21 09:40:31 +00004924 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00004925
4926 // Now that we have our default arguments, check the constructor
4927 // again. It could produce additional diagnostics or affect whether
4928 // the class has implicitly-declared destructors, among other
4929 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00004930 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
4931 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00004932
4933 // Check the default arguments, which we may have added.
4934 if (!Method->isInvalidDecl())
4935 CheckCXXDefaultArguments(Method);
4936}
4937
Douglas Gregor42a552f2008-11-05 20:51:48 +00004938/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00004939/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00004940/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00004941/// emit diagnostics and set the invalid bit to true. In any case, the type
4942/// will be updated to reflect a well-formed type for the constructor and
4943/// returned.
4944QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00004945 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00004946 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00004947
4948 // C++ [class.ctor]p3:
4949 // A constructor shall not be virtual (10.3) or static (9.4). A
4950 // constructor can be invoked for a const, volatile or const
4951 // volatile object. A constructor shall not be declared const,
4952 // volatile, or const volatile (9.3.2).
4953 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00004954 if (!D.isInvalidType())
4955 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
4956 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
4957 << SourceRange(D.getIdentifierLoc());
4958 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00004959 }
John McCalld931b082010-08-26 03:08:43 +00004960 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00004961 if (!D.isInvalidType())
4962 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
4963 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
4964 << SourceRange(D.getIdentifierLoc());
4965 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00004966 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00004967 }
Mike Stump1eb44332009-09-09 15:08:12 +00004968
Abramo Bagnara075f8f12010-12-10 16:29:40 +00004969 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00004970 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00004971 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004972 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4973 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00004974 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004975 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4976 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00004977 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004978 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4979 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00004980 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00004981 }
Mike Stump1eb44332009-09-09 15:08:12 +00004982
Douglas Gregorc938c162011-01-26 05:01:58 +00004983 // C++0x [class.ctor]p4:
4984 // A constructor shall not be declared with a ref-qualifier.
4985 if (FTI.hasRefQualifier()) {
4986 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
4987 << FTI.RefQualifierIsLValueRef
4988 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
4989 D.setInvalidType();
4990 }
4991
Douglas Gregor42a552f2008-11-05 20:51:48 +00004992 // Rebuild the function type "R" without any type qualifiers (in
4993 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00004994 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00004995 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00004996 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
4997 return R;
4998
4999 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5000 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005001 EPI.RefQualifier = RQ_None;
5002
Chris Lattner65401802009-04-25 08:28:21 +00005003 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00005004 Proto->getNumArgs(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005005}
5006
Douglas Gregor72b505b2008-12-16 21:30:33 +00005007/// CheckConstructor - Checks a fully-formed constructor for
5008/// well-formedness, issuing any diagnostics required. Returns true if
5009/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00005010void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00005011 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00005012 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
5013 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00005014 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005015
5016 // C++ [class.copy]p3:
5017 // A declaration of a constructor for a class X is ill-formed if
5018 // its first parameter is of type (optionally cv-qualified) X and
5019 // either there are no other parameters or else all other
5020 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00005021 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00005022 ((Constructor->getNumParams() == 1) ||
5023 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00005024 Constructor->getParamDecl(1)->hasDefaultArg())) &&
5025 Constructor->getTemplateSpecializationKind()
5026 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005027 QualType ParamType = Constructor->getParamDecl(0)->getType();
5028 QualType ClassTy = Context.getTagDeclType(ClassDecl);
5029 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00005030 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005031 const char *ConstRef
5032 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
5033 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00005034 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005035 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00005036
5037 // FIXME: Rather that making the constructor invalid, we should endeavor
5038 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00005039 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005040 }
5041 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00005042}
5043
John McCall15442822010-08-04 01:04:25 +00005044/// CheckDestructor - Checks a fully-formed destructor definition for
5045/// well-formedness, issuing any diagnostics required. Returns true
5046/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005047bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00005048 CXXRecordDecl *RD = Destructor->getParent();
5049
5050 if (Destructor->isVirtual()) {
5051 SourceLocation Loc;
5052
5053 if (!Destructor->isImplicit())
5054 Loc = Destructor->getLocation();
5055 else
5056 Loc = RD->getLocation();
5057
5058 // If we have a virtual destructor, look up the deallocation function
5059 FunctionDecl *OperatorDelete = 0;
5060 DeclarationName Name =
5061 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005062 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00005063 return true;
John McCall5efd91a2010-07-03 18:33:00 +00005064
Eli Friedman5f2987c2012-02-02 03:46:19 +00005065 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00005066
5067 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00005068 }
Anders Carlsson37909802009-11-30 21:24:50 +00005069
5070 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00005071}
5072
Mike Stump1eb44332009-09-09 15:08:12 +00005073static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005074FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
5075 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5076 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00005077 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005078}
5079
Douglas Gregor42a552f2008-11-05 20:51:48 +00005080/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
5081/// the well-formednes of the destructor declarator @p D with type @p
5082/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005083/// emit diagnostics and set the declarator to invalid. Even if this happens,
5084/// will be updated to reflect a well-formed type for the destructor and
5085/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00005086QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005087 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005088 // C++ [class.dtor]p1:
5089 // [...] A typedef-name that names a class is a class-name
5090 // (7.1.3); however, a typedef-name that names a class shall not
5091 // be used as the identifier in the declarator for a destructor
5092 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005093 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smith162e1c12011-04-15 14:24:37 +00005094 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner65401802009-04-25 08:28:21 +00005095 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smith162e1c12011-04-15 14:24:37 +00005096 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00005097 else if (const TemplateSpecializationType *TST =
5098 DeclaratorType->getAs<TemplateSpecializationType>())
5099 if (TST->isTypeAlias())
5100 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5101 << DeclaratorType << 1;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005102
5103 // C++ [class.dtor]p2:
5104 // A destructor is used to destroy objects of its class type. A
5105 // destructor takes no parameters, and no return type can be
5106 // specified for it (not even void). The address of a destructor
5107 // shall not be taken. A destructor shall not be static. A
5108 // destructor can be invoked for a const, volatile or const
5109 // volatile object. A destructor shall not be declared const,
5110 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00005111 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005112 if (!D.isInvalidType())
5113 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
5114 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00005115 << SourceRange(D.getIdentifierLoc())
5116 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5117
John McCalld931b082010-08-26 03:08:43 +00005118 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005119 }
Chris Lattner65401802009-04-25 08:28:21 +00005120 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005121 // Destructors don't have return types, but the parser will
5122 // happily parse something like:
5123 //
5124 // class X {
5125 // float ~X();
5126 // };
5127 //
5128 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005129 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
5130 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5131 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00005132 }
Mike Stump1eb44332009-09-09 15:08:12 +00005133
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005134 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005135 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00005136 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005137 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5138 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005139 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005140 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5141 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005142 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005143 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5144 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00005145 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005146 }
5147
Douglas Gregorc938c162011-01-26 05:01:58 +00005148 // C++0x [class.dtor]p2:
5149 // A destructor shall not be declared with a ref-qualifier.
5150 if (FTI.hasRefQualifier()) {
5151 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
5152 << FTI.RefQualifierIsLValueRef
5153 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5154 D.setInvalidType();
5155 }
5156
Douglas Gregor42a552f2008-11-05 20:51:48 +00005157 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005158 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005159 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
5160
5161 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00005162 FTI.freeArgs();
5163 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005164 }
5165
Mike Stump1eb44332009-09-09 15:08:12 +00005166 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00005167 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005168 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00005169 D.setInvalidType();
5170 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00005171
5172 // Rebuild the function type "R" without any type qualifiers or
5173 // parameters (in case any of the errors above fired) and with
5174 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00005175 // types.
John McCalle23cf432010-12-14 08:05:40 +00005176 if (!D.isInvalidType())
5177 return R;
5178
Douglas Gregord92ec472010-07-01 05:10:53 +00005179 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005180 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5181 EPI.Variadic = false;
5182 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005183 EPI.RefQualifier = RQ_None;
John McCalle23cf432010-12-14 08:05:40 +00005184 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005185}
5186
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005187/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
5188/// well-formednes of the conversion function declarator @p D with
5189/// type @p R. If there are any errors in the declarator, this routine
5190/// will emit diagnostics and return true. Otherwise, it will return
5191/// false. Either way, the type @p R will be updated to reflect a
5192/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00005193void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00005194 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005195 // C++ [class.conv.fct]p1:
5196 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00005197 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00005198 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00005199 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00005200 if (!D.isInvalidType())
5201 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
5202 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5203 << SourceRange(D.getIdentifierLoc());
5204 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005205 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005206 }
John McCalla3f81372010-04-13 00:04:31 +00005207
5208 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
5209
Chris Lattner6e475012009-04-25 08:35:12 +00005210 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005211 // Conversion functions don't have return types, but the parser will
5212 // happily parse something like:
5213 //
5214 // class X {
5215 // float operator bool();
5216 // };
5217 //
5218 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005219 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
5220 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5221 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00005222 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005223 }
5224
John McCalla3f81372010-04-13 00:04:31 +00005225 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5226
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005227 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00005228 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005229 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
5230
5231 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005232 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00005233 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00005234 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005235 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00005236 D.setInvalidType();
5237 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005238
John McCalla3f81372010-04-13 00:04:31 +00005239 // Diagnose "&operator bool()" and other such nonsense. This
5240 // is actually a gcc extension which we don't support.
5241 if (Proto->getResultType() != ConvType) {
5242 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
5243 << Proto->getResultType();
5244 D.setInvalidType();
5245 ConvType = Proto->getResultType();
5246 }
5247
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005248 // C++ [class.conv.fct]p4:
5249 // The conversion-type-id shall not represent a function type nor
5250 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005251 if (ConvType->isArrayType()) {
5252 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
5253 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005254 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005255 } else if (ConvType->isFunctionType()) {
5256 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
5257 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005258 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005259 }
5260
5261 // Rebuild the function type "R" without any parameters (in case any
5262 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00005263 // return type.
John McCalle23cf432010-12-14 08:05:40 +00005264 if (D.isInvalidType())
5265 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005266
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005267 // C++0x explicit conversion operators.
Richard Smithebaf0e62011-10-18 20:49:44 +00005268 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump1eb44332009-09-09 15:08:12 +00005269 Diag(D.getDeclSpec().getExplicitSpecLoc(),
David Blaikie4e4d0842012-03-11 07:00:24 +00005270 getLangOpts().CPlusPlus0x ?
Richard Smithebaf0e62011-10-18 20:49:44 +00005271 diag::warn_cxx98_compat_explicit_conversion_functions :
5272 diag::ext_explicit_conversion_functions)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005273 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005274}
5275
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005276/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
5277/// the declaration of the given C++ conversion function. This routine
5278/// is responsible for recording the conversion function in the C++
5279/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00005280Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005281 assert(Conversion && "Expected to receive a conversion function declaration");
5282
Douglas Gregor9d350972008-12-12 08:25:50 +00005283 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005284
5285 // Make sure we aren't redeclaring the conversion function.
5286 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005287
5288 // C++ [class.conv.fct]p1:
5289 // [...] A conversion function is never used to convert a
5290 // (possibly cv-qualified) object to the (possibly cv-qualified)
5291 // same object type (or a reference to it), to a (possibly
5292 // cv-qualified) base class of that type (or a reference to it),
5293 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00005294 // FIXME: Suppress this warning if the conversion function ends up being a
5295 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00005296 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005297 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00005298 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005299 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005300 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
5301 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00005302 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005303 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005304 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
5305 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00005306 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005307 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005308 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00005309 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005310 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005311 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00005312 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005313 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005314 }
5315
Douglas Gregore80622f2010-09-29 04:25:11 +00005316 if (FunctionTemplateDecl *ConversionTemplate
5317 = Conversion->getDescribedFunctionTemplate())
5318 return ConversionTemplate;
5319
John McCalld226f652010-08-21 09:40:31 +00005320 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005321}
5322
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005323//===----------------------------------------------------------------------===//
5324// Namespace Handling
5325//===----------------------------------------------------------------------===//
5326
John McCallea318642010-08-26 09:15:37 +00005327
5328
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005329/// ActOnStartNamespaceDef - This is called at the start of a namespace
5330/// definition.
John McCalld226f652010-08-21 09:40:31 +00005331Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00005332 SourceLocation InlineLoc,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005333 SourceLocation NamespaceLoc,
John McCallea318642010-08-26 09:15:37 +00005334 SourceLocation IdentLoc,
5335 IdentifierInfo *II,
5336 SourceLocation LBrace,
5337 AttributeList *AttrList) {
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005338 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
5339 // For anonymous namespace, take the location of the left brace.
5340 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005341 bool IsInline = InlineLoc.isValid();
Douglas Gregor67310742012-01-10 22:14:10 +00005342 bool IsInvalid = false;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005343 bool IsStd = false;
5344 bool AddToKnown = false;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005345 Scope *DeclRegionScope = NamespcScope->getParent();
5346
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005347 NamespaceDecl *PrevNS = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005348 if (II) {
5349 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00005350 // The identifier in an original-namespace-definition shall not
5351 // have been previously defined in the declarative region in
5352 // which the original-namespace-definition appears. The
5353 // identifier in an original-namespace-definition is the name of
5354 // the namespace. Subsequently in that declarative region, it is
5355 // treated as an original-namespace-name.
5356 //
5357 // Since namespace names are unique in their scope, and we don't
Douglas Gregor010157f2011-05-06 23:28:47 +00005358 // look through using directives, just look for any ordinary names.
5359
5360 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005361 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
5362 Decl::IDNS_Namespace;
Douglas Gregor010157f2011-05-06 23:28:47 +00005363 NamedDecl *PrevDecl = 0;
5364 for (DeclContext::lookup_result R
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005365 = CurContext->getRedeclContext()->lookup(II);
Douglas Gregor010157f2011-05-06 23:28:47 +00005366 R.first != R.second; ++R.first) {
5367 if ((*R.first)->getIdentifierNamespace() & IDNS) {
5368 PrevDecl = *R.first;
5369 break;
5370 }
5371 }
5372
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005373 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
5374
5375 if (PrevNS) {
Douglas Gregor44b43212008-12-11 16:49:14 +00005376 // This is an extended namespace definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005377 if (IsInline != PrevNS->isInline()) {
Sebastian Redl4e4d5702010-08-31 00:36:36 +00005378 // inline-ness must match
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005379 if (PrevNS->isInline()) {
Douglas Gregorb7ec9062011-05-20 15:48:31 +00005380 // The user probably just forgot the 'inline', so suggest that it
5381 // be added back.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005382 Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
Douglas Gregorb7ec9062011-05-20 15:48:31 +00005383 << FixItHint::CreateInsertion(NamespaceLoc, "inline ");
5384 } else {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005385 Diag(Loc, diag::err_inline_namespace_mismatch)
5386 << IsInline;
Douglas Gregorb7ec9062011-05-20 15:48:31 +00005387 }
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005388 Diag(PrevNS->getLocation(), diag::note_previous_definition);
5389
5390 IsInline = PrevNS->isInline();
5391 }
Douglas Gregor44b43212008-12-11 16:49:14 +00005392 } else if (PrevDecl) {
5393 // This is an invalid name redefinition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005394 Diag(Loc, diag::err_redefinition_different_kind)
5395 << II;
Douglas Gregor44b43212008-12-11 16:49:14 +00005396 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00005397 IsInvalid = true;
Douglas Gregor44b43212008-12-11 16:49:14 +00005398 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005399 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00005400 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00005401 // This is the first "real" definition of the namespace "std", so update
5402 // our cache of the "std" namespace to point at this definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005403 PrevNS = getStdNamespace();
5404 IsStd = true;
5405 AddToKnown = !IsInline;
5406 } else {
5407 // We've seen this namespace for the first time.
5408 AddToKnown = !IsInline;
Mike Stump1eb44332009-09-09 15:08:12 +00005409 }
Douglas Gregor44b43212008-12-11 16:49:14 +00005410 } else {
John McCall9aeed322009-10-01 00:25:31 +00005411 // Anonymous namespaces.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005412
5413 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl7a126a42010-08-31 00:36:30 +00005414 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00005415 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005416 PrevNS = TU->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00005417 } else {
5418 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005419 PrevNS = ND->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00005420 }
5421
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005422 if (PrevNS && IsInline != PrevNS->isInline()) {
5423 // inline-ness must match
5424 Diag(Loc, diag::err_inline_namespace_mismatch)
5425 << IsInline;
5426 Diag(PrevNS->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00005427
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005428 // Recover by ignoring the new namespace's inline status.
5429 IsInline = PrevNS->isInline();
5430 }
5431 }
5432
5433 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
5434 StartLoc, Loc, II, PrevNS);
Douglas Gregor67310742012-01-10 22:14:10 +00005435 if (IsInvalid)
5436 Namespc->setInvalidDecl();
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005437
5438 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00005439
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005440 // FIXME: Should we be merging attributes?
5441 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00005442 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005443
5444 if (IsStd)
5445 StdNamespace = Namespc;
5446 if (AddToKnown)
5447 KnownNamespaces[Namespc] = false;
5448
5449 if (II) {
5450 PushOnScopeChains(Namespc, DeclRegionScope);
5451 } else {
5452 // Link the anonymous namespace into its parent.
5453 DeclContext *Parent = CurContext->getRedeclContext();
5454 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
5455 TU->setAnonymousNamespace(Namespc);
5456 } else {
5457 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall5fdd7642009-12-16 02:06:49 +00005458 }
John McCall9aeed322009-10-01 00:25:31 +00005459
Douglas Gregora4181472010-03-24 00:46:35 +00005460 CurContext->addDecl(Namespc);
5461
John McCall9aeed322009-10-01 00:25:31 +00005462 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
5463 // behaves as if it were replaced by
5464 // namespace unique { /* empty body */ }
5465 // using namespace unique;
5466 // namespace unique { namespace-body }
5467 // where all occurrences of 'unique' in a translation unit are
5468 // replaced by the same identifier and this identifier differs
5469 // from all other identifiers in the entire program.
5470
5471 // We just create the namespace with an empty name and then add an
5472 // implicit using declaration, just like the standard suggests.
5473 //
5474 // CodeGen enforces the "universally unique" aspect by giving all
5475 // declarations semantically contained within an anonymous
5476 // namespace internal linkage.
5477
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005478 if (!PrevNS) {
John McCall5fdd7642009-12-16 02:06:49 +00005479 UsingDirectiveDecl* UD
5480 = UsingDirectiveDecl::Create(Context, CurContext,
5481 /* 'using' */ LBrace,
5482 /* 'namespace' */ SourceLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00005483 /* qualifier */ NestedNameSpecifierLoc(),
John McCall5fdd7642009-12-16 02:06:49 +00005484 /* identifier */ SourceLocation(),
5485 Namespc,
5486 /* Ancestor */ CurContext);
5487 UD->setImplicit();
5488 CurContext->addDecl(UD);
5489 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005490 }
5491
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00005492 ActOnDocumentableDecl(Namespc);
5493
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005494 // Although we could have an invalid decl (i.e. the namespace name is a
5495 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00005496 // FIXME: We should be able to push Namespc here, so that the each DeclContext
5497 // for the namespace has the declarations that showed up in that particular
5498 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00005499 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00005500 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005501}
5502
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005503/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
5504/// is a namespace alias, returns the namespace it points to.
5505static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
5506 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
5507 return AD->getNamespace();
5508 return dyn_cast_or_null<NamespaceDecl>(D);
5509}
5510
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005511/// ActOnFinishNamespaceDef - This callback is called after a namespace is
5512/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00005513void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005514 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
5515 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005516 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005517 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00005518 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00005519 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005520}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005521
John McCall384aff82010-08-25 07:42:41 +00005522CXXRecordDecl *Sema::getStdBadAlloc() const {
5523 return cast_or_null<CXXRecordDecl>(
5524 StdBadAlloc.get(Context.getExternalSource()));
5525}
5526
5527NamespaceDecl *Sema::getStdNamespace() const {
5528 return cast_or_null<NamespaceDecl>(
5529 StdNamespace.get(Context.getExternalSource()));
5530}
5531
Douglas Gregor66992202010-06-29 17:53:46 +00005532/// \brief Retrieve the special "std" namespace, which may require us to
5533/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00005534NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00005535 if (!StdNamespace) {
5536 // The "std" namespace has not yet been defined, so build one implicitly.
5537 StdNamespace = NamespaceDecl::Create(Context,
5538 Context.getTranslationUnitDecl(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005539 /*Inline=*/false,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005540 SourceLocation(), SourceLocation(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005541 &PP.getIdentifierTable().get("std"),
5542 /*PrevDecl=*/0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00005543 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00005544 }
5545
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00005546 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00005547}
5548
Sebastian Redl395e04d2012-01-17 22:49:33 +00005549bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikie4e4d0842012-03-11 07:00:24 +00005550 assert(getLangOpts().CPlusPlus &&
Sebastian Redl395e04d2012-01-17 22:49:33 +00005551 "Looking for std::initializer_list outside of C++.");
5552
5553 // We're looking for implicit instantiations of
5554 // template <typename E> class std::initializer_list.
5555
5556 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
5557 return false;
5558
Sebastian Redl84760e32012-01-17 22:49:58 +00005559 ClassTemplateDecl *Template = 0;
5560 const TemplateArgument *Arguments = 0;
Sebastian Redl395e04d2012-01-17 22:49:33 +00005561
Sebastian Redl84760e32012-01-17 22:49:58 +00005562 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl395e04d2012-01-17 22:49:33 +00005563
Sebastian Redl84760e32012-01-17 22:49:58 +00005564 ClassTemplateSpecializationDecl *Specialization =
5565 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
5566 if (!Specialization)
5567 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00005568
Sebastian Redl84760e32012-01-17 22:49:58 +00005569 Template = Specialization->getSpecializedTemplate();
5570 Arguments = Specialization->getTemplateArgs().data();
5571 } else if (const TemplateSpecializationType *TST =
5572 Ty->getAs<TemplateSpecializationType>()) {
5573 Template = dyn_cast_or_null<ClassTemplateDecl>(
5574 TST->getTemplateName().getAsTemplateDecl());
5575 Arguments = TST->getArgs();
5576 }
5577 if (!Template)
5578 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00005579
5580 if (!StdInitializerList) {
5581 // Haven't recognized std::initializer_list yet, maybe this is it.
5582 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
5583 if (TemplateClass->getIdentifier() !=
5584 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redlb832f6d2012-01-23 22:09:39 +00005585 !getStdNamespace()->InEnclosingNamespaceSetOf(
5586 TemplateClass->getDeclContext()))
Sebastian Redl395e04d2012-01-17 22:49:33 +00005587 return false;
5588 // This is a template called std::initializer_list, but is it the right
5589 // template?
5590 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00005591 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl395e04d2012-01-17 22:49:33 +00005592 return false;
5593 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
5594 return false;
5595
5596 // It's the right template.
5597 StdInitializerList = Template;
5598 }
5599
5600 if (Template != StdInitializerList)
5601 return false;
5602
5603 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl84760e32012-01-17 22:49:58 +00005604 if (Element)
5605 *Element = Arguments[0].getAsType();
Sebastian Redl395e04d2012-01-17 22:49:33 +00005606 return true;
5607}
5608
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00005609static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
5610 NamespaceDecl *Std = S.getStdNamespace();
5611 if (!Std) {
5612 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
5613 return 0;
5614 }
5615
5616 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
5617 Loc, Sema::LookupOrdinaryName);
5618 if (!S.LookupQualifiedName(Result, Std)) {
5619 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
5620 return 0;
5621 }
5622 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
5623 if (!Template) {
5624 Result.suppressDiagnostics();
5625 // We found something weird. Complain about the first thing we found.
5626 NamedDecl *Found = *Result.begin();
5627 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
5628 return 0;
5629 }
5630
5631 // We found some template called std::initializer_list. Now verify that it's
5632 // correct.
5633 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00005634 if (Params->getMinRequiredArguments() != 1 ||
5635 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00005636 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
5637 return 0;
5638 }
5639
5640 return Template;
5641}
5642
5643QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
5644 if (!StdInitializerList) {
5645 StdInitializerList = LookupStdInitializerList(*this, Loc);
5646 if (!StdInitializerList)
5647 return QualType();
5648 }
5649
5650 TemplateArgumentListInfo Args(Loc, Loc);
5651 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
5652 Context.getTrivialTypeSourceInfo(Element,
5653 Loc)));
5654 return Context.getCanonicalType(
5655 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
5656}
5657
Sebastian Redl98d36062012-01-17 22:50:14 +00005658bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
5659 // C++ [dcl.init.list]p2:
5660 // A constructor is an initializer-list constructor if its first parameter
5661 // is of type std::initializer_list<E> or reference to possibly cv-qualified
5662 // std::initializer_list<E> for some type E, and either there are no other
5663 // parameters or else all other parameters have default arguments.
5664 if (Ctor->getNumParams() < 1 ||
5665 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
5666 return false;
5667
5668 QualType ArgType = Ctor->getParamDecl(0)->getType();
5669 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
5670 ArgType = RT->getPointeeType().getUnqualifiedType();
5671
5672 return isStdInitializerList(ArgType, 0);
5673}
5674
Douglas Gregor9172aa62011-03-26 22:25:30 +00005675/// \brief Determine whether a using statement is in a context where it will be
5676/// apply in all contexts.
5677static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
5678 switch (CurContext->getDeclKind()) {
5679 case Decl::TranslationUnit:
5680 return true;
5681 case Decl::LinkageSpec:
5682 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
5683 default:
5684 return false;
5685 }
5686}
5687
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005688namespace {
5689
5690// Callback to only accept typo corrections that are namespaces.
5691class NamespaceValidatorCCC : public CorrectionCandidateCallback {
5692 public:
5693 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
5694 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
5695 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
5696 }
5697 return false;
5698 }
5699};
5700
5701}
5702
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005703static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
5704 CXXScopeSpec &SS,
5705 SourceLocation IdentLoc,
5706 IdentifierInfo *Ident) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005707 NamespaceValidatorCCC Validator;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005708 R.clear();
5709 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005710 R.getLookupKind(), Sc, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00005711 Validator)) {
David Blaikie4e4d0842012-03-11 07:00:24 +00005712 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
5713 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOpts()));
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005714 if (DeclContext *DC = S.computeDeclContext(SS, false))
5715 S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
5716 << Ident << DC << CorrectedQuotedStr << SS.getRange()
5717 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
5718 else
5719 S.Diag(IdentLoc, diag::err_using_directive_suggest)
5720 << Ident << CorrectedQuotedStr
5721 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005722
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005723 S.Diag(Corrected.getCorrectionDecl()->getLocation(),
5724 diag::note_namespace_defined_here) << CorrectedQuotedStr;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005725
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005726 R.addDecl(Corrected.getCorrectionDecl());
5727 return true;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005728 }
5729 return false;
5730}
5731
John McCalld226f652010-08-21 09:40:31 +00005732Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005733 SourceLocation UsingLoc,
5734 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00005735 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005736 SourceLocation IdentLoc,
5737 IdentifierInfo *NamespcName,
5738 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00005739 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
5740 assert(NamespcName && "Invalid NamespcName.");
5741 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00005742
5743 // This can only happen along a recovery path.
5744 while (S->getFlags() & Scope::TemplateParamScope)
5745 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005746 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00005747
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005748 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00005749 NestedNameSpecifier *Qualifier = 0;
5750 if (SS.isSet())
5751 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5752
Douglas Gregoreb11cd02009-01-14 22:20:51 +00005753 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00005754 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
5755 LookupParsedName(R, S, &SS);
5756 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00005757 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00005758
Douglas Gregor66992202010-06-29 17:53:46 +00005759 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005760 R.clear();
Douglas Gregor66992202010-06-29 17:53:46 +00005761 // Allow "using namespace std;" or "using namespace ::std;" even if
5762 // "std" hasn't been defined yet, for GCC compatibility.
5763 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
5764 NamespcName->isStr("std")) {
5765 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00005766 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00005767 R.resolveKind();
5768 }
5769 // Otherwise, attempt typo correction.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005770 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00005771 }
5772
John McCallf36e02d2009-10-09 21:13:30 +00005773 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005774 NamedDecl *Named = R.getFoundDecl();
5775 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
5776 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005777 // C++ [namespace.udir]p1:
5778 // A using-directive specifies that the names in the nominated
5779 // namespace can be used in the scope in which the
5780 // using-directive appears after the using-directive. During
5781 // unqualified name lookup (3.4.1), the names appear as if they
5782 // were declared in the nearest enclosing namespace which
5783 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00005784 // namespace. [Note: in this context, "contains" means "contains
5785 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005786
5787 // Find enclosing context containing both using-directive and
5788 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005789 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005790 DeclContext *CommonAncestor = cast<DeclContext>(NS);
5791 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
5792 CommonAncestor = CommonAncestor->getParent();
5793
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005794 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregordb992412011-02-25 16:33:46 +00005795 SS.getWithLocInContext(Context),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005796 IdentLoc, Named, CommonAncestor);
Douglas Gregord6a49bb2011-03-18 16:10:52 +00005797
Douglas Gregor9172aa62011-03-26 22:25:30 +00005798 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Chandler Carruth40278532011-07-25 16:49:02 +00005799 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregord6a49bb2011-03-18 16:10:52 +00005800 Diag(IdentLoc, diag::warn_using_directive_in_header);
5801 }
5802
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005803 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00005804 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00005805 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00005806 }
5807
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005808 // FIXME: We ignore attributes for now.
John McCalld226f652010-08-21 09:40:31 +00005809 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005810}
5811
5812void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith1b7f9cb2012-03-13 03:12:56 +00005813 // If the scope has an associated entity and the using directive is at
5814 // namespace or translation unit scope, add the UsingDirectiveDecl into
5815 // its lookup structure so qualified name lookup can find it.
5816 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
5817 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005818 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005819 else
Richard Smith1b7f9cb2012-03-13 03:12:56 +00005820 // Otherwise, it is at block sope. The using-directives will affect lookup
5821 // only to the end of the scope.
John McCalld226f652010-08-21 09:40:31 +00005822 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00005823}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005824
Douglas Gregor9cfbe482009-06-20 00:51:54 +00005825
John McCalld226f652010-08-21 09:40:31 +00005826Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00005827 AccessSpecifier AS,
5828 bool HasUsingKeyword,
5829 SourceLocation UsingLoc,
5830 CXXScopeSpec &SS,
5831 UnqualifiedId &Name,
5832 AttributeList *AttrList,
5833 bool IsTypeName,
5834 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00005835 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00005836
Douglas Gregor12c118a2009-11-04 16:30:06 +00005837 switch (Name.getKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00005838 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor12c118a2009-11-04 16:30:06 +00005839 case UnqualifiedId::IK_Identifier:
5840 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00005841 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00005842 case UnqualifiedId::IK_ConversionFunctionId:
5843 break;
5844
5845 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00005846 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smitha1366cb2012-04-27 19:33:05 +00005847 // C++11 inheriting constructors.
Daniel Dunbar96a00142012-03-09 18:35:03 +00005848 Diag(Name.getLocStart(),
David Blaikie4e4d0842012-03-11 07:00:24 +00005849 getLangOpts().CPlusPlus0x ?
Richard Smitha1366cb2012-04-27 19:33:05 +00005850 // FIXME: Produce warn_cxx98_compat_using_decl_constructor
5851 // instead once inheriting constructors work.
5852 diag::err_using_decl_constructor_unsupported :
Richard Smithebaf0e62011-10-18 20:49:44 +00005853 diag::err_using_decl_constructor)
5854 << SS.getRange();
5855
David Blaikie4e4d0842012-03-11 07:00:24 +00005856 if (getLangOpts().CPlusPlus0x) break;
John McCall604e7f12009-12-08 07:46:18 +00005857
John McCalld226f652010-08-21 09:40:31 +00005858 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00005859
5860 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar96a00142012-03-09 18:35:03 +00005861 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor12c118a2009-11-04 16:30:06 +00005862 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00005863 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00005864
5865 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar96a00142012-03-09 18:35:03 +00005866 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor12c118a2009-11-04 16:30:06 +00005867 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00005868 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00005869 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005870
5871 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
5872 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00005873 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00005874 return 0;
John McCall604e7f12009-12-08 07:46:18 +00005875
John McCall60fa3cf2009-12-11 02:10:03 +00005876 // Warn about using declarations.
5877 // TODO: store that the declaration was written without 'using' and
5878 // talk about access decls instead of using decls in the
5879 // diagnostics.
5880 if (!HasUsingKeyword) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00005881 UsingLoc = Name.getLocStart();
John McCall60fa3cf2009-12-11 02:10:03 +00005882
5883 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00005884 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00005885 }
5886
Douglas Gregor56c04582010-12-16 00:46:58 +00005887 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
5888 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
5889 return 0;
5890
John McCall9488ea12009-11-17 05:59:44 +00005891 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005892 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00005893 /* IsInstantiation */ false,
5894 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00005895 if (UD)
5896 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00005897
John McCalld226f652010-08-21 09:40:31 +00005898 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00005899}
5900
Douglas Gregor09acc982010-07-07 23:08:52 +00005901/// \brief Determine whether a using declaration considers the given
5902/// declarations as "equivalent", e.g., if they are redeclarations of
5903/// the same entity or are both typedefs of the same type.
5904static bool
5905IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
5906 bool &SuppressRedeclaration) {
5907 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
5908 SuppressRedeclaration = false;
5909 return true;
5910 }
5911
Richard Smith162e1c12011-04-15 14:24:37 +00005912 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
5913 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor09acc982010-07-07 23:08:52 +00005914 SuppressRedeclaration = true;
5915 return Context.hasSameType(TD1->getUnderlyingType(),
5916 TD2->getUnderlyingType());
5917 }
5918
5919 return false;
5920}
5921
5922
John McCall9f54ad42009-12-10 09:41:52 +00005923/// Determines whether to create a using shadow decl for a particular
5924/// decl, given the set of decls existing prior to this using lookup.
5925bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
5926 const LookupResult &Previous) {
5927 // Diagnose finding a decl which is not from a base class of the
5928 // current class. We do this now because there are cases where this
5929 // function will silently decide not to build a shadow decl, which
5930 // will pre-empt further diagnostics.
5931 //
5932 // We don't need to do this in C++0x because we do the check once on
5933 // the qualifier.
5934 //
5935 // FIXME: diagnose the following if we care enough:
5936 // struct A { int foo; };
5937 // struct B : A { using A::foo; };
5938 // template <class T> struct C : A {};
5939 // template <class T> struct D : C<T> { using B::foo; } // <---
5940 // This is invalid (during instantiation) in C++03 because B::foo
5941 // resolves to the using decl in B, which is not a base class of D<T>.
5942 // We can't diagnose it immediately because C<T> is an unknown
5943 // specialization. The UsingShadowDecl in D<T> then points directly
5944 // to A::foo, which will look well-formed when we instantiate.
5945 // The right solution is to not collapse the shadow-decl chain.
David Blaikie4e4d0842012-03-11 07:00:24 +00005946 if (!getLangOpts().CPlusPlus0x && CurContext->isRecord()) {
John McCall9f54ad42009-12-10 09:41:52 +00005947 DeclContext *OrigDC = Orig->getDeclContext();
5948
5949 // Handle enums and anonymous structs.
5950 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
5951 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
5952 while (OrigRec->isAnonymousStructOrUnion())
5953 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
5954
5955 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
5956 if (OrigDC == CurContext) {
5957 Diag(Using->getLocation(),
5958 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregordc355712011-02-25 00:36:19 +00005959 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00005960 Diag(Orig->getLocation(), diag::note_using_decl_target);
5961 return true;
5962 }
5963
Douglas Gregordc355712011-02-25 00:36:19 +00005964 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall9f54ad42009-12-10 09:41:52 +00005965 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregordc355712011-02-25 00:36:19 +00005966 << Using->getQualifier()
John McCall9f54ad42009-12-10 09:41:52 +00005967 << cast<CXXRecordDecl>(CurContext)
Douglas Gregordc355712011-02-25 00:36:19 +00005968 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00005969 Diag(Orig->getLocation(), diag::note_using_decl_target);
5970 return true;
5971 }
5972 }
5973
5974 if (Previous.empty()) return false;
5975
5976 NamedDecl *Target = Orig;
5977 if (isa<UsingShadowDecl>(Target))
5978 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
5979
John McCalld7533ec2009-12-11 02:33:26 +00005980 // If the target happens to be one of the previous declarations, we
5981 // don't have a conflict.
5982 //
5983 // FIXME: but we might be increasing its access, in which case we
5984 // should redeclare it.
5985 NamedDecl *NonTag = 0, *Tag = 0;
5986 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
5987 I != E; ++I) {
5988 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00005989 bool Result;
5990 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
5991 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00005992
5993 (isa<TagDecl>(D) ? Tag : NonTag) = D;
5994 }
5995
John McCall9f54ad42009-12-10 09:41:52 +00005996 if (Target->isFunctionOrFunctionTemplate()) {
5997 FunctionDecl *FD;
5998 if (isa<FunctionTemplateDecl>(Target))
5999 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
6000 else
6001 FD = cast<FunctionDecl>(Target);
6002
6003 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00006004 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00006005 case Ovl_Overload:
6006 return false;
6007
6008 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00006009 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006010 break;
6011
6012 // We found a decl with the exact signature.
6013 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00006014 // If we're in a record, we want to hide the target, so we
6015 // return true (without a diagnostic) to tell the caller not to
6016 // build a shadow decl.
6017 if (CurContext->isRecord())
6018 return true;
6019
6020 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00006021 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006022 break;
6023 }
6024
6025 Diag(Target->getLocation(), diag::note_using_decl_target);
6026 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
6027 return true;
6028 }
6029
6030 // Target is not a function.
6031
John McCall9f54ad42009-12-10 09:41:52 +00006032 if (isa<TagDecl>(Target)) {
6033 // No conflict between a tag and a non-tag.
6034 if (!Tag) return false;
6035
John McCall41ce66f2009-12-10 19:51:03 +00006036 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006037 Diag(Target->getLocation(), diag::note_using_decl_target);
6038 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
6039 return true;
6040 }
6041
6042 // No conflict between a tag and a non-tag.
6043 if (!NonTag) return false;
6044
John McCall41ce66f2009-12-10 19:51:03 +00006045 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006046 Diag(Target->getLocation(), diag::note_using_decl_target);
6047 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
6048 return true;
6049}
6050
John McCall9488ea12009-11-17 05:59:44 +00006051/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00006052UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00006053 UsingDecl *UD,
6054 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00006055
6056 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00006057 NamedDecl *Target = Orig;
6058 if (isa<UsingShadowDecl>(Target)) {
6059 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6060 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00006061 }
6062
6063 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00006064 = UsingShadowDecl::Create(Context, CurContext,
6065 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00006066 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00006067
6068 Shadow->setAccess(UD->getAccess());
6069 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
6070 Shadow->setInvalidDecl();
6071
John McCall9488ea12009-11-17 05:59:44 +00006072 if (S)
John McCall604e7f12009-12-08 07:46:18 +00006073 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00006074 else
John McCall604e7f12009-12-08 07:46:18 +00006075 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00006076
John McCall604e7f12009-12-08 07:46:18 +00006077
John McCall9f54ad42009-12-10 09:41:52 +00006078 return Shadow;
6079}
John McCall604e7f12009-12-08 07:46:18 +00006080
John McCall9f54ad42009-12-10 09:41:52 +00006081/// Hides a using shadow declaration. This is required by the current
6082/// using-decl implementation when a resolvable using declaration in a
6083/// class is followed by a declaration which would hide or override
6084/// one or more of the using decl's targets; for example:
6085///
6086/// struct Base { void foo(int); };
6087/// struct Derived : Base {
6088/// using Base::foo;
6089/// void foo(int);
6090/// };
6091///
6092/// The governing language is C++03 [namespace.udecl]p12:
6093///
6094/// When a using-declaration brings names from a base class into a
6095/// derived class scope, member functions in the derived class
6096/// override and/or hide member functions with the same name and
6097/// parameter types in a base class (rather than conflicting).
6098///
6099/// There are two ways to implement this:
6100/// (1) optimistically create shadow decls when they're not hidden
6101/// by existing declarations, or
6102/// (2) don't create any shadow decls (or at least don't make them
6103/// visible) until we've fully parsed/instantiated the class.
6104/// The problem with (1) is that we might have to retroactively remove
6105/// a shadow decl, which requires several O(n) operations because the
6106/// decl structures are (very reasonably) not designed for removal.
6107/// (2) avoids this but is very fiddly and phase-dependent.
6108void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00006109 if (Shadow->getDeclName().getNameKind() ==
6110 DeclarationName::CXXConversionFunctionName)
6111 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
6112
John McCall9f54ad42009-12-10 09:41:52 +00006113 // Remove it from the DeclContext...
6114 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006115
John McCall9f54ad42009-12-10 09:41:52 +00006116 // ...and the scope, if applicable...
6117 if (S) {
John McCalld226f652010-08-21 09:40:31 +00006118 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00006119 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006120 }
6121
John McCall9f54ad42009-12-10 09:41:52 +00006122 // ...and the using decl.
6123 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
6124
6125 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00006126 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00006127}
6128
John McCall7ba107a2009-11-18 02:36:19 +00006129/// Builds a using declaration.
6130///
6131/// \param IsInstantiation - Whether this call arises from an
6132/// instantiation of an unresolved using declaration. We treat
6133/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00006134NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
6135 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006136 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006137 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00006138 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006139 bool IsInstantiation,
6140 bool IsTypeName,
6141 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00006142 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006143 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00006144 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00006145
Anders Carlsson550b14b2009-08-28 05:49:21 +00006146 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00006147
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006148 if (SS.isEmpty()) {
6149 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00006150 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006151 }
Mike Stump1eb44332009-09-09 15:08:12 +00006152
John McCall9f54ad42009-12-10 09:41:52 +00006153 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006154 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00006155 ForRedeclaration);
6156 Previous.setHideTags(false);
6157 if (S) {
6158 LookupName(Previous, S);
6159
6160 // It is really dumb that we have to do this.
6161 LookupResult::Filter F = Previous.makeFilter();
6162 while (F.hasNext()) {
6163 NamedDecl *D = F.next();
6164 if (!isDeclInScope(D, CurContext, S))
6165 F.erase();
6166 }
6167 F.done();
6168 } else {
6169 assert(IsInstantiation && "no scope in non-instantiation");
6170 assert(CurContext->isRecord() && "scope not record in instantiation");
6171 LookupQualifiedName(Previous, CurContext);
6172 }
6173
John McCall9f54ad42009-12-10 09:41:52 +00006174 // Check for invalid redeclarations.
6175 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
6176 return 0;
6177
6178 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00006179 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
6180 return 0;
6181
John McCallaf8e6ed2009-11-12 03:15:40 +00006182 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00006183 NamedDecl *D;
Douglas Gregordc355712011-02-25 00:36:19 +00006184 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallaf8e6ed2009-11-12 03:15:40 +00006185 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00006186 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00006187 // FIXME: not all declaration name kinds are legal here
6188 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
6189 UsingLoc, TypenameLoc,
Douglas Gregordc355712011-02-25 00:36:19 +00006190 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006191 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00006192 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00006193 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
6194 QualifierLoc, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00006195 }
John McCalled976492009-12-04 22:46:56 +00006196 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00006197 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
6198 NameInfo, IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00006199 }
John McCalled976492009-12-04 22:46:56 +00006200 D->setAccess(AS);
6201 CurContext->addDecl(D);
6202
6203 if (!LookupContext) return D;
6204 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00006205
John McCall77bb1aa2010-05-01 00:40:08 +00006206 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00006207 UD->setInvalidDecl();
6208 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006209 }
6210
Richard Smithc5a89a12012-04-02 01:30:27 +00006211 // The normal rules do not apply to inheriting constructor declarations.
Sebastian Redlf677ea32011-02-05 19:23:19 +00006212 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Richard Smithc5a89a12012-04-02 01:30:27 +00006213 if (CheckInheritingConstructorUsingDecl(UD))
Sebastian Redlcaa35e42011-03-12 13:44:32 +00006214 UD->setInvalidDecl();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006215 return UD;
6216 }
6217
6218 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00006219
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006220 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00006221
John McCall604e7f12009-12-08 07:46:18 +00006222 // Unlike most lookups, we don't always want to hide tag
6223 // declarations: tag names are visible through the using declaration
6224 // even if hidden by ordinary names, *except* in a dependent context
6225 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00006226 if (!IsInstantiation)
6227 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00006228
John McCallb9abd8722012-04-07 03:04:20 +00006229 // For the purposes of this lookup, we have a base object type
6230 // equal to that of the current context.
6231 if (CurContext->isRecord()) {
6232 R.setBaseObjectType(
6233 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
6234 }
6235
John McCalla24dc2e2009-11-17 02:14:36 +00006236 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00006237
John McCallf36e02d2009-10-09 21:13:30 +00006238 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00006239 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006240 << NameInfo.getName() << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00006241 UD->setInvalidDecl();
6242 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006243 }
6244
John McCalled976492009-12-04 22:46:56 +00006245 if (R.isAmbiguous()) {
6246 UD->setInvalidDecl();
6247 return UD;
6248 }
Mike Stump1eb44332009-09-09 15:08:12 +00006249
John McCall7ba107a2009-11-18 02:36:19 +00006250 if (IsTypeName) {
6251 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00006252 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00006253 Diag(IdentLoc, diag::err_using_typename_non_type);
6254 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
6255 Diag((*I)->getUnderlyingDecl()->getLocation(),
6256 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006257 UD->setInvalidDecl();
6258 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00006259 }
6260 } else {
6261 // If we asked for a non-typename and we got a type, error out,
6262 // but only if this is an instantiation of an unresolved using
6263 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00006264 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00006265 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
6266 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006267 UD->setInvalidDecl();
6268 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00006269 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006270 }
6271
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006272 // C++0x N2914 [namespace.udecl]p6:
6273 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00006274 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006275 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
6276 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00006277 UD->setInvalidDecl();
6278 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006279 }
Mike Stump1eb44332009-09-09 15:08:12 +00006280
John McCall9f54ad42009-12-10 09:41:52 +00006281 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
6282 if (!CheckUsingShadowDecl(UD, *I, Previous))
6283 BuildUsingShadowDecl(S, UD, *I);
6284 }
John McCall9488ea12009-11-17 05:59:44 +00006285
6286 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006287}
6288
Sebastian Redlf677ea32011-02-05 19:23:19 +00006289/// Additional checks for a using declaration referring to a constructor name.
Richard Smithc5a89a12012-04-02 01:30:27 +00006290bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
6291 assert(!UD->isTypeName() && "expecting a constructor name");
Sebastian Redlf677ea32011-02-05 19:23:19 +00006292
Douglas Gregordc355712011-02-25 00:36:19 +00006293 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006294 assert(SourceType &&
6295 "Using decl naming constructor doesn't have type in scope spec.");
6296 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
6297
6298 // Check whether the named type is a direct base class.
6299 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
6300 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
6301 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
6302 BaseIt != BaseE; ++BaseIt) {
6303 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
6304 if (CanonicalSourceType == BaseType)
6305 break;
Richard Smithc5a89a12012-04-02 01:30:27 +00006306 if (BaseIt->getType()->isDependentType())
6307 break;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006308 }
6309
6310 if (BaseIt == BaseE) {
6311 // Did not find SourceType in the bases.
6312 Diag(UD->getUsingLocation(),
6313 diag::err_using_decl_constructor_not_in_direct_base)
6314 << UD->getNameInfo().getSourceRange()
6315 << QualType(SourceType, 0) << TargetClass;
6316 return true;
6317 }
6318
Richard Smithc5a89a12012-04-02 01:30:27 +00006319 if (!CurContext->isDependentContext())
6320 BaseIt->setInheritConstructors();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006321
6322 return false;
6323}
6324
John McCall9f54ad42009-12-10 09:41:52 +00006325/// Checks that the given using declaration is not an invalid
6326/// redeclaration. Note that this is checking only for the using decl
6327/// itself, not for any ill-formedness among the UsingShadowDecls.
6328bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
6329 bool isTypeName,
6330 const CXXScopeSpec &SS,
6331 SourceLocation NameLoc,
6332 const LookupResult &Prev) {
6333 // C++03 [namespace.udecl]p8:
6334 // C++0x [namespace.udecl]p10:
6335 // A using-declaration is a declaration and can therefore be used
6336 // repeatedly where (and only where) multiple declarations are
6337 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00006338 //
John McCall8a726212010-11-29 18:01:58 +00006339 // That's in non-member contexts.
6340 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00006341 return false;
6342
6343 NestedNameSpecifier *Qual
6344 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
6345
6346 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
6347 NamedDecl *D = *I;
6348
6349 bool DTypename;
6350 NestedNameSpecifier *DQual;
6351 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
6352 DTypename = UD->isTypeName();
Douglas Gregordc355712011-02-25 00:36:19 +00006353 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006354 } else if (UnresolvedUsingValueDecl *UD
6355 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
6356 DTypename = false;
Douglas Gregordc355712011-02-25 00:36:19 +00006357 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006358 } else if (UnresolvedUsingTypenameDecl *UD
6359 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
6360 DTypename = true;
Douglas Gregordc355712011-02-25 00:36:19 +00006361 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006362 } else continue;
6363
6364 // using decls differ if one says 'typename' and the other doesn't.
6365 // FIXME: non-dependent using decls?
6366 if (isTypeName != DTypename) continue;
6367
6368 // using decls differ if they name different scopes (but note that
6369 // template instantiation can cause this check to trigger when it
6370 // didn't before instantiation).
6371 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
6372 Context.getCanonicalNestedNameSpecifier(DQual))
6373 continue;
6374
6375 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00006376 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00006377 return true;
6378 }
6379
6380 return false;
6381}
6382
John McCall604e7f12009-12-08 07:46:18 +00006383
John McCalled976492009-12-04 22:46:56 +00006384/// Checks that the given nested-name qualifier used in a using decl
6385/// in the current context is appropriately related to the current
6386/// scope. If an error is found, diagnoses it and returns true.
6387bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
6388 const CXXScopeSpec &SS,
6389 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00006390 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00006391
John McCall604e7f12009-12-08 07:46:18 +00006392 if (!CurContext->isRecord()) {
6393 // C++03 [namespace.udecl]p3:
6394 // C++0x [namespace.udecl]p8:
6395 // A using-declaration for a class member shall be a member-declaration.
6396
6397 // If we weren't able to compute a valid scope, it must be a
6398 // dependent class scope.
6399 if (!NamedContext || NamedContext->isRecord()) {
6400 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
6401 << SS.getRange();
6402 return true;
6403 }
6404
6405 // Otherwise, everything is known to be fine.
6406 return false;
6407 }
6408
6409 // The current scope is a record.
6410
6411 // If the named context is dependent, we can't decide much.
6412 if (!NamedContext) {
6413 // FIXME: in C++0x, we can diagnose if we can prove that the
6414 // nested-name-specifier does not refer to a base class, which is
6415 // still possible in some cases.
6416
6417 // Otherwise we have to conservatively report that things might be
6418 // okay.
6419 return false;
6420 }
6421
6422 if (!NamedContext->isRecord()) {
6423 // Ideally this would point at the last name in the specifier,
6424 // but we don't have that level of source info.
6425 Diag(SS.getRange().getBegin(),
6426 diag::err_using_decl_nested_name_specifier_is_not_class)
6427 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
6428 return true;
6429 }
6430
Douglas Gregor6fb07292010-12-21 07:41:49 +00006431 if (!NamedContext->isDependentContext() &&
6432 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
6433 return true;
6434
David Blaikie4e4d0842012-03-11 07:00:24 +00006435 if (getLangOpts().CPlusPlus0x) {
John McCall604e7f12009-12-08 07:46:18 +00006436 // C++0x [namespace.udecl]p3:
6437 // In a using-declaration used as a member-declaration, the
6438 // nested-name-specifier shall name a base class of the class
6439 // being defined.
6440
6441 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
6442 cast<CXXRecordDecl>(NamedContext))) {
6443 if (CurContext == NamedContext) {
6444 Diag(NameLoc,
6445 diag::err_using_decl_nested_name_specifier_is_current_class)
6446 << SS.getRange();
6447 return true;
6448 }
6449
6450 Diag(SS.getRange().getBegin(),
6451 diag::err_using_decl_nested_name_specifier_is_not_base_class)
6452 << (NestedNameSpecifier*) SS.getScopeRep()
6453 << cast<CXXRecordDecl>(CurContext)
6454 << SS.getRange();
6455 return true;
6456 }
6457
6458 return false;
6459 }
6460
6461 // C++03 [namespace.udecl]p4:
6462 // A using-declaration used as a member-declaration shall refer
6463 // to a member of a base class of the class being defined [etc.].
6464
6465 // Salient point: SS doesn't have to name a base class as long as
6466 // lookup only finds members from base classes. Therefore we can
6467 // diagnose here only if we can prove that that can't happen,
6468 // i.e. if the class hierarchies provably don't intersect.
6469
6470 // TODO: it would be nice if "definitely valid" results were cached
6471 // in the UsingDecl and UsingShadowDecl so that these checks didn't
6472 // need to be repeated.
6473
6474 struct UserData {
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00006475 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
John McCall604e7f12009-12-08 07:46:18 +00006476
6477 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
6478 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6479 Data->Bases.insert(Base);
6480 return true;
6481 }
6482
6483 bool hasDependentBases(const CXXRecordDecl *Class) {
6484 return !Class->forallBases(collect, this);
6485 }
6486
6487 /// Returns true if the base is dependent or is one of the
6488 /// accumulated base classes.
6489 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
6490 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6491 return !Data->Bases.count(Base);
6492 }
6493
6494 bool mightShareBases(const CXXRecordDecl *Class) {
6495 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
6496 }
6497 };
6498
6499 UserData Data;
6500
6501 // Returns false if we find a dependent base.
6502 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
6503 return false;
6504
6505 // Returns false if the class has a dependent base or if it or one
6506 // of its bases is present in the base set of the current context.
6507 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
6508 return false;
6509
6510 Diag(SS.getRange().getBegin(),
6511 diag::err_using_decl_nested_name_specifier_is_not_base_class)
6512 << (NestedNameSpecifier*) SS.getScopeRep()
6513 << cast<CXXRecordDecl>(CurContext)
6514 << SS.getRange();
6515
6516 return true;
John McCalled976492009-12-04 22:46:56 +00006517}
6518
Richard Smith162e1c12011-04-15 14:24:37 +00006519Decl *Sema::ActOnAliasDeclaration(Scope *S,
6520 AccessSpecifier AS,
Richard Smith3e4c6c42011-05-05 21:57:07 +00006521 MultiTemplateParamsArg TemplateParamLists,
Richard Smith162e1c12011-04-15 14:24:37 +00006522 SourceLocation UsingLoc,
6523 UnqualifiedId &Name,
6524 TypeResult Type) {
Richard Smith3e4c6c42011-05-05 21:57:07 +00006525 // Skip up to the relevant declaration scope.
6526 while (S->getFlags() & Scope::TemplateParamScope)
6527 S = S->getParent();
Richard Smith162e1c12011-04-15 14:24:37 +00006528 assert((S->getFlags() & Scope::DeclScope) &&
6529 "got alias-declaration outside of declaration scope");
6530
6531 if (Type.isInvalid())
6532 return 0;
6533
6534 bool Invalid = false;
6535 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
6536 TypeSourceInfo *TInfo = 0;
Nick Lewyckyb79bf1d2011-05-02 01:07:19 +00006537 GetTypeFromParser(Type.get(), &TInfo);
Richard Smith162e1c12011-04-15 14:24:37 +00006538
6539 if (DiagnoseClassNameShadow(CurContext, NameInfo))
6540 return 0;
6541
6542 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3e4c6c42011-05-05 21:57:07 +00006543 UPPC_DeclarationType)) {
Richard Smith162e1c12011-04-15 14:24:37 +00006544 Invalid = true;
Richard Smith3e4c6c42011-05-05 21:57:07 +00006545 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
6546 TInfo->getTypeLoc().getBeginLoc());
6547 }
Richard Smith162e1c12011-04-15 14:24:37 +00006548
6549 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
6550 LookupName(Previous, S);
6551
6552 // Warn about shadowing the name of a template parameter.
6553 if (Previous.isSingleResult() &&
6554 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorcb8f9512011-10-20 17:58:49 +00006555 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smith162e1c12011-04-15 14:24:37 +00006556 Previous.clear();
6557 }
6558
6559 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
6560 "name in alias declaration must be an identifier");
6561 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
6562 Name.StartLocation,
6563 Name.Identifier, TInfo);
6564
6565 NewTD->setAccess(AS);
6566
6567 if (Invalid)
6568 NewTD->setInvalidDecl();
6569
Richard Smith3e4c6c42011-05-05 21:57:07 +00006570 CheckTypedefForVariablyModifiedType(S, NewTD);
6571 Invalid |= NewTD->isInvalidDecl();
6572
Richard Smith162e1c12011-04-15 14:24:37 +00006573 bool Redeclaration = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00006574
6575 NamedDecl *NewND;
6576 if (TemplateParamLists.size()) {
6577 TypeAliasTemplateDecl *OldDecl = 0;
6578 TemplateParameterList *OldTemplateParams = 0;
6579
6580 if (TemplateParamLists.size() != 1) {
6581 Diag(UsingLoc, diag::err_alias_template_extra_headers)
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00006582 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
6583 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
Richard Smith3e4c6c42011-05-05 21:57:07 +00006584 }
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00006585 TemplateParameterList *TemplateParams = TemplateParamLists[0];
Richard Smith3e4c6c42011-05-05 21:57:07 +00006586
6587 // Only consider previous declarations in the same scope.
6588 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
6589 /*ExplicitInstantiationOrSpecialization*/false);
6590 if (!Previous.empty()) {
6591 Redeclaration = true;
6592
6593 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
6594 if (!OldDecl && !Invalid) {
6595 Diag(UsingLoc, diag::err_redefinition_different_kind)
6596 << Name.Identifier;
6597
6598 NamedDecl *OldD = Previous.getRepresentativeDecl();
6599 if (OldD->getLocation().isValid())
6600 Diag(OldD->getLocation(), diag::note_previous_definition);
6601
6602 Invalid = true;
6603 }
6604
6605 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
6606 if (TemplateParameterListsAreEqual(TemplateParams,
6607 OldDecl->getTemplateParameters(),
6608 /*Complain=*/true,
6609 TPL_TemplateMatch))
6610 OldTemplateParams = OldDecl->getTemplateParameters();
6611 else
6612 Invalid = true;
6613
6614 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
6615 if (!Invalid &&
6616 !Context.hasSameType(OldTD->getUnderlyingType(),
6617 NewTD->getUnderlyingType())) {
6618 // FIXME: The C++0x standard does not clearly say this is ill-formed,
6619 // but we can't reasonably accept it.
6620 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
6621 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
6622 if (OldTD->getLocation().isValid())
6623 Diag(OldTD->getLocation(), diag::note_previous_definition);
6624 Invalid = true;
6625 }
6626 }
6627 }
6628
6629 // Merge any previous default template arguments into our parameters,
6630 // and check the parameter list.
6631 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
6632 TPC_TypeAliasTemplate))
6633 return 0;
6634
6635 TypeAliasTemplateDecl *NewDecl =
6636 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
6637 Name.Identifier, TemplateParams,
6638 NewTD);
6639
6640 NewDecl->setAccess(AS);
6641
6642 if (Invalid)
6643 NewDecl->setInvalidDecl();
6644 else if (OldDecl)
6645 NewDecl->setPreviousDeclaration(OldDecl);
6646
6647 NewND = NewDecl;
6648 } else {
6649 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
6650 NewND = NewTD;
6651 }
Richard Smith162e1c12011-04-15 14:24:37 +00006652
6653 if (!Redeclaration)
Richard Smith3e4c6c42011-05-05 21:57:07 +00006654 PushOnScopeChains(NewND, S);
Richard Smith162e1c12011-04-15 14:24:37 +00006655
Dmitri Gribenkoc27bc802012-08-02 20:49:51 +00006656 ActOnDocumentableDecl(NewND);
Richard Smith3e4c6c42011-05-05 21:57:07 +00006657 return NewND;
Richard Smith162e1c12011-04-15 14:24:37 +00006658}
6659
John McCalld226f652010-08-21 09:40:31 +00006660Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00006661 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006662 SourceLocation AliasLoc,
6663 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006664 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00006665 SourceLocation IdentLoc,
6666 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00006667
Anders Carlsson81c85c42009-03-28 23:53:49 +00006668 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00006669 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
6670 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00006671
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006672 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00006673 NamedDecl *PrevDecl
6674 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
6675 ForRedeclaration);
6676 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
6677 PrevDecl = 0;
6678
6679 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00006680 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00006681 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00006682 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00006683 // FIXME: At some point, we'll want to create the (redundant)
6684 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00006685 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00006686 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00006687 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00006688 }
Mike Stump1eb44332009-09-09 15:08:12 +00006689
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006690 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
6691 diag::err_redefinition_different_kind;
6692 Diag(AliasLoc, DiagID) << Alias;
6693 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00006694 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006695 }
6696
John McCalla24dc2e2009-11-17 02:14:36 +00006697 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00006698 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00006699
John McCallf36e02d2009-10-09 21:13:30 +00006700 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006701 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smithbf9658c2012-04-05 23:13:23 +00006702 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00006703 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00006704 }
Anders Carlsson5721c682009-03-28 06:42:02 +00006705 }
Mike Stump1eb44332009-09-09 15:08:12 +00006706
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00006707 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00006708 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00006709 Alias, SS.getWithLocInContext(Context),
John McCallf36e02d2009-10-09 21:13:30 +00006710 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00006711
John McCall3dbd3d52010-02-16 06:53:13 +00006712 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00006713 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00006714}
6715
Douglas Gregor39957dc2010-05-01 15:04:51 +00006716namespace {
6717 /// \brief Scoped object used to handle the state changes required in Sema
6718 /// to implicitly define the body of a C++ member function;
6719 class ImplicitlyDefinedFunctionScope {
6720 Sema &S;
John McCalleee1d542011-02-14 07:13:47 +00006721 Sema::ContextRAII SavedContext;
Douglas Gregor39957dc2010-05-01 15:04:51 +00006722
6723 public:
6724 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
John McCalleee1d542011-02-14 07:13:47 +00006725 : S(S), SavedContext(S, Method)
Douglas Gregor39957dc2010-05-01 15:04:51 +00006726 {
Douglas Gregor39957dc2010-05-01 15:04:51 +00006727 S.PushFunctionScope();
6728 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
6729 }
6730
6731 ~ImplicitlyDefinedFunctionScope() {
6732 S.PopExpressionEvaluationContext();
Eli Friedmanec9ea722012-01-05 03:35:19 +00006733 S.PopFunctionScopeInfo();
Douglas Gregor39957dc2010-05-01 15:04:51 +00006734 }
6735 };
6736}
6737
Sean Hunt001cad92011-05-10 00:49:42 +00006738Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00006739Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
6740 CXXMethodDecl *MD) {
6741 CXXRecordDecl *ClassDecl = MD->getParent();
6742
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006743 // C++ [except.spec]p14:
6744 // An implicitly declared special member function (Clause 12) shall have an
6745 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00006746 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00006747 if (ClassDecl->isInvalidDecl())
6748 return ExceptSpec;
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006749
Sebastian Redl60618fa2011-03-12 11:50:43 +00006750 // Direct base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006751 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
6752 BEnd = ClassDecl->bases_end();
6753 B != BEnd; ++B) {
6754 if (B->isVirtual()) // Handled below.
6755 continue;
6756
Douglas Gregor18274032010-07-03 00:47:00 +00006757 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
6758 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00006759 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
6760 // If this is a deleted function, add it anyway. This might be conformant
6761 // with the standard. This might not. I'm not sure. It might not matter.
6762 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00006763 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00006764 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006765 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00006766
6767 // Virtual base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006768 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
6769 BEnd = ClassDecl->vbases_end();
6770 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00006771 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
6772 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00006773 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
6774 // If this is a deleted function, add it anyway. This might be conformant
6775 // with the standard. This might not. I'm not sure. It might not matter.
6776 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00006777 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00006778 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006779 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00006780
6781 // Field constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006782 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
6783 FEnd = ClassDecl->field_end();
6784 F != FEnd; ++F) {
Richard Smith7a614d82011-06-11 17:19:42 +00006785 if (F->hasInClassInitializer()) {
6786 if (Expr *E = F->getInClassInitializer())
6787 ExceptSpec.CalledExpr(E);
6788 else if (!F->isInvalidDecl())
Richard Smithb9d0b762012-07-27 04:22:15 +00006789 // DR1351:
6790 // If the brace-or-equal-initializer of a non-static data member
6791 // invokes a defaulted default constructor of its class or of an
6792 // enclosing class in a potentially evaluated subexpression, the
6793 // program is ill-formed.
6794 //
6795 // This resolution is unworkable: the exception specification of the
6796 // default constructor can be needed in an unevaluated context, in
6797 // particular, in the operand of a noexcept-expression, and we can be
6798 // unable to compute an exception specification for an enclosed class.
6799 //
6800 // We do not allow an in-class initializer to require the evaluation
6801 // of the exception specification for any in-class initializer whose
6802 // definition is not lexically complete.
6803 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
Richard Smith7a614d82011-06-11 17:19:42 +00006804 } else if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00006805 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Sean Huntb320e0c2011-06-10 03:50:41 +00006806 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6807 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
6808 // If this is a deleted function, add it anyway. This might be conformant
6809 // with the standard. This might not. I'm not sure. It might not matter.
6810 // In particular, the problem is that this function never gets called. It
6811 // might just be ill-formed because this function attempts to refer to
6812 // a deleted function here.
6813 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00006814 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00006815 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006816 }
John McCalle23cf432010-12-14 08:05:40 +00006817
Sean Hunt001cad92011-05-10 00:49:42 +00006818 return ExceptSpec;
6819}
6820
6821CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
6822 CXXRecordDecl *ClassDecl) {
6823 // C++ [class.ctor]p5:
6824 // A default constructor for a class X is a constructor of class X
6825 // that can be called without an argument. If there is no
6826 // user-declared constructor for class X, a default constructor is
6827 // implicitly declared. An implicitly-declared default constructor
6828 // is an inline public member of its class.
6829 assert(!ClassDecl->hasUserDeclaredConstructor() &&
6830 "Should not build implicit default constructor!");
6831
Richard Smith7756afa2012-06-10 05:43:50 +00006832 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
6833 CXXDefaultConstructor,
6834 false);
6835
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006836 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00006837 CanQualType ClassType
6838 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006839 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor32df23e2010-07-01 22:02:46 +00006840 DeclarationName Name
6841 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006842 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith61802452011-12-22 02:22:31 +00006843 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00006844 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00006845 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00006846 Constexpr);
Douglas Gregor32df23e2010-07-01 22:02:46 +00006847 DefaultCon->setAccess(AS_public);
Sean Hunt1e238652011-05-12 03:51:51 +00006848 DefaultCon->setDefaulted();
Douglas Gregor32df23e2010-07-01 22:02:46 +00006849 DefaultCon->setImplicit();
Sean Hunt023df372011-05-09 18:22:59 +00006850 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
Richard Smithb9d0b762012-07-27 04:22:15 +00006851
6852 // Build an exception specification pointing back at this constructor.
6853 FunctionProtoType::ExtProtoInfo EPI;
6854 EPI.ExceptionSpecType = EST_Unevaluated;
6855 EPI.ExceptionSpecDecl = DefaultCon;
6856 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
6857
Douglas Gregor18274032010-07-03 00:47:00 +00006858 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00006859 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
6860
Douglas Gregor23c94db2010-07-02 17:43:08 +00006861 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00006862 PushOnScopeChains(DefaultCon, S, false);
6863 ClassDecl->addDecl(DefaultCon);
Sean Hunt71a682f2011-05-18 03:41:58 +00006864
Sean Hunte16da072011-10-10 06:18:57 +00006865 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Sean Hunt71a682f2011-05-18 03:41:58 +00006866 DefaultCon->setDeletedAsWritten();
Douglas Gregor18274032010-07-03 00:47:00 +00006867
Douglas Gregor32df23e2010-07-01 22:02:46 +00006868 return DefaultCon;
6869}
6870
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00006871void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
6872 CXXConstructorDecl *Constructor) {
Sean Hunt1e238652011-05-12 03:51:51 +00006873 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00006874 !Constructor->doesThisDeclarationHaveABody() &&
6875 !Constructor->isDeleted()) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00006876 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00006877
Anders Carlssonf6513ed2010-04-23 16:04:08 +00006878 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00006879 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00006880
Douglas Gregor39957dc2010-05-01 15:04:51 +00006881 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00006882 DiagnosticErrorTrap Trap(Diags);
Sean Huntcbb67482011-01-08 20:30:50 +00006883 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00006884 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00006885 Diag(CurrentLocation, diag::note_member_synthesized_at)
Sean Huntf961ea52011-05-10 19:08:14 +00006886 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00006887 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00006888 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00006889 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00006890
6891 SourceLocation Loc = Constructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00006892 Constructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor4ada9d32010-09-20 16:48:21 +00006893
6894 Constructor->setUsed();
6895 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00006896
6897 if (ASTMutationListener *L = getASTMutationListener()) {
6898 L->CompletedImplicitDefinition(Constructor);
6899 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00006900}
6901
Richard Smith7a614d82011-06-11 17:19:42 +00006902void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
6903 if (!D) return;
6904 AdjustDeclIfTemplate(D);
6905
6906 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D);
Richard Smith7a614d82011-06-11 17:19:42 +00006907
Richard Smithb9d0b762012-07-27 04:22:15 +00006908 if (!ClassDecl->isDependentType())
6909 CheckExplicitlyDefaultedMethods(ClassDecl);
Richard Smith7a614d82011-06-11 17:19:42 +00006910}
6911
Sebastian Redlf677ea32011-02-05 19:23:19 +00006912void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
6913 // We start with an initial pass over the base classes to collect those that
6914 // inherit constructors from. If there are none, we can forgo all further
6915 // processing.
Chris Lattner5f9e2722011-07-23 10:55:15 +00006916 typedef SmallVector<const RecordType *, 4> BasesVector;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006917 BasesVector BasesToInheritFrom;
6918 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
6919 BaseE = ClassDecl->bases_end();
6920 BaseIt != BaseE; ++BaseIt) {
6921 if (BaseIt->getInheritConstructors()) {
6922 QualType Base = BaseIt->getType();
6923 if (Base->isDependentType()) {
6924 // If we inherit constructors from anything that is dependent, just
6925 // abort processing altogether. We'll get another chance for the
6926 // instantiations.
6927 return;
6928 }
6929 BasesToInheritFrom.push_back(Base->castAs<RecordType>());
6930 }
6931 }
6932 if (BasesToInheritFrom.empty())
6933 return;
6934
6935 // Now collect the constructors that we already have in the current class.
6936 // Those take precedence over inherited constructors.
6937 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
6938 // unless there is a user-declared constructor with the same signature in
6939 // the class where the using-declaration appears.
6940 llvm::SmallSet<const Type *, 8> ExistingConstructors;
6941 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
6942 CtorE = ClassDecl->ctor_end();
6943 CtorIt != CtorE; ++CtorIt) {
6944 ExistingConstructors.insert(
6945 Context.getCanonicalType(CtorIt->getType()).getTypePtr());
6946 }
6947
Sebastian Redlf677ea32011-02-05 19:23:19 +00006948 DeclarationName CreatedCtorName =
6949 Context.DeclarationNames.getCXXConstructorName(
6950 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
6951
6952 // Now comes the true work.
6953 // First, we keep a map from constructor types to the base that introduced
6954 // them. Needed for finding conflicting constructors. We also keep the
6955 // actually inserted declarations in there, for pretty diagnostics.
6956 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
6957 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
6958 ConstructorToSourceMap InheritedConstructors;
6959 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
6960 BaseE = BasesToInheritFrom.end();
6961 BaseIt != BaseE; ++BaseIt) {
6962 const RecordType *Base = *BaseIt;
6963 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
6964 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
6965 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
6966 CtorE = BaseDecl->ctor_end();
6967 CtorIt != CtorE; ++CtorIt) {
6968 // Find the using declaration for inheriting this base's constructors.
Richard Smithc5a89a12012-04-02 01:30:27 +00006969 // FIXME: Don't perform name lookup just to obtain a source location!
Sebastian Redlf677ea32011-02-05 19:23:19 +00006970 DeclarationName Name =
6971 Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
Richard Smithc5a89a12012-04-02 01:30:27 +00006972 LookupResult Result(*this, Name, SourceLocation(), LookupUsingDeclName);
6973 LookupQualifiedName(Result, CurContext);
6974 UsingDecl *UD = Result.getAsSingle<UsingDecl>();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006975 SourceLocation UsingLoc = UD ? UD->getLocation() :
6976 ClassDecl->getLocation();
6977
6978 // C++0x [class.inhctor]p1: The candidate set of inherited constructors
6979 // from the class X named in the using-declaration consists of actual
6980 // constructors and notional constructors that result from the
6981 // transformation of defaulted parameters as follows:
6982 // - all non-template default constructors of X, and
6983 // - for each non-template constructor of X that has at least one
6984 // parameter with a default argument, the set of constructors that
6985 // results from omitting any ellipsis parameter specification and
6986 // successively omitting parameters with a default argument from the
6987 // end of the parameter-type-list.
David Blaikie581deb32012-06-06 20:45:41 +00006988 CXXConstructorDecl *BaseCtor = *CtorIt;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006989 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
6990 const FunctionProtoType *BaseCtorType =
6991 BaseCtor->getType()->getAs<FunctionProtoType>();
6992
6993 for (unsigned params = BaseCtor->getMinRequiredArguments(),
6994 maxParams = BaseCtor->getNumParams();
6995 params <= maxParams; ++params) {
6996 // Skip default constructors. They're never inherited.
6997 if (params == 0)
6998 continue;
6999 // Skip copy and move constructors for the same reason.
7000 if (CanBeCopyOrMove && params == 1)
7001 continue;
7002
7003 // Build up a function type for this particular constructor.
7004 // FIXME: The working paper does not consider that the exception spec
7005 // for the inheriting constructor might be larger than that of the
Richard Smith7a614d82011-06-11 17:19:42 +00007006 // source. This code doesn't yet, either. When it does, this code will
7007 // need to be delayed until after exception specifications and in-class
7008 // member initializers are attached.
Sebastian Redlf677ea32011-02-05 19:23:19 +00007009 const Type *NewCtorType;
7010 if (params == maxParams)
7011 NewCtorType = BaseCtorType;
7012 else {
Chris Lattner5f9e2722011-07-23 10:55:15 +00007013 SmallVector<QualType, 16> Args;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007014 for (unsigned i = 0; i < params; ++i) {
7015 Args.push_back(BaseCtorType->getArgType(i));
7016 }
7017 FunctionProtoType::ExtProtoInfo ExtInfo =
7018 BaseCtorType->getExtProtoInfo();
7019 ExtInfo.Variadic = false;
7020 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
7021 Args.data(), params, ExtInfo)
7022 .getTypePtr();
7023 }
7024 const Type *CanonicalNewCtorType =
7025 Context.getCanonicalType(NewCtorType);
7026
7027 // Now that we have the type, first check if the class already has a
7028 // constructor with this signature.
7029 if (ExistingConstructors.count(CanonicalNewCtorType))
7030 continue;
7031
7032 // Then we check if we have already declared an inherited constructor
7033 // with this signature.
7034 std::pair<ConstructorToSourceMap::iterator, bool> result =
7035 InheritedConstructors.insert(std::make_pair(
7036 CanonicalNewCtorType,
7037 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
7038 if (!result.second) {
7039 // Already in the map. If it came from a different class, that's an
7040 // error. Not if it's from the same.
7041 CanQualType PreviousBase = result.first->second.first;
7042 if (CanonicalBase != PreviousBase) {
7043 const CXXConstructorDecl *PrevCtor = result.first->second.second;
7044 const CXXConstructorDecl *PrevBaseCtor =
7045 PrevCtor->getInheritedConstructor();
7046 assert(PrevBaseCtor && "Conflicting constructor was not inherited");
7047
7048 Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
7049 Diag(BaseCtor->getLocation(),
7050 diag::note_using_decl_constructor_conflict_current_ctor);
7051 Diag(PrevBaseCtor->getLocation(),
7052 diag::note_using_decl_constructor_conflict_previous_ctor);
7053 Diag(PrevCtor->getLocation(),
7054 diag::note_using_decl_constructor_conflict_previous_using);
7055 }
7056 continue;
7057 }
7058
7059 // OK, we're there, now add the constructor.
7060 // C++0x [class.inhctor]p8: [...] that would be performed by a
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007061 // user-written inline constructor [...]
Sebastian Redlf677ea32011-02-05 19:23:19 +00007062 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
7063 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007064 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
7065 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007066 /*ImplicitlyDeclared=*/true,
7067 // FIXME: Due to a defect in the standard, we treat inherited
7068 // constructors as constexpr even if that makes them ill-formed.
7069 /*Constexpr=*/BaseCtor->isConstexpr());
Sebastian Redlf677ea32011-02-05 19:23:19 +00007070 NewCtor->setAccess(BaseCtor->getAccess());
7071
7072 // Build up the parameter decls and add them.
Chris Lattner5f9e2722011-07-23 10:55:15 +00007073 SmallVector<ParmVarDecl *, 16> ParamDecls;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007074 for (unsigned i = 0; i < params; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007075 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
7076 UsingLoc, UsingLoc,
Sebastian Redlf677ea32011-02-05 19:23:19 +00007077 /*IdentifierInfo=*/0,
7078 BaseCtorType->getArgType(i),
7079 /*TInfo=*/0, SC_None,
7080 SC_None, /*DefaultArg=*/0));
7081 }
David Blaikie4278c652011-09-21 18:16:56 +00007082 NewCtor->setParams(ParamDecls);
Sebastian Redlf677ea32011-02-05 19:23:19 +00007083 NewCtor->setInheritedConstructor(BaseCtor);
7084
Sebastian Redlf677ea32011-02-05 19:23:19 +00007085 ClassDecl->addDecl(NewCtor);
7086 result.first->second.second = NewCtor;
7087 }
7088 }
7089 }
7090}
7091
Sean Huntcb45a0f2011-05-12 22:46:25 +00007092Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00007093Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
7094 CXXRecordDecl *ClassDecl = MD->getParent();
7095
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007096 // C++ [except.spec]p14:
7097 // An implicitly declared special member function (Clause 12) shall have
7098 // an exception-specification.
Richard Smithe6975e92012-04-17 00:58:00 +00007099 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007100 if (ClassDecl->isInvalidDecl())
7101 return ExceptSpec;
7102
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007103 // Direct base-class destructors.
7104 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7105 BEnd = ClassDecl->bases_end();
7106 B != BEnd; ++B) {
7107 if (B->isVirtual()) // Handled below.
7108 continue;
7109
7110 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00007111 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00007112 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007113 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00007114
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007115 // Virtual base-class destructors.
7116 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7117 BEnd = ClassDecl->vbases_end();
7118 B != BEnd; ++B) {
7119 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00007120 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00007121 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007122 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00007123
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007124 // Field destructors.
7125 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7126 FEnd = ClassDecl->field_end();
7127 F != FEnd; ++F) {
7128 if (const RecordType *RecordTy
7129 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00007130 ExceptSpec.CalledDecl(F->getLocation(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00007131 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007132 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007133
Sean Huntcb45a0f2011-05-12 22:46:25 +00007134 return ExceptSpec;
7135}
7136
7137CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
7138 // C++ [class.dtor]p2:
7139 // If a class has no user-declared destructor, a destructor is
7140 // declared implicitly. An implicitly-declared destructor is an
7141 // inline public member of its class.
Sean Huntcb45a0f2011-05-12 22:46:25 +00007142
Douglas Gregor4923aa22010-07-02 20:37:36 +00007143 // Create the actual destructor declaration.
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007144 CanQualType ClassType
7145 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007146 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007147 DeclarationName Name
7148 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007149 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007150 CXXDestructorDecl *Destructor
Richard Smithb9d0b762012-07-27 04:22:15 +00007151 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
7152 QualType(), 0, /*isInline=*/true,
Sebastian Redl60618fa2011-03-12 11:50:43 +00007153 /*isImplicitlyDeclared=*/true);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007154 Destructor->setAccess(AS_public);
Sean Huntcb45a0f2011-05-12 22:46:25 +00007155 Destructor->setDefaulted();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007156 Destructor->setImplicit();
7157 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Richard Smithb9d0b762012-07-27 04:22:15 +00007158
7159 // Build an exception specification pointing back at this destructor.
7160 FunctionProtoType::ExtProtoInfo EPI;
7161 EPI.ExceptionSpecType = EST_Unevaluated;
7162 EPI.ExceptionSpecDecl = Destructor;
7163 Destructor->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
7164
Douglas Gregor4923aa22010-07-02 20:37:36 +00007165 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00007166 ++ASTContext::NumImplicitDestructorsDeclared;
Richard Smithb9d0b762012-07-27 04:22:15 +00007167
Douglas Gregor4923aa22010-07-02 20:37:36 +00007168 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00007169 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00007170 PushOnScopeChains(Destructor, S, false);
7171 ClassDecl->addDecl(Destructor);
Sean Huntcb45a0f2011-05-12 22:46:25 +00007172
Richard Smith9a561d52012-02-26 09:11:52 +00007173 AddOverriddenMethods(ClassDecl, Destructor);
7174
Richard Smith7d5088a2012-02-18 02:02:13 +00007175 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
Sean Huntcb45a0f2011-05-12 22:46:25 +00007176 Destructor->setDeletedAsWritten();
Richard Smith9a561d52012-02-26 09:11:52 +00007177
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007178 return Destructor;
7179}
7180
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007181void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00007182 CXXDestructorDecl *Destructor) {
Sean Huntcd10dec2011-05-23 23:14:04 +00007183 assert((Destructor->isDefaulted() &&
Richard Smith03f68782012-02-26 07:51:39 +00007184 !Destructor->doesThisDeclarationHaveABody() &&
7185 !Destructor->isDeleted()) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007186 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00007187 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007188 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007189
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007190 if (Destructor->isInvalidDecl())
7191 return;
7192
Douglas Gregor39957dc2010-05-01 15:04:51 +00007193 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007194
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007195 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00007196 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
7197 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00007198
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007199 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00007200 Diag(CurrentLocation, diag::note_member_synthesized_at)
7201 << CXXDestructor << Context.getTagDeclType(ClassDecl);
7202
7203 Destructor->setInvalidDecl();
7204 return;
7205 }
7206
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007207 SourceLocation Loc = Destructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00007208 Destructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor690b2db2011-09-22 20:32:43 +00007209 Destructor->setImplicitlyDefined(true);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007210 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007211 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007212
7213 if (ASTMutationListener *L = getASTMutationListener()) {
7214 L->CompletedImplicitDefinition(Destructor);
7215 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007216}
7217
Richard Smitha4156b82012-04-21 18:42:51 +00007218/// \brief Perform any semantic analysis which needs to be delayed until all
7219/// pending class member declarations have been parsed.
7220void Sema::ActOnFinishCXXMemberDecls() {
Richard Smitha4156b82012-04-21 18:42:51 +00007221 // Perform any deferred checking of exception specifications for virtual
7222 // destructors.
7223 for (unsigned i = 0, e = DelayedDestructorExceptionSpecChecks.size();
7224 i != e; ++i) {
7225 const CXXDestructorDecl *Dtor =
7226 DelayedDestructorExceptionSpecChecks[i].first;
7227 assert(!Dtor->getParent()->isDependentType() &&
7228 "Should not ever add destructors of templates into the list.");
7229 CheckOverridingFunctionExceptionSpec(Dtor,
7230 DelayedDestructorExceptionSpecChecks[i].second);
7231 }
7232 DelayedDestructorExceptionSpecChecks.clear();
7233}
7234
Richard Smithb9d0b762012-07-27 04:22:15 +00007235void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
7236 CXXDestructorDecl *Destructor) {
7237 assert(getLangOpts().CPlusPlus0x &&
7238 "adjusting dtor exception specs was introduced in c++11");
7239
Sebastian Redl0ee33912011-05-19 05:13:44 +00007240 // C++11 [class.dtor]p3:
7241 // A declaration of a destructor that does not have an exception-
7242 // specification is implicitly considered to have the same exception-
7243 // specification as an implicit declaration.
Richard Smithb9d0b762012-07-27 04:22:15 +00007244 const FunctionProtoType *DtorType = Destructor->getType()->
Sebastian Redl0ee33912011-05-19 05:13:44 +00007245 getAs<FunctionProtoType>();
Richard Smithb9d0b762012-07-27 04:22:15 +00007246 if (DtorType->hasExceptionSpec())
Sebastian Redl0ee33912011-05-19 05:13:44 +00007247 return;
7248
Chandler Carruth3f224b22011-09-20 04:55:26 +00007249 // Replace the destructor's type, building off the existing one. Fortunately,
7250 // the only thing of interest in the destructor type is its extended info.
7251 // The return and arguments are fixed.
Richard Smithb9d0b762012-07-27 04:22:15 +00007252 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
7253 EPI.ExceptionSpecType = EST_Unevaluated;
7254 EPI.ExceptionSpecDecl = Destructor;
7255 Destructor->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
Richard Smitha4156b82012-04-21 18:42:51 +00007256
Sebastian Redl0ee33912011-05-19 05:13:44 +00007257 // FIXME: If the destructor has a body that could throw, and the newly created
7258 // spec doesn't allow exceptions, we should emit a warning, because this
7259 // change in behavior can break conforming C++03 programs at runtime.
Richard Smithb9d0b762012-07-27 04:22:15 +00007260 // However, we don't have a body or an exception specification yet, so it
7261 // needs to be done somewhere else.
Sebastian Redl0ee33912011-05-19 05:13:44 +00007262}
7263
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007264/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregor06a9f362010-05-01 20:49:11 +00007265/// \c To.
7266///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007267/// This routine is used to copy/move the members of a class with an
7268/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregor06a9f362010-05-01 20:49:11 +00007269/// copied are arrays, this routine builds for loops to copy them.
7270///
7271/// \param S The Sema object used for type-checking.
7272///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007273/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007274///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007275/// \param T The type of the expressions being copied/moved. Both expressions
7276/// must have this type.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007277///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007278/// \param To The expression we are copying/moving to.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007279///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007280/// \param From The expression we are copying/moving from.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007281///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007282/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor6cdc1612010-05-04 15:20:55 +00007283/// Otherwise, it's a non-static member subobject.
7284///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007285/// \param Copying Whether we're copying or moving.
7286///
Douglas Gregor06a9f362010-05-01 20:49:11 +00007287/// \param Depth Internal parameter recording the depth of the recursion.
7288///
7289/// \returns A statement or a loop that copies the expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00007290static StmtResult
Douglas Gregor06a9f362010-05-01 20:49:11 +00007291BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCall9ae2f072010-08-23 23:25:46 +00007292 Expr *To, Expr *From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007293 bool CopyingBaseSubobject, bool Copying,
7294 unsigned Depth = 0) {
7295 // C++0x [class.copy]p28:
Douglas Gregor06a9f362010-05-01 20:49:11 +00007296 // Each subobject is assigned in the manner appropriate to its type:
7297 //
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007298 // - if the subobject is of class type, as if by a call to operator= with
7299 // the subobject as the object expression and the corresponding
7300 // subobject of x as a single function argument (as if by explicit
7301 // qualification; that is, ignoring any possible virtual overriding
7302 // functions in more derived classes);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007303 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
7304 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7305
7306 // Look for operator=.
7307 DeclarationName Name
7308 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
7309 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
7310 S.LookupQualifiedName(OpLookup, ClassDecl, false);
7311
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007312 // Filter out any result that isn't a copy/move-assignment operator.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007313 LookupResult::Filter F = OpLookup.makeFilter();
7314 while (F.hasNext()) {
7315 NamedDecl *D = F.next();
7316 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
Richard Smith1c931be2012-04-02 18:40:40 +00007317 if (Method->isCopyAssignmentOperator() ||
7318 (!Copying && Method->isMoveAssignmentOperator()))
Douglas Gregor06a9f362010-05-01 20:49:11 +00007319 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007320
Douglas Gregor06a9f362010-05-01 20:49:11 +00007321 F.erase();
John McCallb0207482010-03-16 06:11:48 +00007322 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007323 F.done();
7324
Douglas Gregor6cdc1612010-05-04 15:20:55 +00007325 // Suppress the protected check (C++ [class.protected]) for each of the
7326 // assignment operators we found. This strange dance is required when
7327 // we're assigning via a base classes's copy-assignment operator. To
7328 // ensure that we're getting the right base class subobject (without
7329 // ambiguities), we need to cast "this" to that subobject type; to
7330 // ensure that we don't go through the virtual call mechanism, we need
7331 // to qualify the operator= name with the base class (see below). However,
7332 // this means that if the base class has a protected copy assignment
7333 // operator, the protected member access check will fail. So, we
7334 // rewrite "protected" access to "public" access in this case, since we
7335 // know by construction that we're calling from a derived class.
7336 if (CopyingBaseSubobject) {
7337 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
7338 L != LEnd; ++L) {
7339 if (L.getAccess() == AS_protected)
7340 L.setAccess(AS_public);
7341 }
7342 }
7343
Douglas Gregor06a9f362010-05-01 20:49:11 +00007344 // Create the nested-name-specifier that will be used to qualify the
7345 // reference to operator=; this is required to suppress the virtual
7346 // call mechanism.
7347 CXXScopeSpec SS;
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00007348 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Douglas Gregorc34348a2011-02-24 17:54:50 +00007349 SS.MakeTrivial(S.Context,
7350 NestedNameSpecifier::Create(S.Context, 0, false,
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00007351 CanonicalT),
Douglas Gregorc34348a2011-02-24 17:54:50 +00007352 Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007353
7354 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00007355 ExprResult OpEqualRef
John McCall9ae2f072010-08-23 23:25:46 +00007356 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00007357 /*TemplateKWLoc=*/SourceLocation(),
7358 /*FirstQualifierInScope=*/0,
7359 OpLookup,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007360 /*TemplateArgs=*/0,
7361 /*SuppressQualifierCheck=*/true);
7362 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007363 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007364
7365 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00007366
John McCall60d7b3a2010-08-24 06:29:42 +00007367 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00007368 OpEqualRef.takeAs<Expr>(),
7369 Loc, &From, 1, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007370 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007371 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007372
7373 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007374 }
John McCallb0207482010-03-16 06:11:48 +00007375
Douglas Gregor06a9f362010-05-01 20:49:11 +00007376 // - if the subobject is of scalar type, the built-in assignment
7377 // operator is used.
7378 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
7379 if (!ArrayTy) {
John McCall2de56d12010-08-25 11:45:40 +00007380 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007381 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007382 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007383
7384 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007385 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007386
7387 // - if the subobject is an array, each element is assigned, in the
7388 // manner appropriate to the element type;
7389
7390 // Construct a loop over the array bounds, e.g.,
7391 //
7392 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
7393 //
7394 // that will copy each of the array elements.
7395 QualType SizeType = S.Context.getSizeType();
7396
7397 // Create the iteration variable.
7398 IdentifierInfo *IterationVarName = 0;
7399 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00007400 SmallString<8> Str;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007401 llvm::raw_svector_ostream OS(Str);
7402 OS << "__i" << Depth;
7403 IterationVarName = &S.Context.Idents.get(OS.str());
7404 }
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007405 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007406 IterationVarName, SizeType,
7407 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00007408 SC_None, SC_None);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007409
7410 // Initialize the iteration variable to zero.
7411 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00007412 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00007413
7414 // Create a reference to the iteration variable; we'll use this several
7415 // times throughout.
7416 Expr *IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00007417 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007418 assert(IterationVarRef && "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00007419 Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take();
7420 assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!");
7421
Douglas Gregor06a9f362010-05-01 20:49:11 +00007422 // Create the DeclStmt that holds the iteration variable.
7423 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
7424
7425 // Create the comparison against the array bound.
Jay Foad9f71a8f2010-12-07 08:25:34 +00007426 llvm::APInt Upper
7427 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCall9ae2f072010-08-23 23:25:46 +00007428 Expr *Comparison
Eli Friedman8c382062012-01-23 02:35:22 +00007429 = new (S.Context) BinaryOperator(IterationVarRefRVal,
John McCallf89e55a2010-11-18 06:31:45 +00007430 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
7431 BO_NE, S.Context.BoolTy,
7432 VK_RValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007433
7434 // Create the pre-increment of the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00007435 Expr *Increment
John McCallf89e55a2010-11-18 06:31:45 +00007436 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
7437 VK_LValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007438
7439 // Subscript the "from" and "to" expressions with the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00007440 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00007441 IterationVarRefRVal,
7442 Loc));
John McCall9ae2f072010-08-23 23:25:46 +00007443 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00007444 IterationVarRefRVal,
7445 Loc));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007446 if (!Copying) // Cast to rvalue
7447 From = CastForMoving(S, From);
7448
7449 // Build the copy/move for an individual element of the array.
John McCallf89e55a2010-11-18 06:31:45 +00007450 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
7451 To, From, CopyingBaseSubobject,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007452 Copying, Depth + 1);
Douglas Gregorff331c12010-07-25 18:17:45 +00007453 if (Copy.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007454 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007455
7456 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00007457 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007458 S.MakeFullExpr(Comparison),
John McCalld226f652010-08-21 09:40:31 +00007459 0, S.MakeFullExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00007460 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007461}
7462
Richard Smithb9d0b762012-07-27 04:22:15 +00007463/// Determine whether an implicit copy assignment operator for ClassDecl has a
7464/// const argument.
7465/// FIXME: It ought to be possible to store this on the record.
7466static bool isImplicitCopyAssignmentArgConst(Sema &S,
7467 CXXRecordDecl *ClassDecl) {
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007468 if (ClassDecl->isInvalidDecl())
Richard Smithb9d0b762012-07-27 04:22:15 +00007469 return true;
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007470
Douglas Gregord3c35902010-07-01 16:36:15 +00007471 // C++ [class.copy]p10:
7472 // If the class definition does not explicitly declare a copy
7473 // assignment operator, one is declared implicitly.
7474 // The implicitly-defined copy assignment operator for a class X
7475 // will have the form
7476 //
7477 // X& X::operator=(const X&)
7478 //
7479 // if
Douglas Gregord3c35902010-07-01 16:36:15 +00007480 // -- each direct base class B of X has a copy assignment operator
7481 // whose parameter is of type const B&, const volatile B& or B,
7482 // and
7483 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7484 BaseEnd = ClassDecl->bases_end();
Richard Smithb9d0b762012-07-27 04:22:15 +00007485 Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00007486 // We'll handle this below
Richard Smithb9d0b762012-07-27 04:22:15 +00007487 if (S.getLangOpts().CPlusPlus0x && Base->isVirtual())
Sean Hunt661c67a2011-06-21 23:42:56 +00007488 continue;
7489
Douglas Gregord3c35902010-07-01 16:36:15 +00007490 assert(!Base->getType()->isDependentType() &&
7491 "Cannot generate implicit members for class with dependent bases.");
Sean Hunt661c67a2011-06-21 23:42:56 +00007492 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
Richard Smithb9d0b762012-07-27 04:22:15 +00007493 if (!S.LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0))
7494 return false;
Sean Hunt661c67a2011-06-21 23:42:56 +00007495 }
7496
Richard Smithebaf0e62011-10-18 20:49:44 +00007497 // In C++11, the above citation has "or virtual" added
Richard Smithb9d0b762012-07-27 04:22:15 +00007498 if (S.getLangOpts().CPlusPlus0x) {
Sean Hunt661c67a2011-06-21 23:42:56 +00007499 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7500 BaseEnd = ClassDecl->vbases_end();
Richard Smithb9d0b762012-07-27 04:22:15 +00007501 Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00007502 assert(!Base->getType()->isDependentType() &&
7503 "Cannot generate implicit members for class with dependent bases.");
7504 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
Richard Smithb9d0b762012-07-27 04:22:15 +00007505 if (!S.LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const,
7506 false, 0))
7507 return false;
Sean Hunt661c67a2011-06-21 23:42:56 +00007508 }
Douglas Gregord3c35902010-07-01 16:36:15 +00007509 }
7510
7511 // -- for all the nonstatic data members of X that are of a class
7512 // type M (or array thereof), each such class type has a copy
7513 // assignment operator whose parameter is of type const M&,
7514 // const volatile M& or M.
7515 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7516 FieldEnd = ClassDecl->field_end();
Richard Smithb9d0b762012-07-27 04:22:15 +00007517 Field != FieldEnd; ++Field) {
7518 QualType FieldType = S.Context.getBaseElementType(Field->getType());
7519 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl())
7520 if (!S.LookupCopyingAssignment(FieldClassDecl, Qualifiers::Const,
7521 false, 0))
7522 return false;
Douglas Gregord3c35902010-07-01 16:36:15 +00007523 }
7524
7525 // Otherwise, the implicitly declared copy assignment operator will
7526 // have the form
7527 //
7528 // X& X::operator=(X&)
Richard Smithb9d0b762012-07-27 04:22:15 +00007529
7530 return true;
7531}
7532
7533Sema::ImplicitExceptionSpecification
7534Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
7535 CXXRecordDecl *ClassDecl = MD->getParent();
7536
7537 ImplicitExceptionSpecification ExceptSpec(*this);
7538 if (ClassDecl->isInvalidDecl())
7539 return ExceptSpec;
7540
7541 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
7542 assert(T->getNumArgs() == 1 && "not a copy assignment op");
7543 unsigned ArgQuals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
7544
Douglas Gregorb87786f2010-07-01 17:48:08 +00007545 // C++ [except.spec]p14:
Richard Smithb9d0b762012-07-27 04:22:15 +00007546 // An implicitly declared special member function (Clause 12) shall have an
Douglas Gregorb87786f2010-07-01 17:48:08 +00007547 // exception-specification. [...]
Sean Hunt661c67a2011-06-21 23:42:56 +00007548
7549 // It is unspecified whether or not an implicit copy assignment operator
7550 // attempts to deduplicate calls to assignment operators of virtual bases are
7551 // made. As such, this exception specification is effectively unspecified.
7552 // Based on a similar decision made for constness in C++0x, we're erring on
7553 // the side of assuming such calls to be made regardless of whether they
7554 // actually happen.
Douglas Gregorb87786f2010-07-01 17:48:08 +00007555 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7556 BaseEnd = ClassDecl->bases_end();
7557 Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00007558 if (Base->isVirtual())
7559 continue;
7560
Douglas Gregora376d102010-07-02 21:50:04 +00007561 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00007562 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00007563 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7564 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00007565 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Douglas Gregorb87786f2010-07-01 17:48:08 +00007566 }
Sean Hunt661c67a2011-06-21 23:42:56 +00007567
7568 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7569 BaseEnd = ClassDecl->vbases_end();
7570 Base != BaseEnd; ++Base) {
7571 CXXRecordDecl *BaseClassDecl
7572 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7573 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7574 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00007575 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Sean Hunt661c67a2011-06-21 23:42:56 +00007576 }
7577
Douglas Gregorb87786f2010-07-01 17:48:08 +00007578 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7579 FieldEnd = ClassDecl->field_end();
7580 Field != FieldEnd;
7581 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00007582 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00007583 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7584 if (CXXMethodDecl *CopyAssign =
Richard Smith6a06e5f2012-07-18 03:36:00 +00007585 LookupCopyingAssignment(FieldClassDecl,
7586 ArgQuals | FieldType.getCVRQualifiers(),
7587 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00007588 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007589 }
Douglas Gregorb87786f2010-07-01 17:48:08 +00007590 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007591
Richard Smithb9d0b762012-07-27 04:22:15 +00007592 return ExceptSpec;
Sean Hunt30de05c2011-05-14 05:23:20 +00007593}
7594
7595CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
7596 // Note: The following rules are largely analoguous to the copy
7597 // constructor rules. Note that virtual bases are not taken into account
7598 // for determining the argument type of the operator. Note also that
7599 // operators taking an object instead of a reference are allowed.
7600
Sean Hunt30de05c2011-05-14 05:23:20 +00007601 QualType ArgType = Context.getTypeDeclType(ClassDecl);
7602 QualType RetType = Context.getLValueReferenceType(ArgType);
Richard Smithb9d0b762012-07-27 04:22:15 +00007603 if (isImplicitCopyAssignmentArgConst(*this, ClassDecl))
Sean Hunt30de05c2011-05-14 05:23:20 +00007604 ArgType = ArgType.withConst();
7605 ArgType = Context.getLValueReferenceType(ArgType);
7606
Douglas Gregord3c35902010-07-01 16:36:15 +00007607 // An implicitly-declared copy assignment operator is an inline public
7608 // member of its class.
7609 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007610 SourceLocation ClassLoc = ClassDecl->getLocation();
7611 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregord3c35902010-07-01 16:36:15 +00007612 CXXMethodDecl *CopyAssignment
Richard Smithb9d0b762012-07-27 04:22:15 +00007613 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Douglas Gregord3c35902010-07-01 16:36:15 +00007614 /*TInfo=*/0, /*isStatic=*/false,
John McCalld931b082010-08-26 03:08:43 +00007615 /*StorageClassAsWritten=*/SC_None,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007616 /*isInline=*/true, /*isConstexpr=*/false,
Douglas Gregorf5251602011-03-08 17:10:18 +00007617 SourceLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00007618 CopyAssignment->setAccess(AS_public);
Sean Hunt7f410192011-05-14 05:23:24 +00007619 CopyAssignment->setDefaulted();
Douglas Gregord3c35902010-07-01 16:36:15 +00007620 CopyAssignment->setImplicit();
7621 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Richard Smithb9d0b762012-07-27 04:22:15 +00007622
7623 // Build an exception specification pointing back at this member.
7624 FunctionProtoType::ExtProtoInfo EPI;
7625 EPI.ExceptionSpecType = EST_Unevaluated;
7626 EPI.ExceptionSpecDecl = CopyAssignment;
7627 CopyAssignment->setType(Context.getFunctionType(RetType, &ArgType, 1, EPI));
7628
Douglas Gregord3c35902010-07-01 16:36:15 +00007629 // Add the parameter to the operator.
7630 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007631 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregord3c35902010-07-01 16:36:15 +00007632 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00007633 SC_None,
7634 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00007635 CopyAssignment->setParams(FromParam);
Douglas Gregord3c35902010-07-01 16:36:15 +00007636
Douglas Gregora376d102010-07-02 21:50:04 +00007637 // Note that we have added this copy-assignment operator.
Douglas Gregora376d102010-07-02 21:50:04 +00007638 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Sean Hunt7f410192011-05-14 05:23:24 +00007639
Douglas Gregor23c94db2010-07-02 17:43:08 +00007640 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora376d102010-07-02 21:50:04 +00007641 PushOnScopeChains(CopyAssignment, S, false);
7642 ClassDecl->addDecl(CopyAssignment);
Douglas Gregord3c35902010-07-01 16:36:15 +00007643
Nico Weberafcc96a2012-01-23 03:19:29 +00007644 // C++0x [class.copy]p19:
7645 // .... If the class definition does not explicitly declare a copy
7646 // assignment operator, there is no user-declared move constructor, and
7647 // there is no user-declared move assignment operator, a copy assignment
7648 // operator is implicitly declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00007649 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
Sean Hunt71a682f2011-05-18 03:41:58 +00007650 CopyAssignment->setDeletedAsWritten();
Richard Smith6c4c36c2012-03-30 20:53:28 +00007651
Douglas Gregord3c35902010-07-01 16:36:15 +00007652 AddOverriddenMethods(ClassDecl, CopyAssignment);
7653 return CopyAssignment;
7654}
7655
Douglas Gregor06a9f362010-05-01 20:49:11 +00007656void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
7657 CXXMethodDecl *CopyAssignOperator) {
Sean Hunt7f410192011-05-14 05:23:24 +00007658 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00007659 CopyAssignOperator->isOverloadedOperator() &&
7660 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00007661 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
7662 !CopyAssignOperator->isDeleted()) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00007663 "DefineImplicitCopyAssignment called for wrong function");
7664
7665 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
7666
7667 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
7668 CopyAssignOperator->setInvalidDecl();
7669 return;
7670 }
7671
7672 CopyAssignOperator->setUsed();
7673
7674 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007675 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007676
7677 // C++0x [class.copy]p30:
7678 // The implicitly-defined or explicitly-defaulted copy assignment operator
7679 // for a non-union class X performs memberwise copy assignment of its
7680 // subobjects. The direct base classes of X are assigned first, in the
7681 // order of their declaration in the base-specifier-list, and then the
7682 // immediate non-static data members of X are assigned, in the order in
7683 // which they were declared in the class definition.
7684
7685 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00007686 SmallVector<Stmt*, 8> Statements;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007687
7688 // The parameter for the "other" object, which we are copying from.
7689 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
7690 Qualifiers OtherQuals = Other->getType().getQualifiers();
7691 QualType OtherRefType = Other->getType();
7692 if (const LValueReferenceType *OtherRef
7693 = OtherRefType->getAs<LValueReferenceType>()) {
7694 OtherRefType = OtherRef->getPointeeType();
7695 OtherQuals = OtherRefType.getQualifiers();
7696 }
7697
7698 // Our location for everything implicitly-generated.
7699 SourceLocation Loc = CopyAssignOperator->getLocation();
7700
7701 // Construct a reference to the "other" object. We'll be using this
7702 // throughout the generated ASTs.
John McCall09431682010-11-18 19:01:18 +00007703 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007704 assert(OtherRef && "Reference to parameter cannot fail!");
7705
7706 // Construct the "this" pointer. We'll be using this throughout the generated
7707 // ASTs.
7708 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
7709 assert(This && "Reference to this cannot fail!");
7710
7711 // Assign base classes.
7712 bool Invalid = false;
7713 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7714 E = ClassDecl->bases_end(); Base != E; ++Base) {
7715 // Form the assignment:
7716 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
7717 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00007718 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00007719 Invalid = true;
7720 continue;
7721 }
7722
John McCallf871d0c2010-08-07 06:22:56 +00007723 CXXCastPath BasePath;
7724 BasePath.push_back(Base);
7725
Douglas Gregor06a9f362010-05-01 20:49:11 +00007726 // Construct the "from" expression, which is an implicit cast to the
7727 // appropriately-qualified base type.
John McCall3fa5cae2010-10-26 07:05:15 +00007728 Expr *From = OtherRef;
John Wiegley429bb272011-04-08 18:41:53 +00007729 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
7730 CK_UncheckedDerivedToBase,
7731 VK_LValue, &BasePath).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007732
7733 // Dereference "this".
John McCall5baba9d2010-08-25 10:28:54 +00007734 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007735
7736 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley429bb272011-04-08 18:41:53 +00007737 To = ImpCastExprToType(To.take(),
7738 Context.getCVRQualifiedType(BaseType,
7739 CopyAssignOperator->getTypeQualifiers()),
7740 CK_UncheckedDerivedToBase,
7741 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007742
7743 // Build the copy.
John McCall60d7b3a2010-08-24 06:29:42 +00007744 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00007745 To.get(), From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007746 /*CopyingBaseSubobject=*/true,
7747 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007748 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007749 Diag(CurrentLocation, diag::note_member_synthesized_at)
7750 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7751 CopyAssignOperator->setInvalidDecl();
7752 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007753 }
7754
7755 // Success! Record the copy.
7756 Statements.push_back(Copy.takeAs<Expr>());
7757 }
7758
7759 // \brief Reference to the __builtin_memcpy function.
7760 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00007761 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007762 Expr *CollectableMemCpyRef = 0;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007763
7764 // Assign non-static members.
7765 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7766 FieldEnd = ClassDecl->field_end();
7767 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00007768 if (Field->isUnnamedBitfield())
7769 continue;
7770
Douglas Gregor06a9f362010-05-01 20:49:11 +00007771 // Check for members of reference type; we can't copy those.
7772 if (Field->getType()->isReferenceType()) {
7773 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7774 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
7775 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007776 Diag(CurrentLocation, diag::note_member_synthesized_at)
7777 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007778 Invalid = true;
7779 continue;
7780 }
7781
7782 // Check for members of const-qualified, non-class type.
7783 QualType BaseType = Context.getBaseElementType(Field->getType());
7784 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
7785 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7786 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
7787 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007788 Diag(CurrentLocation, diag::note_member_synthesized_at)
7789 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007790 Invalid = true;
7791 continue;
7792 }
John McCallb77115d2011-06-17 00:18:42 +00007793
7794 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00007795 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
7796 continue;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007797
7798 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00007799 if (FieldType->isIncompleteArrayType()) {
7800 assert(ClassDecl->hasFlexibleArrayMember() &&
7801 "Incomplete array type is not valid");
7802 continue;
7803 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007804
7805 // Build references to the field in the object we're copying from and to.
7806 CXXScopeSpec SS; // Intentionally empty
7807 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
7808 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00007809 MemberLookup.addDecl(*Field);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007810 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00007811 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall09431682010-11-18 19:01:18 +00007812 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00007813 SS, SourceLocation(), 0,
7814 MemberLookup, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00007815 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall09431682010-11-18 19:01:18 +00007816 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00007817 SS, SourceLocation(), 0,
7818 MemberLookup, 0);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007819 assert(!From.isInvalid() && "Implicit field reference cannot fail");
7820 assert(!To.isInvalid() && "Implicit field reference cannot fail");
7821
7822 // If the field should be copied with __builtin_memcpy rather than via
7823 // explicit assignments, do so. This optimization only applies for arrays
7824 // of scalars and arrays of class type with trivial copy-assignment
7825 // operators.
Fariborz Jahanian6b167f42011-08-09 00:26:11 +00007826 if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007827 && BaseType.hasTrivialAssignment(Context, /*Copying=*/true)) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00007828 // Compute the size of the memory buffer to be copied.
7829 QualType SizeType = Context.getSizeType();
7830 llvm::APInt Size(Context.getTypeSize(SizeType),
7831 Context.getTypeSizeInChars(BaseType).getQuantity());
7832 for (const ConstantArrayType *Array
7833 = Context.getAsConstantArrayType(FieldType);
7834 Array;
7835 Array = Context.getAsConstantArrayType(Array->getElementType())) {
Jay Foad9f71a8f2010-12-07 08:25:34 +00007836 llvm::APInt ArraySize
7837 = Array->getSize().zextOrTrunc(Size.getBitWidth());
Douglas Gregor06a9f362010-05-01 20:49:11 +00007838 Size *= ArraySize;
7839 }
7840
7841 // Take the address of the field references for "from" and "to".
John McCall2de56d12010-08-25 11:45:40 +00007842 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
7843 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007844
7845 bool NeedsCollectableMemCpy =
7846 (BaseType->isRecordType() &&
7847 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
7848
7849 if (NeedsCollectableMemCpy) {
7850 if (!CollectableMemCpyRef) {
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00007851 // Create a reference to the __builtin_objc_memmove_collectable function.
7852 LookupResult R(*this,
7853 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007854 Loc, LookupOrdinaryName);
7855 LookupName(R, TUScope, true);
7856
7857 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
7858 if (!CollectableMemCpy) {
7859 // Something went horribly wrong earlier, and we will have
7860 // complained about it.
7861 Invalid = true;
7862 continue;
7863 }
7864
7865 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
Eli Friedmana6c66ce2012-08-31 00:14:07 +00007866 Context.BuiltinFnTy,
7867 VK_RValue, Loc, 0).take();
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007868 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
7869 }
7870 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007871 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007872 else if (!BuiltinMemCpyRef) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00007873 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
7874 LookupOrdinaryName);
7875 LookupName(R, TUScope, true);
7876
7877 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
7878 if (!BuiltinMemCpy) {
7879 // Something went horribly wrong earlier, and we will have complained
7880 // about it.
7881 Invalid = true;
7882 continue;
7883 }
7884
7885 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
Eli Friedmana6c66ce2012-08-31 00:14:07 +00007886 Context.BuiltinFnTy,
7887 VK_RValue, Loc, 0).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007888 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
7889 }
7890
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00007891 SmallVector<Expr*, 8> CallArgs;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007892 CallArgs.push_back(To.takeAs<Expr>());
7893 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00007894 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCall60d7b3a2010-08-24 06:29:42 +00007895 ExprResult Call = ExprError();
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007896 if (NeedsCollectableMemCpy)
7897 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00007898 CollectableMemCpyRef,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007899 Loc, CallArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00007900 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007901 else
7902 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00007903 BuiltinMemCpyRef,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007904 Loc, CallArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00007905 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007906
Douglas Gregor06a9f362010-05-01 20:49:11 +00007907 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
7908 Statements.push_back(Call.takeAs<Expr>());
7909 continue;
7910 }
7911
7912 // Build the copy of this field.
John McCall60d7b3a2010-08-24 06:29:42 +00007913 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007914 To.get(), From.get(),
7915 /*CopyingBaseSubobject=*/false,
7916 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007917 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007918 Diag(CurrentLocation, diag::note_member_synthesized_at)
7919 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7920 CopyAssignOperator->setInvalidDecl();
7921 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007922 }
7923
7924 // Success! Record the copy.
7925 Statements.push_back(Copy.takeAs<Stmt>());
7926 }
7927
7928 if (!Invalid) {
7929 // Add a "return *this;"
John McCall2de56d12010-08-25 11:45:40 +00007930 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007931
John McCall60d7b3a2010-08-24 06:29:42 +00007932 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00007933 if (Return.isInvalid())
7934 Invalid = true;
7935 else {
7936 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007937
7938 if (Trap.hasErrorOccurred()) {
7939 Diag(CurrentLocation, diag::note_member_synthesized_at)
7940 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7941 Invalid = true;
7942 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007943 }
7944 }
7945
7946 if (Invalid) {
7947 CopyAssignOperator->setInvalidDecl();
7948 return;
7949 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00007950
7951 StmtResult Body;
7952 {
7953 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007954 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00007955 /*isStmtExpr=*/false);
7956 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
7957 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007958 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007959
7960 if (ASTMutationListener *L = getASTMutationListener()) {
7961 L->CompletedImplicitDefinition(CopyAssignOperator);
7962 }
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007963}
7964
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007965Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00007966Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
7967 CXXRecordDecl *ClassDecl = MD->getParent();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007968
Richard Smithb9d0b762012-07-27 04:22:15 +00007969 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007970 if (ClassDecl->isInvalidDecl())
7971 return ExceptSpec;
7972
7973 // C++0x [except.spec]p14:
7974 // An implicitly declared special member function (Clause 12) shall have an
7975 // exception-specification. [...]
7976
7977 // It is unspecified whether or not an implicit move assignment operator
7978 // attempts to deduplicate calls to assignment operators of virtual bases are
7979 // made. As such, this exception specification is effectively unspecified.
7980 // Based on a similar decision made for constness in C++0x, we're erring on
7981 // the side of assuming such calls to be made regardless of whether they
7982 // actually happen.
7983 // Note that a move constructor is not implicitly declared when there are
7984 // virtual bases, but it can still be user-declared and explicitly defaulted.
7985 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7986 BaseEnd = ClassDecl->bases_end();
7987 Base != BaseEnd; ++Base) {
7988 if (Base->isVirtual())
7989 continue;
7990
7991 CXXRecordDecl *BaseClassDecl
7992 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7993 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00007994 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00007995 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007996 }
7997
7998 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7999 BaseEnd = ClassDecl->vbases_end();
8000 Base != BaseEnd; ++Base) {
8001 CXXRecordDecl *BaseClassDecl
8002 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8003 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00008004 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008005 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008006 }
8007
8008 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8009 FieldEnd = ClassDecl->field_end();
8010 Field != FieldEnd;
8011 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00008012 QualType FieldType = Context.getBaseElementType(Field->getType());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008013 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith6a06e5f2012-07-18 03:36:00 +00008014 if (CXXMethodDecl *MoveAssign =
8015 LookupMovingAssignment(FieldClassDecl,
8016 FieldType.getCVRQualifiers(),
8017 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008018 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008019 }
8020 }
8021
8022 return ExceptSpec;
8023}
8024
Richard Smith1c931be2012-04-02 18:40:40 +00008025/// Determine whether the class type has any direct or indirect virtual base
8026/// classes which have a non-trivial move assignment operator.
8027static bool
8028hasVirtualBaseWithNonTrivialMoveAssignment(Sema &S, CXXRecordDecl *ClassDecl) {
8029 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8030 BaseEnd = ClassDecl->vbases_end();
8031 Base != BaseEnd; ++Base) {
8032 CXXRecordDecl *BaseClass =
8033 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8034
8035 // Try to declare the move assignment. If it would be deleted, then the
8036 // class does not have a non-trivial move assignment.
8037 if (BaseClass->needsImplicitMoveAssignment())
8038 S.DeclareImplicitMoveAssignment(BaseClass);
8039
8040 // If the class has both a trivial move assignment and a non-trivial move
8041 // assignment, hasTrivialMoveAssignment() is false.
8042 if (BaseClass->hasDeclaredMoveAssignment() &&
8043 !BaseClass->hasTrivialMoveAssignment())
8044 return true;
8045 }
8046
8047 return false;
8048}
8049
8050/// Determine whether the given type either has a move constructor or is
8051/// trivially copyable.
8052static bool
8053hasMoveOrIsTriviallyCopyable(Sema &S, QualType Type, bool IsConstructor) {
8054 Type = S.Context.getBaseElementType(Type);
8055
8056 // FIXME: Technically, non-trivially-copyable non-class types, such as
8057 // reference types, are supposed to return false here, but that appears
8058 // to be a standard defect.
8059 CXXRecordDecl *ClassDecl = Type->getAsCXXRecordDecl();
Richard Smith5d59b792012-04-25 18:28:49 +00008060 if (!ClassDecl || !ClassDecl->getDefinition())
Richard Smith1c931be2012-04-02 18:40:40 +00008061 return true;
8062
8063 if (Type.isTriviallyCopyableType(S.Context))
8064 return true;
8065
8066 if (IsConstructor) {
8067 if (ClassDecl->needsImplicitMoveConstructor())
8068 S.DeclareImplicitMoveConstructor(ClassDecl);
8069 return ClassDecl->hasDeclaredMoveConstructor();
8070 }
8071
8072 if (ClassDecl->needsImplicitMoveAssignment())
8073 S.DeclareImplicitMoveAssignment(ClassDecl);
8074 return ClassDecl->hasDeclaredMoveAssignment();
8075}
8076
8077/// Determine whether all non-static data members and direct or virtual bases
8078/// of class \p ClassDecl have either a move operation, or are trivially
8079/// copyable.
8080static bool subobjectsHaveMoveOrTrivialCopy(Sema &S, CXXRecordDecl *ClassDecl,
8081 bool IsConstructor) {
8082 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8083 BaseEnd = ClassDecl->bases_end();
8084 Base != BaseEnd; ++Base) {
8085 if (Base->isVirtual())
8086 continue;
8087
8088 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
8089 return false;
8090 }
8091
8092 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8093 BaseEnd = ClassDecl->vbases_end();
8094 Base != BaseEnd; ++Base) {
8095 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
8096 return false;
8097 }
8098
8099 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8100 FieldEnd = ClassDecl->field_end();
8101 Field != FieldEnd; ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00008102 if (!hasMoveOrIsTriviallyCopyable(S, Field->getType(), IsConstructor))
Richard Smith1c931be2012-04-02 18:40:40 +00008103 return false;
8104 }
8105
8106 return true;
8107}
8108
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008109CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00008110 // C++11 [class.copy]p20:
8111 // If the definition of a class X does not explicitly declare a move
8112 // assignment operator, one will be implicitly declared as defaulted
8113 // if and only if:
8114 //
8115 // - [first 4 bullets]
8116 assert(ClassDecl->needsImplicitMoveAssignment());
8117
8118 // [Checked after we build the declaration]
8119 // - the move assignment operator would not be implicitly defined as
8120 // deleted,
8121
8122 // [DR1402]:
8123 // - X has no direct or indirect virtual base class with a non-trivial
8124 // move assignment operator, and
8125 // - each of X's non-static data members and direct or virtual base classes
8126 // has a type that either has a move assignment operator or is trivially
8127 // copyable.
8128 if (hasVirtualBaseWithNonTrivialMoveAssignment(*this, ClassDecl) ||
8129 !subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl,/*Constructor*/false)) {
8130 ClassDecl->setFailedImplicitMoveAssignment();
8131 return 0;
8132 }
8133
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008134 // Note: The following rules are largely analoguous to the move
8135 // constructor rules.
8136
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008137 QualType ArgType = Context.getTypeDeclType(ClassDecl);
8138 QualType RetType = Context.getLValueReferenceType(ArgType);
8139 ArgType = Context.getRValueReferenceType(ArgType);
8140
8141 // An implicitly-declared move assignment operator is an inline public
8142 // member of its class.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008143 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8144 SourceLocation ClassLoc = ClassDecl->getLocation();
8145 DeclarationNameInfo NameInfo(Name, ClassLoc);
8146 CXXMethodDecl *MoveAssignment
Richard Smithb9d0b762012-07-27 04:22:15 +00008147 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008148 /*TInfo=*/0, /*isStatic=*/false,
8149 /*StorageClassAsWritten=*/SC_None,
8150 /*isInline=*/true,
8151 /*isConstexpr=*/false,
8152 SourceLocation());
8153 MoveAssignment->setAccess(AS_public);
8154 MoveAssignment->setDefaulted();
8155 MoveAssignment->setImplicit();
8156 MoveAssignment->setTrivial(ClassDecl->hasTrivialMoveAssignment());
8157
Richard Smithb9d0b762012-07-27 04:22:15 +00008158 // Build an exception specification pointing back at this member.
8159 FunctionProtoType::ExtProtoInfo EPI;
8160 EPI.ExceptionSpecType = EST_Unevaluated;
8161 EPI.ExceptionSpecDecl = MoveAssignment;
8162 MoveAssignment->setType(Context.getFunctionType(RetType, &ArgType, 1, EPI));
8163
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008164 // Add the parameter to the operator.
8165 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
8166 ClassLoc, ClassLoc, /*Id=*/0,
8167 ArgType, /*TInfo=*/0,
8168 SC_None,
8169 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008170 MoveAssignment->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008171
8172 // Note that we have added this copy-assignment operator.
8173 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
8174
8175 // C++0x [class.copy]p9:
8176 // If the definition of a class X does not explicitly declare a move
8177 // assignment operator, one will be implicitly declared as defaulted if and
8178 // only if:
8179 // [...]
8180 // - the move assignment operator would not be implicitly defined as
8181 // deleted.
Richard Smith7d5088a2012-02-18 02:02:13 +00008182 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008183 // Cache this result so that we don't try to generate this over and over
8184 // on every lookup, leaking memory and wasting time.
8185 ClassDecl->setFailedImplicitMoveAssignment();
8186 return 0;
8187 }
8188
8189 if (Scope *S = getScopeForContext(ClassDecl))
8190 PushOnScopeChains(MoveAssignment, S, false);
8191 ClassDecl->addDecl(MoveAssignment);
8192
8193 AddOverriddenMethods(ClassDecl, MoveAssignment);
8194 return MoveAssignment;
8195}
8196
8197void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
8198 CXXMethodDecl *MoveAssignOperator) {
8199 assert((MoveAssignOperator->isDefaulted() &&
8200 MoveAssignOperator->isOverloadedOperator() &&
8201 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00008202 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
8203 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008204 "DefineImplicitMoveAssignment called for wrong function");
8205
8206 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
8207
8208 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
8209 MoveAssignOperator->setInvalidDecl();
8210 return;
8211 }
8212
8213 MoveAssignOperator->setUsed();
8214
8215 ImplicitlyDefinedFunctionScope Scope(*this, MoveAssignOperator);
8216 DiagnosticErrorTrap Trap(Diags);
8217
8218 // C++0x [class.copy]p28:
8219 // The implicitly-defined or move assignment operator for a non-union class
8220 // X performs memberwise move assignment of its subobjects. The direct base
8221 // classes of X are assigned first, in the order of their declaration in the
8222 // base-specifier-list, and then the immediate non-static data members of X
8223 // are assigned, in the order in which they were declared in the class
8224 // definition.
8225
8226 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00008227 SmallVector<Stmt*, 8> Statements;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008228
8229 // The parameter for the "other" object, which we are move from.
8230 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
8231 QualType OtherRefType = Other->getType()->
8232 getAs<RValueReferenceType>()->getPointeeType();
8233 assert(OtherRefType.getQualifiers() == 0 &&
8234 "Bad argument type of defaulted move assignment");
8235
8236 // Our location for everything implicitly-generated.
8237 SourceLocation Loc = MoveAssignOperator->getLocation();
8238
8239 // Construct a reference to the "other" object. We'll be using this
8240 // throughout the generated ASTs.
8241 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
8242 assert(OtherRef && "Reference to parameter cannot fail!");
8243 // Cast to rvalue.
8244 OtherRef = CastForMoving(*this, OtherRef);
8245
8246 // Construct the "this" pointer. We'll be using this throughout the generated
8247 // ASTs.
8248 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8249 assert(This && "Reference to this cannot fail!");
Richard Smith1c931be2012-04-02 18:40:40 +00008250
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008251 // Assign base classes.
8252 bool Invalid = false;
8253 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8254 E = ClassDecl->bases_end(); Base != E; ++Base) {
8255 // Form the assignment:
8256 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
8257 QualType BaseType = Base->getType().getUnqualifiedType();
8258 if (!BaseType->isRecordType()) {
8259 Invalid = true;
8260 continue;
8261 }
8262
8263 CXXCastPath BasePath;
8264 BasePath.push_back(Base);
8265
8266 // Construct the "from" expression, which is an implicit cast to the
8267 // appropriately-qualified base type.
8268 Expr *From = OtherRef;
8269 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
Douglas Gregorb2b56582011-09-06 16:26:56 +00008270 VK_XValue, &BasePath).take();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008271
8272 // Dereference "this".
8273 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8274
8275 // Implicitly cast "this" to the appropriately-qualified base type.
8276 To = ImpCastExprToType(To.take(),
8277 Context.getCVRQualifiedType(BaseType,
8278 MoveAssignOperator->getTypeQualifiers()),
8279 CK_UncheckedDerivedToBase,
8280 VK_LValue, &BasePath);
8281
8282 // Build the move.
8283 StmtResult Move = BuildSingleCopyAssign(*this, Loc, BaseType,
8284 To.get(), From,
8285 /*CopyingBaseSubobject=*/true,
8286 /*Copying=*/false);
8287 if (Move.isInvalid()) {
8288 Diag(CurrentLocation, diag::note_member_synthesized_at)
8289 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8290 MoveAssignOperator->setInvalidDecl();
8291 return;
8292 }
8293
8294 // Success! Record the move.
8295 Statements.push_back(Move.takeAs<Expr>());
8296 }
8297
8298 // \brief Reference to the __builtin_memcpy function.
8299 Expr *BuiltinMemCpyRef = 0;
8300 // \brief Reference to the __builtin_objc_memmove_collectable function.
8301 Expr *CollectableMemCpyRef = 0;
8302
8303 // Assign non-static members.
8304 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8305 FieldEnd = ClassDecl->field_end();
8306 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00008307 if (Field->isUnnamedBitfield())
8308 continue;
8309
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008310 // Check for members of reference type; we can't move those.
8311 if (Field->getType()->isReferenceType()) {
8312 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8313 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8314 Diag(Field->getLocation(), diag::note_declared_at);
8315 Diag(CurrentLocation, diag::note_member_synthesized_at)
8316 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8317 Invalid = true;
8318 continue;
8319 }
8320
8321 // Check for members of const-qualified, non-class type.
8322 QualType BaseType = Context.getBaseElementType(Field->getType());
8323 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8324 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8325 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8326 Diag(Field->getLocation(), diag::note_declared_at);
8327 Diag(CurrentLocation, diag::note_member_synthesized_at)
8328 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8329 Invalid = true;
8330 continue;
8331 }
8332
8333 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00008334 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8335 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008336
8337 QualType FieldType = Field->getType().getNonReferenceType();
8338 if (FieldType->isIncompleteArrayType()) {
8339 assert(ClassDecl->hasFlexibleArrayMember() &&
8340 "Incomplete array type is not valid");
8341 continue;
8342 }
8343
8344 // Build references to the field in the object we're copying from and to.
8345 CXXScopeSpec SS; // Intentionally empty
8346 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8347 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00008348 MemberLookup.addDecl(*Field);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008349 MemberLookup.resolveKind();
8350 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
8351 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008352 SS, SourceLocation(), 0,
8353 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008354 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
8355 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008356 SS, SourceLocation(), 0,
8357 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008358 assert(!From.isInvalid() && "Implicit field reference cannot fail");
8359 assert(!To.isInvalid() && "Implicit field reference cannot fail");
8360
8361 assert(!From.get()->isLValue() && // could be xvalue or prvalue
8362 "Member reference with rvalue base must be rvalue except for reference "
8363 "members, which aren't allowed for move assignment.");
8364
8365 // If the field should be copied with __builtin_memcpy rather than via
8366 // explicit assignments, do so. This optimization only applies for arrays
8367 // of scalars and arrays of class type with trivial move-assignment
8368 // operators.
8369 if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
8370 && BaseType.hasTrivialAssignment(Context, /*Copying=*/false)) {
8371 // Compute the size of the memory buffer to be copied.
8372 QualType SizeType = Context.getSizeType();
8373 llvm::APInt Size(Context.getTypeSize(SizeType),
8374 Context.getTypeSizeInChars(BaseType).getQuantity());
8375 for (const ConstantArrayType *Array
8376 = Context.getAsConstantArrayType(FieldType);
8377 Array;
8378 Array = Context.getAsConstantArrayType(Array->getElementType())) {
8379 llvm::APInt ArraySize
8380 = Array->getSize().zextOrTrunc(Size.getBitWidth());
8381 Size *= ArraySize;
8382 }
8383
Douglas Gregor45d3d712011-09-01 02:09:07 +00008384 // Take the address of the field references for "from" and "to". We
8385 // directly construct UnaryOperators here because semantic analysis
8386 // does not permit us to take the address of an xvalue.
8387 From = new (Context) UnaryOperator(From.get(), UO_AddrOf,
8388 Context.getPointerType(From.get()->getType()),
8389 VK_RValue, OK_Ordinary, Loc);
8390 To = new (Context) UnaryOperator(To.get(), UO_AddrOf,
8391 Context.getPointerType(To.get()->getType()),
8392 VK_RValue, OK_Ordinary, Loc);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008393
8394 bool NeedsCollectableMemCpy =
8395 (BaseType->isRecordType() &&
8396 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
8397
8398 if (NeedsCollectableMemCpy) {
8399 if (!CollectableMemCpyRef) {
8400 // Create a reference to the __builtin_objc_memmove_collectable function.
8401 LookupResult R(*this,
8402 &Context.Idents.get("__builtin_objc_memmove_collectable"),
8403 Loc, LookupOrdinaryName);
8404 LookupName(R, TUScope, true);
8405
8406 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
8407 if (!CollectableMemCpy) {
8408 // Something went horribly wrong earlier, and we will have
8409 // complained about it.
8410 Invalid = true;
8411 continue;
8412 }
8413
8414 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
Eli Friedmana6c66ce2012-08-31 00:14:07 +00008415 Context.BuiltinFnTy,
8416 VK_RValue, Loc, 0).take();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008417 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
8418 }
8419 }
8420 // Create a reference to the __builtin_memcpy builtin function.
8421 else if (!BuiltinMemCpyRef) {
8422 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
8423 LookupOrdinaryName);
8424 LookupName(R, TUScope, true);
8425
8426 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
8427 if (!BuiltinMemCpy) {
8428 // Something went horribly wrong earlier, and we will have complained
8429 // about it.
8430 Invalid = true;
8431 continue;
8432 }
8433
8434 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
Eli Friedmana6c66ce2012-08-31 00:14:07 +00008435 Context.BuiltinFnTy,
8436 VK_RValue, Loc, 0).take();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008437 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
8438 }
8439
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00008440 SmallVector<Expr*, 8> CallArgs;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008441 CallArgs.push_back(To.takeAs<Expr>());
8442 CallArgs.push_back(From.takeAs<Expr>());
8443 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
8444 ExprResult Call = ExprError();
8445 if (NeedsCollectableMemCpy)
8446 Call = ActOnCallExpr(/*Scope=*/0,
8447 CollectableMemCpyRef,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00008448 Loc, CallArgs,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008449 Loc);
8450 else
8451 Call = ActOnCallExpr(/*Scope=*/0,
8452 BuiltinMemCpyRef,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00008453 Loc, CallArgs,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008454 Loc);
8455
8456 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8457 Statements.push_back(Call.takeAs<Expr>());
8458 continue;
8459 }
8460
8461 // Build the move of this field.
8462 StmtResult Move = BuildSingleCopyAssign(*this, Loc, FieldType,
8463 To.get(), From.get(),
8464 /*CopyingBaseSubobject=*/false,
8465 /*Copying=*/false);
8466 if (Move.isInvalid()) {
8467 Diag(CurrentLocation, diag::note_member_synthesized_at)
8468 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8469 MoveAssignOperator->setInvalidDecl();
8470 return;
8471 }
8472
8473 // Success! Record the copy.
8474 Statements.push_back(Move.takeAs<Stmt>());
8475 }
8476
8477 if (!Invalid) {
8478 // Add a "return *this;"
8479 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8480
8481 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
8482 if (Return.isInvalid())
8483 Invalid = true;
8484 else {
8485 Statements.push_back(Return.takeAs<Stmt>());
8486
8487 if (Trap.hasErrorOccurred()) {
8488 Diag(CurrentLocation, diag::note_member_synthesized_at)
8489 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8490 Invalid = true;
8491 }
8492 }
8493 }
8494
8495 if (Invalid) {
8496 MoveAssignOperator->setInvalidDecl();
8497 return;
8498 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008499
8500 StmtResult Body;
8501 {
8502 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00008503 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008504 /*isStmtExpr=*/false);
8505 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8506 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008507 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
8508
8509 if (ASTMutationListener *L = getASTMutationListener()) {
8510 L->CompletedImplicitDefinition(MoveAssignOperator);
8511 }
8512}
8513
Richard Smithb9d0b762012-07-27 04:22:15 +00008514/// Determine whether an implicit copy constructor for ClassDecl has a const
8515/// argument.
8516/// FIXME: It ought to be possible to store this on the record.
8517static bool isImplicitCopyCtorArgConst(Sema &S, CXXRecordDecl *ClassDecl) {
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008518 if (ClassDecl->isInvalidDecl())
Richard Smithb9d0b762012-07-27 04:22:15 +00008519 return true;
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008520
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008521 // C++ [class.copy]p5:
8522 // The implicitly-declared copy constructor for a class X will
8523 // have the form
8524 //
8525 // X::X(const X&)
8526 //
8527 // if
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008528 // -- each direct or virtual base class B of X has a copy
8529 // constructor whose first parameter is of type const B& or
8530 // const volatile B&, and
8531 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8532 BaseEnd = ClassDecl->bases_end();
Richard Smithb9d0b762012-07-27 04:22:15 +00008533 Base != BaseEnd; ++Base) {
Douglas Gregor598a8542010-07-01 18:27:03 +00008534 // Virtual bases are handled below.
8535 if (Base->isVirtual())
8536 continue;
Richard Smithb9d0b762012-07-27 04:22:15 +00008537
Douglas Gregor22584312010-07-02 23:41:54 +00008538 CXXRecordDecl *BaseClassDecl
Douglas Gregor598a8542010-07-01 18:27:03 +00008539 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Richard Smithb9d0b762012-07-27 04:22:15 +00008540 // FIXME: This lookup is wrong. If the copy ctor for a member or base is
8541 // ambiguous, we should still produce a constructor with a const-qualified
8542 // parameter.
8543 if (!S.LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const))
8544 return false;
Douglas Gregor598a8542010-07-01 18:27:03 +00008545 }
8546
8547 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8548 BaseEnd = ClassDecl->vbases_end();
Richard Smithb9d0b762012-07-27 04:22:15 +00008549 Base != BaseEnd; ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00008550 CXXRecordDecl *BaseClassDecl
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008551 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Richard Smithb9d0b762012-07-27 04:22:15 +00008552 if (!S.LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const))
8553 return false;
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008554 }
Richard Smithb9d0b762012-07-27 04:22:15 +00008555
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008556 // -- for all the nonstatic data members of X that are of a
8557 // class type M (or array thereof), each such class type
8558 // has a copy constructor whose first parameter is of type
8559 // const M& or const volatile M&.
8560 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8561 FieldEnd = ClassDecl->field_end();
Richard Smithb9d0b762012-07-27 04:22:15 +00008562 Field != FieldEnd; ++Field) {
8563 QualType FieldType = S.Context.getBaseElementType(Field->getType());
Sean Huntc530d172011-06-10 04:44:37 +00008564 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smithb9d0b762012-07-27 04:22:15 +00008565 if (!S.LookupCopyingConstructor(FieldClassDecl, Qualifiers::Const))
8566 return false;
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008567 }
8568 }
Richard Smithb9d0b762012-07-27 04:22:15 +00008569
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008570 // Otherwise, the implicitly declared copy constructor will have
8571 // the form
8572 //
8573 // X::X(X&)
Richard Smithb9d0b762012-07-27 04:22:15 +00008574
8575 return true;
8576}
8577
8578Sema::ImplicitExceptionSpecification
8579Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
8580 CXXRecordDecl *ClassDecl = MD->getParent();
8581
8582 ImplicitExceptionSpecification ExceptSpec(*this);
8583 if (ClassDecl->isInvalidDecl())
8584 return ExceptSpec;
8585
8586 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
8587 assert(T->getNumArgs() >= 1 && "not a copy ctor");
8588 unsigned Quals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
8589
Douglas Gregor0d405db2010-07-01 20:59:04 +00008590 // C++ [except.spec]p14:
8591 // An implicitly declared special member function (Clause 12) shall have an
8592 // exception-specification. [...]
Douglas Gregor0d405db2010-07-01 20:59:04 +00008593 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8594 BaseEnd = ClassDecl->bases_end();
8595 Base != BaseEnd;
8596 ++Base) {
8597 // Virtual bases are handled below.
8598 if (Base->isVirtual())
8599 continue;
8600
Douglas Gregor22584312010-07-02 23:41:54 +00008601 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00008602 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00008603 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008604 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00008605 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00008606 }
8607 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8608 BaseEnd = ClassDecl->vbases_end();
8609 Base != BaseEnd;
8610 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00008611 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00008612 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00008613 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008614 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00008615 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00008616 }
8617 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8618 FieldEnd = ClassDecl->field_end();
8619 Field != FieldEnd;
8620 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00008621 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Huntc530d172011-06-10 04:44:37 +00008622 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8623 if (CXXConstructorDecl *CopyConstructor =
Richard Smith6a06e5f2012-07-18 03:36:00 +00008624 LookupCopyingConstructor(FieldClassDecl,
8625 Quals | FieldType.getCVRQualifiers()))
Richard Smithe6975e92012-04-17 00:58:00 +00008626 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00008627 }
8628 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008629
Richard Smithb9d0b762012-07-27 04:22:15 +00008630 return ExceptSpec;
Sean Hunt49634cf2011-05-13 06:10:58 +00008631}
8632
8633CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
8634 CXXRecordDecl *ClassDecl) {
8635 // C++ [class.copy]p4:
8636 // If the class definition does not explicitly declare a copy
8637 // constructor, one is declared implicitly.
8638
Sean Hunt49634cf2011-05-13 06:10:58 +00008639 QualType ClassType = Context.getTypeDeclType(ClassDecl);
8640 QualType ArgType = ClassType;
Richard Smithb9d0b762012-07-27 04:22:15 +00008641 bool Const = isImplicitCopyCtorArgConst(*this, ClassDecl);
Sean Hunt49634cf2011-05-13 06:10:58 +00008642 if (Const)
8643 ArgType = ArgType.withConst();
8644 ArgType = Context.getLValueReferenceType(ArgType);
Sean Hunt49634cf2011-05-13 06:10:58 +00008645
Richard Smith7756afa2012-06-10 05:43:50 +00008646 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8647 CXXCopyConstructor,
8648 Const);
8649
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008650 DeclarationName Name
8651 = Context.DeclarationNames.getCXXConstructorName(
8652 Context.getCanonicalType(ClassType));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008653 SourceLocation ClassLoc = ClassDecl->getLocation();
8654 DeclarationNameInfo NameInfo(Name, ClassLoc);
Sean Hunt49634cf2011-05-13 06:10:58 +00008655
8656 // An implicitly-declared copy constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00008657 // member of its class.
8658 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00008659 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00008660 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00008661 Constexpr);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008662 CopyConstructor->setAccess(AS_public);
Sean Hunt49634cf2011-05-13 06:10:58 +00008663 CopyConstructor->setDefaulted();
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008664 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
Richard Smith61802452011-12-22 02:22:31 +00008665
Richard Smithb9d0b762012-07-27 04:22:15 +00008666 // Build an exception specification pointing back at this member.
8667 FunctionProtoType::ExtProtoInfo EPI;
8668 EPI.ExceptionSpecType = EST_Unevaluated;
8669 EPI.ExceptionSpecDecl = CopyConstructor;
8670 CopyConstructor->setType(
8671 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
8672
Douglas Gregor22584312010-07-02 23:41:54 +00008673 // Note that we have declared this constructor.
Douglas Gregor22584312010-07-02 23:41:54 +00008674 ++ASTContext::NumImplicitCopyConstructorsDeclared;
8675
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008676 // Add the parameter to the constructor.
8677 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008678 ClassLoc, ClassLoc,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008679 /*IdentifierInfo=*/0,
8680 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00008681 SC_None,
8682 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008683 CopyConstructor->setParams(FromParam);
Sean Hunt49634cf2011-05-13 06:10:58 +00008684
Douglas Gregor23c94db2010-07-02 17:43:08 +00008685 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor22584312010-07-02 23:41:54 +00008686 PushOnScopeChains(CopyConstructor, S, false);
8687 ClassDecl->addDecl(CopyConstructor);
Sean Hunt71a682f2011-05-18 03:41:58 +00008688
Nico Weberafcc96a2012-01-23 03:19:29 +00008689 // C++11 [class.copy]p8:
8690 // ... If the class definition does not explicitly declare a copy
8691 // constructor, there is no user-declared move constructor, and there is no
8692 // user-declared move assignment operator, a copy constructor is implicitly
8693 // declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00008694 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Sean Hunt71a682f2011-05-18 03:41:58 +00008695 CopyConstructor->setDeletedAsWritten();
Richard Smith6c4c36c2012-03-30 20:53:28 +00008696
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008697 return CopyConstructor;
8698}
8699
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008700void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Sean Hunt49634cf2011-05-13 06:10:58 +00008701 CXXConstructorDecl *CopyConstructor) {
8702 assert((CopyConstructor->isDefaulted() &&
8703 CopyConstructor->isCopyConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00008704 !CopyConstructor->doesThisDeclarationHaveABody() &&
8705 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008706 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00008707
Anders Carlsson63010a72010-04-23 16:24:12 +00008708 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008709 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008710
Douglas Gregor39957dc2010-05-01 15:04:51 +00008711 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008712 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008713
Sean Huntcbb67482011-01-08 20:30:50 +00008714 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008715 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00008716 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008717 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00008718 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008719 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008720 Sema::CompoundScopeRAII CompoundScope(*this);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008721 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
8722 CopyConstructor->getLocation(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00008723 MultiStmtArg(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008724 /*isStmtExpr=*/false)
8725 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00008726 CopyConstructor->setImplicitlyDefined(true);
Anders Carlsson8e142cc2010-04-25 00:52:09 +00008727 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008728
8729 CopyConstructor->setUsed();
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008730 if (ASTMutationListener *L = getASTMutationListener()) {
8731 L->CompletedImplicitDefinition(CopyConstructor);
8732 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008733}
8734
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008735Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00008736Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
8737 CXXRecordDecl *ClassDecl = MD->getParent();
8738
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008739 // C++ [except.spec]p14:
8740 // An implicitly declared special member function (Clause 12) shall have an
8741 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00008742 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008743 if (ClassDecl->isInvalidDecl())
8744 return ExceptSpec;
8745
8746 // Direct base-class constructors.
8747 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8748 BEnd = ClassDecl->bases_end();
8749 B != BEnd; ++B) {
8750 if (B->isVirtual()) // Handled below.
8751 continue;
8752
8753 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8754 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +00008755 CXXConstructorDecl *Constructor =
8756 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008757 // If this is a deleted function, add it anyway. This might be conformant
8758 // with the standard. This might not. I'm not sure. It might not matter.
8759 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00008760 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008761 }
8762 }
8763
8764 // Virtual base-class constructors.
8765 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8766 BEnd = ClassDecl->vbases_end();
8767 B != BEnd; ++B) {
8768 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8769 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +00008770 CXXConstructorDecl *Constructor =
8771 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008772 // If this is a deleted function, add it anyway. This might be conformant
8773 // with the standard. This might not. I'm not sure. It might not matter.
8774 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00008775 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008776 }
8777 }
8778
8779 // Field constructors.
8780 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8781 FEnd = ClassDecl->field_end();
8782 F != FEnd; ++F) {
Richard Smith6a06e5f2012-07-18 03:36:00 +00008783 QualType FieldType = Context.getBaseElementType(F->getType());
8784 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
8785 CXXConstructorDecl *Constructor =
8786 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008787 // If this is a deleted function, add it anyway. This might be conformant
8788 // with the standard. This might not. I'm not sure. It might not matter.
8789 // In particular, the problem is that this function never gets called. It
8790 // might just be ill-formed because this function attempts to refer to
8791 // a deleted function here.
8792 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00008793 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008794 }
8795 }
8796
8797 return ExceptSpec;
8798}
8799
8800CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
8801 CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00008802 // C++11 [class.copy]p9:
8803 // If the definition of a class X does not explicitly declare a move
8804 // constructor, one will be implicitly declared as defaulted if and only if:
8805 //
8806 // - [first 4 bullets]
8807 assert(ClassDecl->needsImplicitMoveConstructor());
8808
8809 // [Checked after we build the declaration]
8810 // - the move assignment operator would not be implicitly defined as
8811 // deleted,
8812
8813 // [DR1402]:
8814 // - each of X's non-static data members and direct or virtual base classes
8815 // has a type that either has a move constructor or is trivially copyable.
8816 if (!subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl, /*Constructor*/true)) {
8817 ClassDecl->setFailedImplicitMoveConstructor();
8818 return 0;
8819 }
8820
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008821 QualType ClassType = Context.getTypeDeclType(ClassDecl);
8822 QualType ArgType = Context.getRValueReferenceType(ClassType);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008823
Richard Smith7756afa2012-06-10 05:43:50 +00008824 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8825 CXXMoveConstructor,
8826 false);
8827
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008828 DeclarationName Name
8829 = Context.DeclarationNames.getCXXConstructorName(
8830 Context.getCanonicalType(ClassType));
8831 SourceLocation ClassLoc = ClassDecl->getLocation();
8832 DeclarationNameInfo NameInfo(Name, ClassLoc);
8833
8834 // C++0x [class.copy]p11:
8835 // An implicitly-declared copy/move constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00008836 // member of its class.
8837 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00008838 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00008839 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00008840 Constexpr);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008841 MoveConstructor->setAccess(AS_public);
8842 MoveConstructor->setDefaulted();
8843 MoveConstructor->setTrivial(ClassDecl->hasTrivialMoveConstructor());
Richard Smith61802452011-12-22 02:22:31 +00008844
Richard Smithb9d0b762012-07-27 04:22:15 +00008845 // Build an exception specification pointing back at this member.
8846 FunctionProtoType::ExtProtoInfo EPI;
8847 EPI.ExceptionSpecType = EST_Unevaluated;
8848 EPI.ExceptionSpecDecl = MoveConstructor;
8849 MoveConstructor->setType(
8850 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
8851
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008852 // Add the parameter to the constructor.
8853 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
8854 ClassLoc, ClassLoc,
8855 /*IdentifierInfo=*/0,
8856 ArgType, /*TInfo=*/0,
8857 SC_None,
8858 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008859 MoveConstructor->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008860
8861 // C++0x [class.copy]p9:
8862 // If the definition of a class X does not explicitly declare a move
8863 // constructor, one will be implicitly declared as defaulted if and only if:
8864 // [...]
8865 // - the move constructor would not be implicitly defined as deleted.
Sean Hunt769bb2d2011-10-11 06:43:29 +00008866 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008867 // Cache this result so that we don't try to generate this over and over
8868 // on every lookup, leaking memory and wasting time.
8869 ClassDecl->setFailedImplicitMoveConstructor();
8870 return 0;
8871 }
8872
8873 // Note that we have declared this constructor.
8874 ++ASTContext::NumImplicitMoveConstructorsDeclared;
8875
8876 if (Scope *S = getScopeForContext(ClassDecl))
8877 PushOnScopeChains(MoveConstructor, S, false);
8878 ClassDecl->addDecl(MoveConstructor);
8879
8880 return MoveConstructor;
8881}
8882
8883void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
8884 CXXConstructorDecl *MoveConstructor) {
8885 assert((MoveConstructor->isDefaulted() &&
8886 MoveConstructor->isMoveConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00008887 !MoveConstructor->doesThisDeclarationHaveABody() &&
8888 !MoveConstructor->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008889 "DefineImplicitMoveConstructor - call it for implicit move ctor");
8890
8891 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
8892 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
8893
8894 ImplicitlyDefinedFunctionScope Scope(*this, MoveConstructor);
8895 DiagnosticErrorTrap Trap(Diags);
8896
8897 if (SetCtorInitializers(MoveConstructor, 0, 0, /*AnyErrors=*/false) ||
8898 Trap.hasErrorOccurred()) {
8899 Diag(CurrentLocation, diag::note_member_synthesized_at)
8900 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
8901 MoveConstructor->setInvalidDecl();
8902 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008903 Sema::CompoundScopeRAII CompoundScope(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008904 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
8905 MoveConstructor->getLocation(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00008906 MultiStmtArg(),
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008907 /*isStmtExpr=*/false)
8908 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00008909 MoveConstructor->setImplicitlyDefined(true);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008910 }
8911
8912 MoveConstructor->setUsed();
8913
8914 if (ASTMutationListener *L = getASTMutationListener()) {
8915 L->CompletedImplicitDefinition(MoveConstructor);
8916 }
8917}
8918
Douglas Gregore4e68d42012-02-15 19:33:52 +00008919bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
8920 return FD->isDeleted() &&
8921 (FD->isDefaulted() || FD->isImplicit()) &&
8922 isa<CXXMethodDecl>(FD);
8923}
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008924
Douglas Gregor27dd7d92012-02-17 03:02:34 +00008925/// \brief Mark the call operator of the given lambda closure type as "used".
8926static void markLambdaCallOperatorUsed(Sema &S, CXXRecordDecl *Lambda) {
8927 CXXMethodDecl *CallOperator
Douglas Gregorac1303e2012-02-22 05:02:47 +00008928 = cast<CXXMethodDecl>(
8929 *Lambda->lookup(
8930 S.Context.DeclarationNames.getCXXOperatorName(OO_Call)).first);
Douglas Gregor27dd7d92012-02-17 03:02:34 +00008931 CallOperator->setReferenced();
8932 CallOperator->setUsed();
8933}
8934
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008935void Sema::DefineImplicitLambdaToFunctionPointerConversion(
8936 SourceLocation CurrentLocation,
8937 CXXConversionDecl *Conv)
8938{
Douglas Gregor27dd7d92012-02-17 03:02:34 +00008939 CXXRecordDecl *Lambda = Conv->getParent();
8940
8941 // Make sure that the lambda call operator is marked used.
8942 markLambdaCallOperatorUsed(*this, Lambda);
8943
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008944 Conv->setUsed();
8945
8946 ImplicitlyDefinedFunctionScope Scope(*this, Conv);
8947 DiagnosticErrorTrap Trap(Diags);
8948
Douglas Gregor27dd7d92012-02-17 03:02:34 +00008949 // Return the address of the __invoke function.
8950 DeclarationName InvokeName = &Context.Idents.get("__invoke");
8951 CXXMethodDecl *Invoke
8952 = cast<CXXMethodDecl>(*Lambda->lookup(InvokeName).first);
8953 Expr *FunctionRef = BuildDeclRefExpr(Invoke, Invoke->getType(),
8954 VK_LValue, Conv->getLocation()).take();
8955 assert(FunctionRef && "Can't refer to __invoke function?");
8956 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
8957 Conv->setBody(new (Context) CompoundStmt(Context, &Return, 1,
8958 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008959 Conv->getLocation()));
Douglas Gregor27dd7d92012-02-17 03:02:34 +00008960
8961 // Fill in the __invoke function with a dummy implementation. IR generation
8962 // will fill in the actual details.
8963 Invoke->setUsed();
8964 Invoke->setReferenced();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00008965 Invoke->setBody(new (Context) CompoundStmt(Conv->getLocation()));
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008966
8967 if (ASTMutationListener *L = getASTMutationListener()) {
8968 L->CompletedImplicitDefinition(Conv);
Douglas Gregor27dd7d92012-02-17 03:02:34 +00008969 L->CompletedImplicitDefinition(Invoke);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008970 }
8971}
8972
8973void Sema::DefineImplicitLambdaToBlockPointerConversion(
8974 SourceLocation CurrentLocation,
8975 CXXConversionDecl *Conv)
8976{
8977 Conv->setUsed();
8978
8979 ImplicitlyDefinedFunctionScope Scope(*this, Conv);
8980 DiagnosticErrorTrap Trap(Diags);
8981
Douglas Gregorac1303e2012-02-22 05:02:47 +00008982 // Copy-initialize the lambda object as needed to capture it.
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008983 Expr *This = ActOnCXXThis(CurrentLocation).take();
8984 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008985
Eli Friedman23f02672012-03-01 04:01:32 +00008986 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
8987 Conv->getLocation(),
8988 Conv, DerefThis);
8989
8990 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
8991 // behavior. Note that only the general conversion function does this
8992 // (since it's unusable otherwise); in the case where we inline the
8993 // block literal, it has block literal lifetime semantics.
David Blaikie4e4d0842012-03-11 07:00:24 +00008994 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman23f02672012-03-01 04:01:32 +00008995 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
8996 CK_CopyAndAutoreleaseBlockObject,
8997 BuildBlock.get(), 0, VK_RValue);
8998
8999 if (BuildBlock.isInvalid()) {
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009000 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregorac1303e2012-02-22 05:02:47 +00009001 Conv->setInvalidDecl();
9002 return;
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009003 }
Douglas Gregorac1303e2012-02-22 05:02:47 +00009004
Douglas Gregorac1303e2012-02-22 05:02:47 +00009005 // Create the return statement that returns the block from the conversion
9006 // function.
Eli Friedman23f02672012-03-01 04:01:32 +00009007 StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregorac1303e2012-02-22 05:02:47 +00009008 if (Return.isInvalid()) {
9009 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
9010 Conv->setInvalidDecl();
9011 return;
9012 }
9013
9014 // Set the body of the conversion function.
9015 Stmt *ReturnS = Return.take();
9016 Conv->setBody(new (Context) CompoundStmt(Context, &ReturnS, 1,
9017 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009018 Conv->getLocation()));
9019
Douglas Gregorac1303e2012-02-22 05:02:47 +00009020 // We're done; notify the mutation listener, if any.
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009021 if (ASTMutationListener *L = getASTMutationListener()) {
9022 L->CompletedImplicitDefinition(Conv);
9023 }
9024}
9025
Douglas Gregorf52757d2012-03-10 06:53:13 +00009026/// \brief Determine whether the given list arguments contains exactly one
9027/// "real" (non-default) argument.
9028static bool hasOneRealArgument(MultiExprArg Args) {
9029 switch (Args.size()) {
9030 case 0:
9031 return false;
9032
9033 default:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009034 if (!Args[1]->isDefaultArgument())
Douglas Gregorf52757d2012-03-10 06:53:13 +00009035 return false;
9036
9037 // fall through
9038 case 1:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009039 return !Args[0]->isDefaultArgument();
Douglas Gregorf52757d2012-03-10 06:53:13 +00009040 }
9041
9042 return false;
9043}
9044
John McCall60d7b3a2010-08-24 06:29:42 +00009045ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00009046Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00009047 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00009048 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009049 bool HadMultipleCandidates,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009050 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009051 unsigned ConstructKind,
9052 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009053 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00009054
Douglas Gregor2f599792010-04-02 18:24:57 +00009055 // C++0x [class.copy]p34:
9056 // When certain criteria are met, an implementation is allowed to
9057 // omit the copy/move construction of a class object, even if the
9058 // copy/move constructor and/or destructor for the object have
9059 // side effects. [...]
9060 // - when a temporary class object that has not been bound to a
9061 // reference (12.2) would be copied/moved to a class object
9062 // with the same cv-unqualified type, the copy/move operation
9063 // can be omitted by constructing the temporary object
9064 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +00009065 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregorf52757d2012-03-10 06:53:13 +00009066 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Benjamin Kramer5354e772012-08-23 23:38:35 +00009067 Expr *SubExpr = ExprArgs[0];
John McCall558d2ab2010-09-15 10:14:12 +00009068 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009069 }
Mike Stump1eb44332009-09-09 15:08:12 +00009070
9071 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009072 Elidable, ExprArgs, HadMultipleCandidates,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009073 RequiresZeroInit, ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009074}
9075
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009076/// BuildCXXConstructExpr - Creates a complete call to a constructor,
9077/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00009078ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00009079Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
9080 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00009081 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009082 bool HadMultipleCandidates,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009083 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009084 unsigned ConstructKind,
9085 SourceRange ParenRange) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00009086 MarkFunctionReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00009087 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00009088 Constructor, Elidable, ExprArgs,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00009089 HadMultipleCandidates, /*FIXME*/false,
9090 RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009091 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
9092 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009093}
9094
Mike Stump1eb44332009-09-09 15:08:12 +00009095bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009096 CXXConstructorDecl *Constructor,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009097 MultiExprArg Exprs,
9098 bool HadMultipleCandidates) {
Chandler Carruth428edaf2010-10-25 08:47:36 +00009099 // FIXME: Provide the correct paren SourceRange when available.
John McCall60d7b3a2010-08-24 06:29:42 +00009100 ExprResult TempResult =
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00009101 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009102 Exprs, HadMultipleCandidates, false,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009103 CXXConstructExpr::CK_Complete, SourceRange());
Anders Carlssonfe2de492009-08-25 05:18:00 +00009104 if (TempResult.isInvalid())
9105 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00009106
Anders Carlssonda3f4e22009-08-25 05:12:04 +00009107 Expr *Temp = TempResult.takeAs<Expr>();
John McCallb4eb64d2010-10-08 02:01:28 +00009108 CheckImplicitConversions(Temp, VD->getLocation());
Eli Friedman5f2987c2012-02-02 03:46:19 +00009109 MarkFunctionReferenced(VD->getLocation(), Constructor);
John McCall4765fa02010-12-06 08:20:24 +00009110 Temp = MaybeCreateExprWithCleanups(Temp);
Douglas Gregor838db382010-02-11 01:19:42 +00009111 VD->setInit(Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00009112
Anders Carlssonfe2de492009-08-25 05:18:00 +00009113 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00009114}
9115
John McCall68c6c9a2010-02-02 09:10:11 +00009116void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009117 if (VD->isInvalidDecl()) return;
9118
John McCall68c6c9a2010-02-02 09:10:11 +00009119 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009120 if (ClassDecl->isInvalidDecl()) return;
Richard Smith213d70b2012-02-18 04:13:32 +00009121 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009122 if (ClassDecl->isDependentContext()) return;
John McCall626e96e2010-08-01 20:20:59 +00009123
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009124 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedman5f2987c2012-02-02 03:46:19 +00009125 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009126 CheckDestructorAccess(VD->getLocation(), Destructor,
9127 PDiag(diag::err_access_dtor_var)
9128 << VD->getDeclName()
9129 << VD->getType());
Richard Smith213d70b2012-02-18 04:13:32 +00009130 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson2b32dad2011-03-24 01:01:41 +00009131
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009132 if (!VD->hasGlobalStorage()) return;
9133
9134 // Emit warning for non-trivial dtor in global scope (a real global,
9135 // class-static, function-static).
9136 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
9137
9138 // TODO: this should be re-enabled for static locals by !CXAAtExit
9139 if (!VD->isStaticLocal())
9140 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00009141}
9142
Douglas Gregor39da0b82009-09-09 23:08:42 +00009143/// \brief Given a constructor and the set of arguments provided for the
9144/// constructor, convert the arguments and add any required default arguments
9145/// to form a proper call to this constructor.
9146///
9147/// \returns true if an error occurred, false otherwise.
9148bool
9149Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
9150 MultiExprArg ArgsPtr,
Richard Smith831421f2012-06-25 20:30:08 +00009151 SourceLocation Loc,
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00009152 SmallVectorImpl<Expr*> &ConvertedArgs,
Douglas Gregored878af2012-02-24 23:56:31 +00009153 bool AllowExplicit) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00009154 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
9155 unsigned NumArgs = ArgsPtr.size();
Benjamin Kramer5354e772012-08-23 23:38:35 +00009156 Expr **Args = ArgsPtr.data();
Douglas Gregor39da0b82009-09-09 23:08:42 +00009157
9158 const FunctionProtoType *Proto
9159 = Constructor->getType()->getAs<FunctionProtoType>();
9160 assert(Proto && "Constructor without a prototype?");
9161 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00009162
9163 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009164 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00009165 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009166 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00009167 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009168
9169 VariadicCallType CallType =
9170 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner5f9e2722011-07-23 10:55:15 +00009171 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009172 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
9173 Proto, 0, Args, NumArgs, AllArgs,
Douglas Gregored878af2012-02-24 23:56:31 +00009174 CallType, AllowExplicit);
Benjamin Kramer14c59822012-02-14 12:06:21 +00009175 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmane61eb042012-02-18 04:48:30 +00009176
9177 DiagnoseSentinelCalls(Constructor, Loc, AllArgs.data(), AllArgs.size());
9178
Richard Smith831421f2012-06-25 20:30:08 +00009179 CheckConstructorCall(Constructor, AllArgs.data(), AllArgs.size(),
9180 Proto, Loc);
Eli Friedmane61eb042012-02-18 04:48:30 +00009181
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009182 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00009183}
9184
Anders Carlsson20d45d22009-12-12 00:32:00 +00009185static inline bool
9186CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
9187 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00009188 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +00009189 if (isa<NamespaceDecl>(DC)) {
9190 return SemaRef.Diag(FnDecl->getLocation(),
9191 diag::err_operator_new_delete_declared_in_namespace)
9192 << FnDecl->getDeclName();
9193 }
9194
9195 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +00009196 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00009197 return SemaRef.Diag(FnDecl->getLocation(),
9198 diag::err_operator_new_delete_declared_static)
9199 << FnDecl->getDeclName();
9200 }
9201
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00009202 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00009203}
9204
Anders Carlsson156c78e2009-12-13 17:53:43 +00009205static inline bool
9206CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
9207 CanQualType ExpectedResultType,
9208 CanQualType ExpectedFirstParamType,
9209 unsigned DependentParamTypeDiag,
9210 unsigned InvalidParamTypeDiag) {
9211 QualType ResultType =
9212 FnDecl->getType()->getAs<FunctionType>()->getResultType();
9213
9214 // Check that the result type is not dependent.
9215 if (ResultType->isDependentType())
9216 return SemaRef.Diag(FnDecl->getLocation(),
9217 diag::err_operator_new_delete_dependent_result_type)
9218 << FnDecl->getDeclName() << ExpectedResultType;
9219
9220 // Check that the result type is what we expect.
9221 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
9222 return SemaRef.Diag(FnDecl->getLocation(),
9223 diag::err_operator_new_delete_invalid_result_type)
9224 << FnDecl->getDeclName() << ExpectedResultType;
9225
9226 // A function template must have at least 2 parameters.
9227 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
9228 return SemaRef.Diag(FnDecl->getLocation(),
9229 diag::err_operator_new_delete_template_too_few_parameters)
9230 << FnDecl->getDeclName();
9231
9232 // The function decl must have at least 1 parameter.
9233 if (FnDecl->getNumParams() == 0)
9234 return SemaRef.Diag(FnDecl->getLocation(),
9235 diag::err_operator_new_delete_too_few_parameters)
9236 << FnDecl->getDeclName();
9237
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +00009238 // Check the first parameter type is not dependent.
Anders Carlsson156c78e2009-12-13 17:53:43 +00009239 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
9240 if (FirstParamType->isDependentType())
9241 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
9242 << FnDecl->getDeclName() << ExpectedFirstParamType;
9243
9244 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +00009245 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +00009246 ExpectedFirstParamType)
9247 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
9248 << FnDecl->getDeclName() << ExpectedFirstParamType;
9249
9250 return false;
9251}
9252
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009253static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +00009254CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00009255 // C++ [basic.stc.dynamic.allocation]p1:
9256 // A program is ill-formed if an allocation function is declared in a
9257 // namespace scope other than global scope or declared static in global
9258 // scope.
9259 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9260 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +00009261
9262 CanQualType SizeTy =
9263 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
9264
9265 // C++ [basic.stc.dynamic.allocation]p1:
9266 // The return type shall be void*. The first parameter shall have type
9267 // std::size_t.
9268 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
9269 SizeTy,
9270 diag::err_operator_new_dependent_param_type,
9271 diag::err_operator_new_param_type))
9272 return true;
9273
9274 // C++ [basic.stc.dynamic.allocation]p1:
9275 // The first parameter shall not have an associated default argument.
9276 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +00009277 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +00009278 diag::err_operator_new_default_arg)
9279 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
9280
9281 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +00009282}
9283
9284static bool
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009285CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
9286 // C++ [basic.stc.dynamic.deallocation]p1:
9287 // A program is ill-formed if deallocation functions are declared in a
9288 // namespace scope other than global scope or declared static in global
9289 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +00009290 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9291 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009292
9293 // C++ [basic.stc.dynamic.deallocation]p2:
9294 // Each deallocation function shall return void and its first parameter
9295 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +00009296 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
9297 SemaRef.Context.VoidPtrTy,
9298 diag::err_operator_delete_dependent_param_type,
9299 diag::err_operator_delete_param_type))
9300 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009301
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009302 return false;
9303}
9304
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009305/// CheckOverloadedOperatorDeclaration - Check whether the declaration
9306/// of this overloaded operator is well-formed. If so, returns false;
9307/// otherwise, emits appropriate diagnostics and returns true.
9308bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009309 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009310 "Expected an overloaded operator declaration");
9311
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009312 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
9313
Mike Stump1eb44332009-09-09 15:08:12 +00009314 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009315 // The allocation and deallocation functions, operator new,
9316 // operator new[], operator delete and operator delete[], are
9317 // described completely in 3.7.3. The attributes and restrictions
9318 // found in the rest of this subclause do not apply to them unless
9319 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +00009320 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009321 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00009322
Anders Carlssona3ccda52009-12-12 00:26:23 +00009323 if (Op == OO_New || Op == OO_Array_New)
9324 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009325
9326 // C++ [over.oper]p6:
9327 // An operator function shall either be a non-static member
9328 // function or be a non-member function and have at least one
9329 // parameter whose type is a class, a reference to a class, an
9330 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009331 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
9332 if (MethodDecl->isStatic())
9333 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009334 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009335 } else {
9336 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009337 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
9338 ParamEnd = FnDecl->param_end();
9339 Param != ParamEnd; ++Param) {
9340 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00009341 if (ParamType->isDependentType() || ParamType->isRecordType() ||
9342 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009343 ClassOrEnumParam = true;
9344 break;
9345 }
9346 }
9347
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009348 if (!ClassOrEnumParam)
9349 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009350 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009351 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009352 }
9353
9354 // C++ [over.oper]p8:
9355 // An operator function cannot have default arguments (8.3.6),
9356 // except where explicitly stated below.
9357 //
Mike Stump1eb44332009-09-09 15:08:12 +00009358 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009359 // (C++ [over.call]p1).
9360 if (Op != OO_Call) {
9361 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
9362 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +00009363 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00009364 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00009365 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +00009366 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009367 }
9368 }
9369
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009370 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
9371 { false, false, false }
9372#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
9373 , { Unary, Binary, MemberOnly }
9374#include "clang/Basic/OperatorKinds.def"
9375 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009376
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009377 bool CanBeUnaryOperator = OperatorUses[Op][0];
9378 bool CanBeBinaryOperator = OperatorUses[Op][1];
9379 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009380
9381 // C++ [over.oper]p8:
9382 // [...] Operator functions cannot have more or fewer parameters
9383 // than the number required for the corresponding operator, as
9384 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00009385 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009386 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009387 if (Op != OO_Call &&
9388 ((NumParams == 1 && !CanBeUnaryOperator) ||
9389 (NumParams == 2 && !CanBeBinaryOperator) ||
9390 (NumParams < 1) || (NumParams > 2))) {
9391 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00009392 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009393 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00009394 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009395 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00009396 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009397 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00009398 assert(CanBeBinaryOperator &&
9399 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00009400 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009401 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009402
Chris Lattner416e46f2008-11-21 07:57:12 +00009403 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009404 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009405 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00009406
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009407 // Overloaded operators other than operator() cannot be variadic.
9408 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00009409 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009410 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009411 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009412 }
9413
9414 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009415 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
9416 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009417 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009418 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009419 }
9420
9421 // C++ [over.inc]p1:
9422 // The user-defined function called operator++ implements the
9423 // prefix and postfix ++ operator. If this function is a member
9424 // function with no parameters, or a non-member function with one
9425 // parameter of class or enumeration type, it defines the prefix
9426 // increment operator ++ for objects of that type. If the function
9427 // is a member function with one parameter (which shall be of type
9428 // int) or a non-member function with two parameters (the second
9429 // of which shall be of type int), it defines the postfix
9430 // increment operator ++ for objects of that type.
9431 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
9432 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
9433 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00009434 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009435 ParamIsInt = BT->getKind() == BuiltinType::Int;
9436
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00009437 if (!ParamIsInt)
9438 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00009439 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00009440 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009441 }
9442
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009443 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009444}
Chris Lattner5a003a42008-12-17 07:09:26 +00009445
Sean Hunta6c058d2010-01-13 09:01:02 +00009446/// CheckLiteralOperatorDeclaration - Check whether the declaration
9447/// of this literal operator function is well-formed. If so, returns
9448/// false; otherwise, emits appropriate diagnostics and returns true.
9449bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smithe5658f02012-03-10 22:18:57 +00009450 if (isa<CXXMethodDecl>(FnDecl)) {
Sean Hunta6c058d2010-01-13 09:01:02 +00009451 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
9452 << FnDecl->getDeclName();
9453 return true;
9454 }
9455
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009456 if (FnDecl->isExternC()) {
9457 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
9458 return true;
9459 }
9460
Sean Hunta6c058d2010-01-13 09:01:02 +00009461 bool Valid = false;
9462
Richard Smith36f5cfe2012-03-09 08:00:36 +00009463 // This might be the definition of a literal operator template.
9464 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
9465 // This might be a specialization of a literal operator template.
9466 if (!TpDecl)
9467 TpDecl = FnDecl->getPrimaryTemplate();
9468
Sean Hunt216c2782010-04-07 23:11:06 +00009469 // template <char...> type operator "" name() is the only valid template
9470 // signature, and the only valid signature with no parameters.
Richard Smith36f5cfe2012-03-09 08:00:36 +00009471 if (TpDecl) {
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009472 if (FnDecl->param_size() == 0) {
Sean Hunt216c2782010-04-07 23:11:06 +00009473 // Must have only one template parameter
9474 TemplateParameterList *Params = TpDecl->getTemplateParameters();
9475 if (Params->size() == 1) {
9476 NonTypeTemplateParmDecl *PmDecl =
Richard Smith5295b972012-08-03 21:14:57 +00009477 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +00009478
Sean Hunt216c2782010-04-07 23:11:06 +00009479 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +00009480 if (PmDecl && PmDecl->isTemplateParameterPack() &&
9481 Context.hasSameType(PmDecl->getType(), Context.CharTy))
9482 Valid = true;
9483 }
9484 }
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009485 } else if (FnDecl->param_size()) {
Sean Hunta6c058d2010-01-13 09:01:02 +00009486 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +00009487 FunctionDecl::param_iterator Param = FnDecl->param_begin();
9488
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009489 QualType T = (*Param)->getType().getUnqualifiedType();
Sean Hunta6c058d2010-01-13 09:01:02 +00009490
Sean Hunt30019c02010-04-07 22:57:35 +00009491 // unsigned long long int, long double, and any character type are allowed
9492 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +00009493 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
9494 Context.hasSameType(T, Context.LongDoubleTy) ||
9495 Context.hasSameType(T, Context.CharTy) ||
9496 Context.hasSameType(T, Context.WCharTy) ||
9497 Context.hasSameType(T, Context.Char16Ty) ||
9498 Context.hasSameType(T, Context.Char32Ty)) {
9499 if (++Param == FnDecl->param_end())
9500 Valid = true;
9501 goto FinishedParams;
9502 }
9503
Sean Hunt30019c02010-04-07 22:57:35 +00009504 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +00009505 const PointerType *PT = T->getAs<PointerType>();
9506 if (!PT)
9507 goto FinishedParams;
9508 T = PT->getPointeeType();
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009509 if (!T.isConstQualified() || T.isVolatileQualified())
Sean Hunta6c058d2010-01-13 09:01:02 +00009510 goto FinishedParams;
9511 T = T.getUnqualifiedType();
9512
9513 // Move on to the second parameter;
9514 ++Param;
9515
9516 // If there is no second parameter, the first must be a const char *
9517 if (Param == FnDecl->param_end()) {
9518 if (Context.hasSameType(T, Context.CharTy))
9519 Valid = true;
9520 goto FinishedParams;
9521 }
9522
9523 // const char *, const wchar_t*, const char16_t*, and const char32_t*
9524 // are allowed as the first parameter to a two-parameter function
9525 if (!(Context.hasSameType(T, Context.CharTy) ||
9526 Context.hasSameType(T, Context.WCharTy) ||
9527 Context.hasSameType(T, Context.Char16Ty) ||
9528 Context.hasSameType(T, Context.Char32Ty)))
9529 goto FinishedParams;
9530
9531 // The second and final parameter must be an std::size_t
9532 T = (*Param)->getType().getUnqualifiedType();
9533 if (Context.hasSameType(T, Context.getSizeType()) &&
9534 ++Param == FnDecl->param_end())
9535 Valid = true;
9536 }
9537
9538 // FIXME: This diagnostic is absolutely terrible.
9539FinishedParams:
9540 if (!Valid) {
9541 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
9542 << FnDecl->getDeclName();
9543 return true;
9544 }
9545
Richard Smitha9e88b22012-03-09 08:16:22 +00009546 // A parameter-declaration-clause containing a default argument is not
9547 // equivalent to any of the permitted forms.
9548 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
9549 ParamEnd = FnDecl->param_end();
9550 Param != ParamEnd; ++Param) {
9551 if ((*Param)->hasDefaultArg()) {
9552 Diag((*Param)->getDefaultArgRange().getBegin(),
9553 diag::err_literal_operator_default_argument)
9554 << (*Param)->getDefaultArgRange();
9555 break;
9556 }
9557 }
9558
Richard Smith2fb4ae32012-03-08 02:39:21 +00009559 StringRef LiteralName
Douglas Gregor1155c422011-08-30 22:40:35 +00009560 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
9561 if (LiteralName[0] != '_') {
Richard Smith2fb4ae32012-03-08 02:39:21 +00009562 // C++11 [usrlit.suffix]p1:
9563 // Literal suffix identifiers that do not start with an underscore
9564 // are reserved for future standardization.
9565 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
Douglas Gregor1155c422011-08-30 22:40:35 +00009566 }
Richard Smith2fb4ae32012-03-08 02:39:21 +00009567
Sean Hunta6c058d2010-01-13 09:01:02 +00009568 return false;
9569}
9570
Douglas Gregor074149e2009-01-05 19:45:36 +00009571/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
9572/// linkage specification, including the language and (if present)
9573/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
9574/// the location of the language string literal, which is provided
9575/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
9576/// the '{' brace. Otherwise, this linkage specification does not
9577/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +00009578Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
9579 SourceLocation LangLoc,
Chris Lattner5f9e2722011-07-23 10:55:15 +00009580 StringRef Lang,
Chris Lattner7d642712010-11-09 20:15:55 +00009581 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00009582 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +00009583 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00009584 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +00009585 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00009586 Language = LinkageSpecDecl::lang_cxx;
9587 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00009588 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +00009589 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +00009590 }
Mike Stump1eb44332009-09-09 15:08:12 +00009591
Chris Lattnercc98eac2008-12-17 07:13:27 +00009592 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +00009593
Douglas Gregor074149e2009-01-05 19:45:36 +00009594 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009595 ExternLoc, LangLoc, Language);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009596 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00009597 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +00009598 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +00009599}
9600
Abramo Bagnara35f9a192010-07-30 16:47:02 +00009601/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +00009602/// the C++ linkage specification LinkageSpec. If RBraceLoc is
9603/// valid, it's the position of the closing '}' brace in a linkage
9604/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +00009605Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +00009606 Decl *LinkageSpec,
9607 SourceLocation RBraceLoc) {
9608 if (LinkageSpec) {
9609 if (RBraceLoc.isValid()) {
9610 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
9611 LSDecl->setRBraceLoc(RBraceLoc);
9612 }
Douglas Gregor074149e2009-01-05 19:45:36 +00009613 PopDeclContext();
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +00009614 }
Douglas Gregor074149e2009-01-05 19:45:36 +00009615 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00009616}
9617
Douglas Gregord308e622009-05-18 20:51:54 +00009618/// \brief Perform semantic analysis for the variable declaration that
9619/// occurs within a C++ catch clause, returning the newly-created
9620/// variable.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009621VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +00009622 TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009623 SourceLocation StartLoc,
9624 SourceLocation Loc,
9625 IdentifierInfo *Name) {
Douglas Gregord308e622009-05-18 20:51:54 +00009626 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +00009627 QualType ExDeclType = TInfo->getType();
9628
Sebastian Redl4b07b292008-12-22 19:15:10 +00009629 // Arrays and functions decay.
9630 if (ExDeclType->isArrayType())
9631 ExDeclType = Context.getArrayDecayedType(ExDeclType);
9632 else if (ExDeclType->isFunctionType())
9633 ExDeclType = Context.getPointerType(ExDeclType);
9634
9635 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
9636 // The exception-declaration shall not denote a pointer or reference to an
9637 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009638 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +00009639 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +00009640 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009641 Invalid = true;
9642 }
Douglas Gregord308e622009-05-18 20:51:54 +00009643
Sebastian Redl4b07b292008-12-22 19:15:10 +00009644 QualType BaseType = ExDeclType;
9645 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00009646 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +00009647 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009648 BaseType = Ptr->getPointeeType();
9649 Mode = 1;
Douglas Gregorecd7b042012-01-24 19:01:26 +00009650 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +00009651 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009652 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00009653 BaseType = Ref->getPointeeType();
9654 Mode = 2;
Douglas Gregorecd7b042012-01-24 19:01:26 +00009655 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009656 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009657 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregorecd7b042012-01-24 19:01:26 +00009658 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +00009659 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009660
Mike Stump1eb44332009-09-09 15:08:12 +00009661 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +00009662 RequireNonAbstractType(Loc, ExDeclType,
9663 diag::err_abstract_type_in_decl,
9664 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00009665 Invalid = true;
9666
John McCall5a180392010-07-24 00:37:23 +00009667 // Only the non-fragile NeXT runtime currently supports C++ catches
9668 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikie4e4d0842012-03-11 07:00:24 +00009669 if (!Invalid && getLangOpts().ObjC1) {
John McCall5a180392010-07-24 00:37:23 +00009670 QualType T = ExDeclType;
9671 if (const ReferenceType *RT = T->getAs<ReferenceType>())
9672 T = RT->getPointeeType();
9673
9674 if (T->isObjCObjectType()) {
9675 Diag(Loc, diag::err_objc_object_catch);
9676 Invalid = true;
9677 } else if (T->isObjCObjectPointerType()) {
John McCall260611a2012-06-20 06:18:46 +00009678 // FIXME: should this be a test for macosx-fragile specifically?
9679 if (getLangOpts().ObjCRuntime.isFragile())
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +00009680 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall5a180392010-07-24 00:37:23 +00009681 }
9682 }
9683
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009684 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
9685 ExDeclType, TInfo, SC_None, SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +00009686 ExDecl->setExceptionVariable(true);
9687
Douglas Gregor9aab9c42011-12-10 01:22:52 +00009688 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +00009689 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor9aab9c42011-12-10 01:22:52 +00009690 Invalid = true;
9691
Douglas Gregorc41b8782011-07-06 18:14:43 +00009692 if (!Invalid && !ExDeclType->isDependentType()) {
John McCalle996ffd2011-02-16 08:02:54 +00009693 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
Douglas Gregor6d182892010-03-05 23:38:39 +00009694 // C++ [except.handle]p16:
9695 // The object declared in an exception-declaration or, if the
9696 // exception-declaration does not specify a name, a temporary (12.2) is
9697 // copy-initialized (8.5) from the exception object. [...]
9698 // The object is destroyed when the handler exits, after the destruction
9699 // of any automatic objects initialized within the handler.
9700 //
9701 // We just pretend to initialize the object with itself, then make sure
9702 // it can be destroyed later.
John McCalle996ffd2011-02-16 08:02:54 +00009703 QualType initType = ExDeclType;
9704
9705 InitializedEntity entity =
9706 InitializedEntity::InitializeVariable(ExDecl);
9707 InitializationKind initKind =
9708 InitializationKind::CreateCopy(Loc, SourceLocation());
9709
9710 Expr *opaqueValue =
9711 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
9712 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
9713 ExprResult result = sequence.Perform(*this, entity, initKind,
9714 MultiExprArg(&opaqueValue, 1));
9715 if (result.isInvalid())
Douglas Gregor6d182892010-03-05 23:38:39 +00009716 Invalid = true;
John McCalle996ffd2011-02-16 08:02:54 +00009717 else {
9718 // If the constructor used was non-trivial, set this as the
9719 // "initializer".
9720 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
9721 if (!construct->getConstructor()->isTrivial()) {
9722 Expr *init = MaybeCreateExprWithCleanups(construct);
9723 ExDecl->setInit(init);
9724 }
9725
9726 // And make sure it's destructable.
9727 FinalizeVarWithDestructor(ExDecl, recordType);
9728 }
Douglas Gregor6d182892010-03-05 23:38:39 +00009729 }
9730 }
9731
Douglas Gregord308e622009-05-18 20:51:54 +00009732 if (Invalid)
9733 ExDecl->setInvalidDecl();
9734
9735 return ExDecl;
9736}
9737
9738/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
9739/// handler.
John McCalld226f652010-08-21 09:40:31 +00009740Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +00009741 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +00009742 bool Invalid = D.isInvalidType();
9743
9744 // Check for unexpanded parameter packs.
9745 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
9746 UPPC_ExceptionType)) {
9747 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
9748 D.getIdentifierLoc());
9749 Invalid = true;
9750 }
9751
Sebastian Redl4b07b292008-12-22 19:15:10 +00009752 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +00009753 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +00009754 LookupOrdinaryName,
9755 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009756 // The scope should be freshly made just for us. There is just no way
9757 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +00009758 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +00009759 if (PrevDecl->isTemplateParameter()) {
9760 // Maybe we will complain about the shadowed template parameter.
9761 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregorcb8f9512011-10-20 17:58:49 +00009762 PrevDecl = 0;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009763 }
9764 }
9765
Chris Lattnereaaebc72009-04-25 08:06:05 +00009766 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009767 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
9768 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00009769 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009770 }
9771
Douglas Gregor83cb9422010-09-09 17:09:21 +00009772 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar96a00142012-03-09 18:35:03 +00009773 D.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009774 D.getIdentifierLoc(),
9775 D.getIdentifier());
Chris Lattnereaaebc72009-04-25 08:06:05 +00009776 if (Invalid)
9777 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00009778
Sebastian Redl4b07b292008-12-22 19:15:10 +00009779 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00009780 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00009781 PushOnScopeChains(ExDecl, S);
9782 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009783 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00009784
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00009785 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +00009786 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009787}
Anders Carlssonfb311762009-03-14 00:25:26 +00009788
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009789Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +00009790 Expr *AssertExpr,
Richard Smithe3f470a2012-07-11 22:37:56 +00009791 Expr *AssertMessageExpr,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009792 SourceLocation RParenLoc) {
Richard Smithe3f470a2012-07-11 22:37:56 +00009793 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr);
Anders Carlssonfb311762009-03-14 00:25:26 +00009794
Richard Smithe3f470a2012-07-11 22:37:56 +00009795 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
9796 return 0;
9797
9798 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
9799 AssertMessage, RParenLoc, false);
9800}
9801
9802Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
9803 Expr *AssertExpr,
9804 StringLiteral *AssertMessage,
9805 SourceLocation RParenLoc,
9806 bool Failed) {
9807 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
9808 !Failed) {
Richard Smith282e7e62012-02-04 09:53:13 +00009809 // In a static_assert-declaration, the constant-expression shall be a
9810 // constant expression that can be contextually converted to bool.
9811 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
9812 if (Converted.isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +00009813 Failed = true;
Richard Smith282e7e62012-02-04 09:53:13 +00009814
Richard Smithdaaefc52011-12-14 23:32:26 +00009815 llvm::APSInt Cond;
Richard Smithe3f470a2012-07-11 22:37:56 +00009816 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregorab41fe92012-05-04 22:38:52 +00009817 diag::err_static_assert_expression_is_not_constant,
Richard Smith282e7e62012-02-04 09:53:13 +00009818 /*AllowFold=*/false).isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +00009819 Failed = true;
Anders Carlssonfb311762009-03-14 00:25:26 +00009820
Richard Smithe3f470a2012-07-11 22:37:56 +00009821 if (!Failed && !Cond) {
Richard Smith0cc323c2012-03-05 23:20:05 +00009822 llvm::SmallString<256> MsgBuffer;
9823 llvm::raw_svector_ostream Msg(MsgBuffer);
Richard Smithd1420c62012-08-16 03:56:14 +00009824 AssertMessage->printPretty(Msg, 0, getPrintingPolicy());
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009825 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smith0cc323c2012-03-05 23:20:05 +00009826 << Msg.str() << AssertExpr->getSourceRange();
Richard Smithe3f470a2012-07-11 22:37:56 +00009827 Failed = true;
Richard Smith0cc323c2012-03-05 23:20:05 +00009828 }
Anders Carlssonc3082412009-03-14 00:33:21 +00009829 }
Mike Stump1eb44332009-09-09 15:08:12 +00009830
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009831 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
Richard Smithe3f470a2012-07-11 22:37:56 +00009832 AssertExpr, AssertMessage, RParenLoc,
9833 Failed);
Mike Stump1eb44332009-09-09 15:08:12 +00009834
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009835 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +00009836 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +00009837}
Sebastian Redl50de12f2009-03-24 22:27:57 +00009838
Douglas Gregor1d869352010-04-07 16:53:43 +00009839/// \brief Perform semantic analysis of the given friend type declaration.
9840///
9841/// \returns A friend declaration that.
Abramo Bagnara0216df82011-10-29 20:52:52 +00009842FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation Loc,
9843 SourceLocation FriendLoc,
Douglas Gregor1d869352010-04-07 16:53:43 +00009844 TypeSourceInfo *TSInfo) {
9845 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
9846
9847 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00009848 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +00009849
Richard Smith6b130222011-10-18 21:39:00 +00009850 // C++03 [class.friend]p2:
9851 // An elaborated-type-specifier shall be used in a friend declaration
9852 // for a class.*
9853 //
9854 // * The class-key of the elaborated-type-specifier is required.
9855 if (!ActiveTemplateInstantiations.empty()) {
9856 // Do not complain about the form of friend template types during
9857 // template instantiation; we will already have complained when the
9858 // template was declared.
9859 } else if (!T->isElaboratedTypeSpecifier()) {
9860 // If we evaluated the type to a record type, suggest putting
9861 // a tag in front.
9862 if (const RecordType *RT = T->getAs<RecordType>()) {
9863 RecordDecl *RD = RT->getDecl();
9864
9865 std::string InsertionText = std::string(" ") + RD->getKindName();
9866
9867 Diag(TypeRange.getBegin(),
David Blaikie4e4d0842012-03-11 07:00:24 +00009868 getLangOpts().CPlusPlus0x ?
Richard Smith6b130222011-10-18 21:39:00 +00009869 diag::warn_cxx98_compat_unelaborated_friend_type :
9870 diag::ext_unelaborated_friend_type)
9871 << (unsigned) RD->getTagKind()
9872 << T
9873 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
9874 InsertionText);
9875 } else {
9876 Diag(FriendLoc,
David Blaikie4e4d0842012-03-11 07:00:24 +00009877 getLangOpts().CPlusPlus0x ?
Richard Smith6b130222011-10-18 21:39:00 +00009878 diag::warn_cxx98_compat_nonclass_type_friend :
9879 diag::ext_nonclass_type_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +00009880 << T
Douglas Gregor1d869352010-04-07 16:53:43 +00009881 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregor1d869352010-04-07 16:53:43 +00009882 }
Richard Smith6b130222011-10-18 21:39:00 +00009883 } else if (T->getAs<EnumType>()) {
9884 Diag(FriendLoc,
David Blaikie4e4d0842012-03-11 07:00:24 +00009885 getLangOpts().CPlusPlus0x ?
Richard Smith6b130222011-10-18 21:39:00 +00009886 diag::warn_cxx98_compat_enum_friend :
9887 diag::ext_enum_friend)
9888 << T
9889 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregor1d869352010-04-07 16:53:43 +00009890 }
9891
Douglas Gregor06245bf2010-04-07 17:57:12 +00009892 // C++0x [class.friend]p3:
9893 // If the type specifier in a friend declaration designates a (possibly
9894 // cv-qualified) class type, that class is declared as a friend; otherwise,
9895 // the friend declaration is ignored.
9896
9897 // FIXME: C++0x has some syntactic restrictions on friend type declarations
9898 // in [class.friend]p3 that we do not implement.
Douglas Gregor1d869352010-04-07 16:53:43 +00009899
Abramo Bagnara0216df82011-10-29 20:52:52 +00009900 return FriendDecl::Create(Context, CurContext, Loc, TSInfo, FriendLoc);
Douglas Gregor1d869352010-04-07 16:53:43 +00009901}
9902
John McCall9a34edb2010-10-19 01:40:49 +00009903/// Handle a friend tag declaration where the scope specifier was
9904/// templated.
9905Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
9906 unsigned TagSpec, SourceLocation TagLoc,
9907 CXXScopeSpec &SS,
9908 IdentifierInfo *Name, SourceLocation NameLoc,
9909 AttributeList *Attr,
9910 MultiTemplateParamsArg TempParamLists) {
9911 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
9912
9913 bool isExplicitSpecialization = false;
John McCall9a34edb2010-10-19 01:40:49 +00009914 bool Invalid = false;
9915
9916 if (TemplateParameterList *TemplateParams
Douglas Gregorc8406492011-05-10 18:27:06 +00009917 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
Benjamin Kramer5354e772012-08-23 23:38:35 +00009918 TempParamLists.data(),
John McCall9a34edb2010-10-19 01:40:49 +00009919 TempParamLists.size(),
9920 /*friend*/ true,
9921 isExplicitSpecialization,
9922 Invalid)) {
John McCall9a34edb2010-10-19 01:40:49 +00009923 if (TemplateParams->size() > 0) {
9924 // This is a declaration of a class template.
9925 if (Invalid)
9926 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +00009927
Eric Christopher4110e132011-07-21 05:34:24 +00009928 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
9929 SS, Name, NameLoc, Attr,
9930 TemplateParams, AS_public,
Douglas Gregore7612302011-09-09 19:05:14 +00009931 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher4110e132011-07-21 05:34:24 +00009932 TempParamLists.size() - 1,
Benjamin Kramer5354e772012-08-23 23:38:35 +00009933 TempParamLists.data()).take();
John McCall9a34edb2010-10-19 01:40:49 +00009934 } else {
9935 // The "template<>" header is extraneous.
9936 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
9937 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
9938 isExplicitSpecialization = true;
9939 }
9940 }
9941
9942 if (Invalid) return 0;
9943
John McCall9a34edb2010-10-19 01:40:49 +00009944 bool isAllExplicitSpecializations = true;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00009945 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009946 if (TempParamLists[I]->size()) {
John McCall9a34edb2010-10-19 01:40:49 +00009947 isAllExplicitSpecializations = false;
9948 break;
9949 }
9950 }
9951
9952 // FIXME: don't ignore attributes.
9953
9954 // If it's explicit specializations all the way down, just forget
9955 // about the template header and build an appropriate non-templated
9956 // friend. TODO: for source fidelity, remember the headers.
9957 if (isAllExplicitSpecializations) {
Douglas Gregorba4ee9a2011-10-20 15:58:54 +00009958 if (SS.isEmpty()) {
9959 bool Owned = false;
9960 bool IsDependent = false;
9961 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
9962 Attr, AS_public,
9963 /*ModulePrivateLoc=*/SourceLocation(),
9964 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smithbdad7a22012-01-10 01:33:14 +00009965 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorba4ee9a2011-10-20 15:58:54 +00009966 /*ScopedEnumUsesClassTag=*/false,
9967 /*UnderlyingType=*/TypeResult());
9968 }
9969
Douglas Gregor2494dd02011-03-01 01:34:45 +00009970 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall9a34edb2010-10-19 01:40:49 +00009971 ElaboratedTypeKeyword Keyword
9972 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor2494dd02011-03-01 01:34:45 +00009973 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +00009974 *Name, NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +00009975 if (T.isNull())
9976 return 0;
9977
9978 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9979 if (isa<DependentNameType>(T)) {
9980 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara38a42912012-02-06 19:09:27 +00009981 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +00009982 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +00009983 TL.setNameLoc(NameLoc);
9984 } else {
9985 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara38a42912012-02-06 19:09:27 +00009986 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +00009987 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +00009988 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
9989 }
9990
9991 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
9992 TSI, FriendLoc);
9993 Friend->setAccess(AS_public);
9994 CurContext->addDecl(Friend);
9995 return Friend;
9996 }
Douglas Gregorba4ee9a2011-10-20 15:58:54 +00009997
9998 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
9999
10000
John McCall9a34edb2010-10-19 01:40:49 +000010001
10002 // Handle the case of a templated-scope friend class. e.g.
10003 // template <class T> class A<T>::B;
10004 // FIXME: we don't support these right now.
10005 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
10006 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
10007 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10008 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara38a42912012-02-06 19:09:27 +000010009 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010010 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCall9a34edb2010-10-19 01:40:49 +000010011 TL.setNameLoc(NameLoc);
10012
10013 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
10014 TSI, FriendLoc);
10015 Friend->setAccess(AS_public);
10016 Friend->setUnsupportedFriend(true);
10017 CurContext->addDecl(Friend);
10018 return Friend;
10019}
10020
10021
John McCalldd4a3b02009-09-16 22:47:08 +000010022/// Handle a friend type declaration. This works in tandem with
10023/// ActOnTag.
10024///
10025/// Notes on friend class templates:
10026///
10027/// We generally treat friend class declarations as if they were
10028/// declaring a class. So, for example, the elaborated type specifier
10029/// in a friend declaration is required to obey the restrictions of a
10030/// class-head (i.e. no typedefs in the scope chain), template
10031/// parameters are required to match up with simple template-ids, &c.
10032/// However, unlike when declaring a template specialization, it's
10033/// okay to refer to a template specialization without an empty
10034/// template parameter declaration, e.g.
10035/// friend class A<T>::B<unsigned>;
10036/// We permit this as a special case; if there are any template
10037/// parameters present at all, require proper matching, i.e.
James Dennettef2b5b32012-06-15 22:23:43 +000010038/// template <> template \<class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +000010039Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +000010040 MultiTemplateParamsArg TempParams) {
Daniel Dunbar96a00142012-03-09 18:35:03 +000010041 SourceLocation Loc = DS.getLocStart();
John McCall67d1a672009-08-06 02:15:43 +000010042
10043 assert(DS.isFriendSpecified());
10044 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10045
John McCalldd4a3b02009-09-16 22:47:08 +000010046 // Try to convert the decl specifier to a type. This works for
10047 // friend templates because ActOnTag never produces a ClassTemplateDecl
10048 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +000010049 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +000010050 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
10051 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +000010052 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +000010053 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010054
Douglas Gregor6ccab972010-12-16 01:14:37 +000010055 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
10056 return 0;
10057
John McCalldd4a3b02009-09-16 22:47:08 +000010058 // This is definitely an error in C++98. It's probably meant to
10059 // be forbidden in C++0x, too, but the specification is just
10060 // poorly written.
10061 //
10062 // The problem is with declarations like the following:
10063 // template <T> friend A<T>::foo;
10064 // where deciding whether a class C is a friend or not now hinges
10065 // on whether there exists an instantiation of A that causes
10066 // 'foo' to equal C. There are restrictions on class-heads
10067 // (which we declare (by fiat) elaborated friend declarations to
10068 // be) that makes this tractable.
10069 //
10070 // FIXME: handle "template <> friend class A<T>;", which
10071 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +000010072 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +000010073 Diag(Loc, diag::err_tagless_friend_type_template)
10074 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +000010075 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +000010076 }
Douglas Gregor1d869352010-04-07 16:53:43 +000010077
John McCall02cace72009-08-28 07:59:38 +000010078 // C++98 [class.friend]p1: A friend of a class is a function
10079 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +000010080 // This is fixed in DR77, which just barely didn't make the C++03
10081 // deadline. It's also a very silly restriction that seriously
10082 // affects inner classes and which nobody else seems to implement;
10083 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +000010084 //
10085 // But note that we could warn about it: it's always useless to
10086 // friend one of your own members (it's not, however, worthless to
10087 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +000010088
John McCalldd4a3b02009-09-16 22:47:08 +000010089 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +000010090 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +000010091 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +000010092 NumTempParamLists,
Benjamin Kramer5354e772012-08-23 23:38:35 +000010093 TempParams.data(),
John McCall32f2fb52010-03-25 18:04:51 +000010094 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +000010095 DS.getFriendSpecLoc());
10096 else
Abramo Bagnara0216df82011-10-29 20:52:52 +000010097 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregor1d869352010-04-07 16:53:43 +000010098
10099 if (!D)
John McCalld226f652010-08-21 09:40:31 +000010100 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +000010101
John McCalldd4a3b02009-09-16 22:47:08 +000010102 D->setAccess(AS_public);
10103 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +000010104
John McCalld226f652010-08-21 09:40:31 +000010105 return D;
John McCall02cace72009-08-28 07:59:38 +000010106}
10107
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010108Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
John McCall337ec3d2010-10-12 23:13:28 +000010109 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +000010110 const DeclSpec &DS = D.getDeclSpec();
10111
10112 assert(DS.isFriendSpecified());
10113 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10114
10115 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +000010116 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall67d1a672009-08-06 02:15:43 +000010117
10118 // C++ [class.friend]p1
10119 // A friend of a class is a function or class....
10120 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +000010121 // It *doesn't* see through dependent types, which is correct
10122 // according to [temp.arg.type]p3:
10123 // If a declaration acquires a function type through a
10124 // type dependent on a template-parameter and this causes
10125 // a declaration that does not use the syntactic form of a
10126 // function declarator to have a function type, the program
10127 // is ill-formed.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010128 if (!TInfo->getType()->isFunctionType()) {
John McCall67d1a672009-08-06 02:15:43 +000010129 Diag(Loc, diag::err_unexpected_friend);
10130
10131 // It might be worthwhile to try to recover by creating an
10132 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +000010133 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010134 }
10135
10136 // C++ [namespace.memdef]p3
10137 // - If a friend declaration in a non-local class first declares a
10138 // class or function, the friend class or function is a member
10139 // of the innermost enclosing namespace.
10140 // - The name of the friend is not found by simple name lookup
10141 // until a matching declaration is provided in that namespace
10142 // scope (either before or after the class declaration granting
10143 // friendship).
10144 // - If a friend function is called, its name may be found by the
10145 // name lookup that considers functions from namespaces and
10146 // classes associated with the types of the function arguments.
10147 // - When looking for a prior declaration of a class or a function
10148 // declared as a friend, scopes outside the innermost enclosing
10149 // namespace scope are not considered.
10150
John McCall337ec3d2010-10-12 23:13:28 +000010151 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +000010152 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
10153 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +000010154 assert(Name);
10155
Douglas Gregor6ccab972010-12-16 01:14:37 +000010156 // Check for unexpanded parameter packs.
10157 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
10158 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
10159 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
10160 return 0;
10161
John McCall67d1a672009-08-06 02:15:43 +000010162 // The context we found the declaration in, or in which we should
10163 // create the declaration.
10164 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +000010165 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +000010166 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +000010167 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +000010168
John McCall337ec3d2010-10-12 23:13:28 +000010169 // FIXME: there are different rules in local classes
John McCall67d1a672009-08-06 02:15:43 +000010170
John McCall337ec3d2010-10-12 23:13:28 +000010171 // There are four cases here.
10172 // - There's no scope specifier, in which case we just go to the
John McCall29ae6e52010-10-13 05:45:15 +000010173 // appropriate scope and look for a function or function template
John McCall337ec3d2010-10-12 23:13:28 +000010174 // there as appropriate.
10175 // Recover from invalid scope qualifiers as if they just weren't there.
10176 if (SS.isInvalid() || !SS.isSet()) {
John McCall29ae6e52010-10-13 05:45:15 +000010177 // C++0x [namespace.memdef]p3:
10178 // If the name in a friend declaration is neither qualified nor
10179 // a template-id and the declaration is a function or an
10180 // elaborated-type-specifier, the lookup to determine whether
10181 // the entity has been previously declared shall not consider
10182 // any scopes outside the innermost enclosing namespace.
10183 // C++0x [class.friend]p11:
10184 // If a friend declaration appears in a local class and the name
10185 // specified is an unqualified name, a prior declaration is
10186 // looked up without considering scopes that are outside the
10187 // innermost enclosing non-class scope. For a friend function
10188 // declaration, if there is no prior declaration, the program is
10189 // ill-formed.
10190 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCall8a407372010-10-14 22:22:28 +000010191 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +000010192
John McCall29ae6e52010-10-13 05:45:15 +000010193 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +000010194 DC = CurContext;
10195 while (true) {
10196 // Skip class contexts. If someone can cite chapter and verse
10197 // for this behavior, that would be nice --- it's what GCC and
10198 // EDG do, and it seems like a reasonable intent, but the spec
10199 // really only says that checks for unqualified existing
10200 // declarations should stop at the nearest enclosing namespace,
10201 // not that they should only consider the nearest enclosing
10202 // namespace.
Nick Lewycky9c6fde52012-03-16 19:51:19 +000010203 while (DC->isRecord() || DC->isTransparentContext())
Douglas Gregor182ddf02009-09-28 00:08:27 +000010204 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +000010205
John McCall68263142009-11-18 22:49:29 +000010206 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +000010207
10208 // TODO: decide what we think about using declarations.
John McCall29ae6e52010-10-13 05:45:15 +000010209 if (isLocal || !Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +000010210 break;
John McCall29ae6e52010-10-13 05:45:15 +000010211
John McCall8a407372010-10-14 22:22:28 +000010212 if (isTemplateId) {
10213 if (isa<TranslationUnitDecl>(DC)) break;
10214 } else {
10215 if (DC->isFileContext()) break;
10216 }
John McCall67d1a672009-08-06 02:15:43 +000010217 DC = DC->getParent();
10218 }
10219
10220 // C++ [class.friend]p1: A friend of a class is a function or
10221 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000010222 // C++11 changes this for both friend types and functions.
John McCall7f27d922009-08-06 20:49:32 +000010223 // Most C++ 98 compilers do seem to give an error here, so
10224 // we do, too.
Richard Smithebaf0e62011-10-18 20:49:44 +000010225 if (!Previous.empty() && DC->Equals(CurContext))
10226 Diag(DS.getFriendSpecLoc(),
David Blaikie4e4d0842012-03-11 07:00:24 +000010227 getLangOpts().CPlusPlus0x ?
Richard Smithebaf0e62011-10-18 20:49:44 +000010228 diag::warn_cxx98_compat_friend_is_member :
10229 diag::err_friend_is_member);
John McCall337ec3d2010-10-12 23:13:28 +000010230
John McCall380aaa42010-10-13 06:22:15 +000010231 DCScope = getScopeForDeclContext(S, DC);
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000010232
Douglas Gregor883af832011-10-10 01:11:59 +000010233 // C++ [class.friend]p6:
10234 // A function can be defined in a friend declaration of a class if and
10235 // only if the class is a non-local class (9.8), the function name is
10236 // unqualified, and the function has namespace scope.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010237 if (isLocal && D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010238 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
10239 }
10240
John McCall337ec3d2010-10-12 23:13:28 +000010241 // - There's a non-dependent scope specifier, in which case we
10242 // compute it and do a previous lookup there for a function
10243 // or function template.
10244 } else if (!SS.getScopeRep()->isDependent()) {
10245 DC = computeDeclContext(SS);
10246 if (!DC) return 0;
10247
10248 if (RequireCompleteDeclContext(SS, DC)) return 0;
10249
10250 LookupQualifiedName(Previous, DC);
10251
10252 // Ignore things found implicitly in the wrong scope.
10253 // TODO: better diagnostics for this case. Suggesting the right
10254 // qualified scope would be nice...
10255 LookupResult::Filter F = Previous.makeFilter();
10256 while (F.hasNext()) {
10257 NamedDecl *D = F.next();
10258 if (!DC->InEnclosingNamespaceSetOf(
10259 D->getDeclContext()->getRedeclContext()))
10260 F.erase();
10261 }
10262 F.done();
10263
10264 if (Previous.empty()) {
10265 D.setInvalidType();
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010266 Diag(Loc, diag::err_qualified_friend_not_found)
10267 << Name << TInfo->getType();
John McCall337ec3d2010-10-12 23:13:28 +000010268 return 0;
10269 }
10270
10271 // C++ [class.friend]p1: A friend of a class is a function or
10272 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000010273 if (DC->Equals(CurContext))
10274 Diag(DS.getFriendSpecLoc(),
David Blaikie4e4d0842012-03-11 07:00:24 +000010275 getLangOpts().CPlusPlus0x ?
Richard Smithebaf0e62011-10-18 20:49:44 +000010276 diag::warn_cxx98_compat_friend_is_member :
10277 diag::err_friend_is_member);
Douglas Gregor883af832011-10-10 01:11:59 +000010278
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010279 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010280 // C++ [class.friend]p6:
10281 // A function can be defined in a friend declaration of a class if and
10282 // only if the class is a non-local class (9.8), the function name is
10283 // unqualified, and the function has namespace scope.
10284 SemaDiagnosticBuilder DB
10285 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
10286
10287 DB << SS.getScopeRep();
10288 if (DC->isFileContext())
10289 DB << FixItHint::CreateRemoval(SS.getRange());
10290 SS.clear();
10291 }
John McCall337ec3d2010-10-12 23:13:28 +000010292
10293 // - There's a scope specifier that does not match any template
10294 // parameter lists, in which case we use some arbitrary context,
10295 // create a method or method template, and wait for instantiation.
10296 // - There's a scope specifier that does match some template
10297 // parameter lists, which we don't handle right now.
10298 } else {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010299 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010300 // C++ [class.friend]p6:
10301 // A function can be defined in a friend declaration of a class if and
10302 // only if the class is a non-local class (9.8), the function name is
10303 // unqualified, and the function has namespace scope.
10304 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
10305 << SS.getScopeRep();
10306 }
10307
John McCall337ec3d2010-10-12 23:13:28 +000010308 DC = CurContext;
10309 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +000010310 }
Douglas Gregor883af832011-10-10 01:11:59 +000010311
John McCall29ae6e52010-10-13 05:45:15 +000010312 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +000010313 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +000010314 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
10315 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
10316 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +000010317 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +000010318 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
10319 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +000010320 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010321 }
John McCall67d1a672009-08-06 02:15:43 +000010322 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010323
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000010324 // FIXME: This is an egregious hack to cope with cases where the scope stack
10325 // does not contain the declaration context, i.e., in an out-of-line
10326 // definition of a class.
10327 Scope FakeDCScope(S, Scope::DeclScope, Diags);
10328 if (!DCScope) {
10329 FakeDCScope.setEntity(DC);
10330 DCScope = &FakeDCScope;
10331 }
10332
Francois Pichetaf0f4d02011-08-14 03:52:19 +000010333 bool AddToScope = true;
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010334 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010335 TemplateParams, AddToScope);
John McCalld226f652010-08-21 09:40:31 +000010336 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +000010337
Douglas Gregor182ddf02009-09-28 00:08:27 +000010338 assert(ND->getDeclContext() == DC);
10339 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +000010340
John McCallab88d972009-08-31 22:39:49 +000010341 // Add the function declaration to the appropriate lookup tables,
10342 // adjusting the redeclarations list as necessary. We don't
10343 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +000010344 //
John McCallab88d972009-08-31 22:39:49 +000010345 // Also update the scope-based lookup if the target context's
10346 // lookup context is in lexical scope.
10347 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000010348 DC = DC->getRedeclContext();
Richard Smith1b7f9cb2012-03-13 03:12:56 +000010349 DC->makeDeclVisibleInContext(ND);
John McCallab88d972009-08-31 22:39:49 +000010350 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +000010351 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +000010352 }
John McCall02cace72009-08-28 07:59:38 +000010353
10354 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +000010355 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +000010356 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +000010357 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +000010358 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +000010359
John McCall1f2e1a92012-08-10 03:15:35 +000010360 if (ND->isInvalidDecl()) {
John McCall337ec3d2010-10-12 23:13:28 +000010361 FrD->setInvalidDecl();
John McCall1f2e1a92012-08-10 03:15:35 +000010362 } else {
10363 if (DC->isRecord()) CheckFriendAccess(ND);
10364
John McCall6102ca12010-10-16 06:59:13 +000010365 FunctionDecl *FD;
10366 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
10367 FD = FTD->getTemplatedDecl();
10368 else
10369 FD = cast<FunctionDecl>(ND);
10370
10371 // Mark templated-scope function declarations as unsupported.
10372 if (FD->getNumTemplateParameterLists())
10373 FrD->setUnsupportedFriend(true);
10374 }
John McCall337ec3d2010-10-12 23:13:28 +000010375
John McCalld226f652010-08-21 09:40:31 +000010376 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +000010377}
10378
John McCalld226f652010-08-21 09:40:31 +000010379void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
10380 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +000010381
Sebastian Redl50de12f2009-03-24 22:27:57 +000010382 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
10383 if (!Fn) {
10384 Diag(DelLoc, diag::err_deleted_non_function);
10385 return;
10386 }
Douglas Gregoref96ee02012-01-14 16:38:05 +000010387 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
David Blaikied9cf8262012-06-25 21:55:30 +000010388 // Don't consider the implicit declaration we generate for explicit
10389 // specializations. FIXME: Do not generate these implicit declarations.
David Blaikie619ee6a2012-06-29 18:00:25 +000010390 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization
10391 || Prev->getPreviousDecl()) && !Prev->isDefined()) {
David Blaikied9cf8262012-06-25 21:55:30 +000010392 Diag(DelLoc, diag::err_deleted_decl_not_first);
10393 Diag(Prev->getLocation(), diag::note_previous_declaration);
10394 }
Sebastian Redl50de12f2009-03-24 22:27:57 +000010395 // If the declaration wasn't the first, we delete the function anyway for
10396 // recovery.
10397 }
Sean Hunt10620eb2011-05-06 20:44:56 +000010398 Fn->setDeletedAsWritten();
Richard Smithe653ba22012-02-26 00:31:33 +000010399
10400 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
10401 if (!MD)
10402 return;
10403
10404 // A deleted special member function is trivial if the corresponding
10405 // implicitly-declared function would have been.
10406 switch (getSpecialMember(MD)) {
10407 case CXXInvalid:
10408 break;
10409 case CXXDefaultConstructor:
10410 MD->setTrivial(MD->getParent()->hasTrivialDefaultConstructor());
10411 break;
10412 case CXXCopyConstructor:
10413 MD->setTrivial(MD->getParent()->hasTrivialCopyConstructor());
10414 break;
10415 case CXXMoveConstructor:
10416 MD->setTrivial(MD->getParent()->hasTrivialMoveConstructor());
10417 break;
10418 case CXXCopyAssignment:
10419 MD->setTrivial(MD->getParent()->hasTrivialCopyAssignment());
10420 break;
10421 case CXXMoveAssignment:
10422 MD->setTrivial(MD->getParent()->hasTrivialMoveAssignment());
10423 break;
10424 case CXXDestructor:
10425 MD->setTrivial(MD->getParent()->hasTrivialDestructor());
10426 break;
10427 }
Sebastian Redl50de12f2009-03-24 22:27:57 +000010428}
Sebastian Redl13e88542009-04-27 21:33:24 +000010429
Sean Hunte4246a62011-05-12 06:15:49 +000010430void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
10431 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
10432
10433 if (MD) {
Sean Hunteb88ae52011-05-23 21:07:59 +000010434 if (MD->getParent()->isDependentType()) {
10435 MD->setDefaulted();
10436 MD->setExplicitlyDefaulted();
10437 return;
10438 }
10439
Sean Hunte4246a62011-05-12 06:15:49 +000010440 CXXSpecialMember Member = getSpecialMember(MD);
10441 if (Member == CXXInvalid) {
10442 Diag(DefaultLoc, diag::err_default_special_members);
10443 return;
10444 }
10445
10446 MD->setDefaulted();
10447 MD->setExplicitlyDefaulted();
10448
Sean Huntcd10dec2011-05-23 23:14:04 +000010449 // If this definition appears within the record, do the checking when
10450 // the record is complete.
10451 const FunctionDecl *Primary = MD;
Richard Smitha8eaf002012-08-23 06:16:52 +000010452 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
Sean Huntcd10dec2011-05-23 23:14:04 +000010453 // Find the uninstantiated declaration that actually had the '= default'
10454 // on it.
Richard Smitha8eaf002012-08-23 06:16:52 +000010455 Pattern->isDefined(Primary);
Sean Huntcd10dec2011-05-23 23:14:04 +000010456
10457 if (Primary == Primary->getCanonicalDecl())
Sean Hunte4246a62011-05-12 06:15:49 +000010458 return;
10459
Richard Smithb9d0b762012-07-27 04:22:15 +000010460 CheckExplicitlyDefaultedSpecialMember(MD);
10461
Sean Hunte4246a62011-05-12 06:15:49 +000010462 switch (Member) {
10463 case CXXDefaultConstructor: {
10464 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010465 if (!CD->isInvalidDecl())
10466 DefineImplicitDefaultConstructor(DefaultLoc, CD);
10467 break;
10468 }
10469
10470 case CXXCopyConstructor: {
10471 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010472 if (!CD->isInvalidDecl())
10473 DefineImplicitCopyConstructor(DefaultLoc, CD);
Sean Hunte4246a62011-05-12 06:15:49 +000010474 break;
10475 }
Sean Huntcb45a0f2011-05-12 22:46:25 +000010476
Sean Hunt2b188082011-05-14 05:23:28 +000010477 case CXXCopyAssignment: {
Sean Hunt2b188082011-05-14 05:23:28 +000010478 if (!MD->isInvalidDecl())
10479 DefineImplicitCopyAssignment(DefaultLoc, MD);
10480 break;
10481 }
10482
Sean Huntcb45a0f2011-05-12 22:46:25 +000010483 case CXXDestructor: {
10484 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010485 if (!DD->isInvalidDecl())
10486 DefineImplicitDestructor(DefaultLoc, DD);
Sean Huntcb45a0f2011-05-12 22:46:25 +000010487 break;
10488 }
10489
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010490 case CXXMoveConstructor: {
10491 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010492 if (!CD->isInvalidDecl())
10493 DefineImplicitMoveConstructor(DefaultLoc, CD);
Sean Hunt82713172011-05-25 23:16:36 +000010494 break;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010495 }
Sean Hunt82713172011-05-25 23:16:36 +000010496
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010497 case CXXMoveAssignment: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010498 if (!MD->isInvalidDecl())
10499 DefineImplicitMoveAssignment(DefaultLoc, MD);
10500 break;
10501 }
10502
10503 case CXXInvalid:
David Blaikieb219cfc2011-09-23 05:06:16 +000010504 llvm_unreachable("Invalid special member.");
Sean Hunte4246a62011-05-12 06:15:49 +000010505 }
10506 } else {
10507 Diag(DefaultLoc, diag::err_default_special_members);
10508 }
10509}
10510
Sebastian Redl13e88542009-04-27 21:33:24 +000010511static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +000010512 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +000010513 Stmt *SubStmt = *CI;
10514 if (!SubStmt)
10515 continue;
10516 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar96a00142012-03-09 18:35:03 +000010517 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl13e88542009-04-27 21:33:24 +000010518 diag::err_return_in_constructor_handler);
10519 if (!isa<Expr>(SubStmt))
10520 SearchForReturnInStmt(Self, SubStmt);
10521 }
10522}
10523
10524void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
10525 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
10526 CXXCatchStmt *Handler = TryBlock->getHandler(I);
10527 SearchForReturnInStmt(*this, Handler);
10528 }
10529}
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010530
Mike Stump1eb44332009-09-09 15:08:12 +000010531bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010532 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +000010533 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
10534 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010535
Chandler Carruth73857792010-02-15 11:53:20 +000010536 if (Context.hasSameType(NewTy, OldTy) ||
10537 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010538 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000010539
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010540 // Check if the return types are covariant
10541 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +000010542
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010543 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010544 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
10545 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010546 NewClassTy = NewPT->getPointeeType();
10547 OldClassTy = OldPT->getPointeeType();
10548 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010549 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
10550 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
10551 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
10552 NewClassTy = NewRT->getPointeeType();
10553 OldClassTy = OldRT->getPointeeType();
10554 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010555 }
10556 }
Mike Stump1eb44332009-09-09 15:08:12 +000010557
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010558 // The return types aren't either both pointers or references to a class type.
10559 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +000010560 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010561 diag::err_different_return_type_for_overriding_virtual_function)
10562 << New->getDeclName() << NewTy << OldTy;
10563 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +000010564
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010565 return true;
10566 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010567
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010568 // C++ [class.virtual]p6:
10569 // If the return type of D::f differs from the return type of B::f, the
10570 // class type in the return type of D::f shall be complete at the point of
10571 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +000010572 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
10573 if (!RT->isBeingDefined() &&
10574 RequireCompleteType(New->getLocation(), NewClassTy,
Douglas Gregord10099e2012-05-04 16:32:21 +000010575 diag::err_covariant_return_incomplete,
10576 New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010577 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +000010578 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010579
Douglas Gregora4923eb2009-11-16 21:35:15 +000010580 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010581 // Check if the new class derives from the old class.
10582 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
10583 Diag(New->getLocation(),
10584 diag::err_covariant_return_not_derived)
10585 << New->getDeclName() << NewTy << OldTy;
10586 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10587 return true;
10588 }
Mike Stump1eb44332009-09-09 15:08:12 +000010589
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010590 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +000010591 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +000010592 diag::err_covariant_return_inaccessible_base,
10593 diag::err_covariant_return_ambiguous_derived_to_base_conv,
10594 // FIXME: Should this point to the return type?
10595 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCalleee1d542011-02-14 07:13:47 +000010596 // FIXME: this note won't trigger for delayed access control
10597 // diagnostics, and it's impossible to get an undelayed error
10598 // here from access control during the original parse because
10599 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010600 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10601 return true;
10602 }
10603 }
Mike Stump1eb44332009-09-09 15:08:12 +000010604
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010605 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010606 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010607 Diag(New->getLocation(),
10608 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010609 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010610 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10611 return true;
10612 };
Mike Stump1eb44332009-09-09 15:08:12 +000010613
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010614
10615 // The new class type must have the same or less qualifiers as the old type.
10616 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
10617 Diag(New->getLocation(),
10618 diag::err_covariant_return_type_class_type_more_qualified)
10619 << New->getDeclName() << NewTy << OldTy;
10620 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10621 return true;
10622 };
Mike Stump1eb44332009-09-09 15:08:12 +000010623
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010624 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010625}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010626
Douglas Gregor4ba31362009-12-01 17:24:26 +000010627/// \brief Mark the given method pure.
10628///
10629/// \param Method the method to be marked pure.
10630///
10631/// \param InitRange the source range that covers the "0" initializer.
10632bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnara796aa442011-03-12 11:17:06 +000010633 SourceLocation EndLoc = InitRange.getEnd();
10634 if (EndLoc.isValid())
10635 Method->setRangeEnd(EndLoc);
10636
Douglas Gregor4ba31362009-12-01 17:24:26 +000010637 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
10638 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +000010639 return false;
Abramo Bagnara796aa442011-03-12 11:17:06 +000010640 }
Douglas Gregor4ba31362009-12-01 17:24:26 +000010641
10642 if (!Method->isInvalidDecl())
10643 Diag(Method->getLocation(), diag::err_non_virtual_pure)
10644 << Method->getDeclName() << InitRange;
10645 return true;
10646}
10647
Douglas Gregor552e2992012-02-21 02:22:07 +000010648/// \brief Determine whether the given declaration is a static data member.
10649static bool isStaticDataMember(Decl *D) {
10650 VarDecl *Var = dyn_cast_or_null<VarDecl>(D);
10651 if (!Var)
10652 return false;
10653
10654 return Var->isStaticDataMember();
10655}
John McCall731ad842009-12-19 09:28:58 +000010656/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
10657/// an initializer for the out-of-line declaration 'Dcl'. The scope
10658/// is a fresh scope pushed for just this purpose.
10659///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010660/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
10661/// static data member of class X, names should be looked up in the scope of
10662/// class X.
John McCalld226f652010-08-21 09:40:31 +000010663void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010664 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000010665 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010666
John McCall731ad842009-12-19 09:28:58 +000010667 // We should only get called for declarations with scope specifiers, like:
10668 // int foo::bar;
10669 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000010670 EnterDeclaratorContext(S, D->getDeclContext());
Douglas Gregor552e2992012-02-21 02:22:07 +000010671
10672 // If we are parsing the initializer for a static data member, push a
10673 // new expression evaluation context that is associated with this static
10674 // data member.
10675 if (isStaticDataMember(D))
10676 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010677}
10678
10679/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +000010680/// initializer for the out-of-line declaration 'D'.
10681void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010682 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000010683 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010684
Douglas Gregor552e2992012-02-21 02:22:07 +000010685 if (isStaticDataMember(D))
10686 PopExpressionEvaluationContext();
10687
John McCall731ad842009-12-19 09:28:58 +000010688 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000010689 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010690}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010691
10692/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
10693/// C++ if/switch/while/for statement.
10694/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +000010695DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010696 // C++ 6.4p2:
10697 // The declarator shall not specify a function or an array.
10698 // The type-specifier-seq shall not contain typedef and shall not declare a
10699 // new class or enumeration.
10700 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
10701 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000010702
10703 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor9a30c992011-07-05 16:13:20 +000010704 if (!Dcl)
10705 return true;
10706
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000010707 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
10708 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010709 << D.getSourceRange();
Douglas Gregor9a30c992011-07-05 16:13:20 +000010710 return true;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010711 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010712
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010713 return Dcl;
10714}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010715
Douglas Gregordfe65432011-07-28 19:11:31 +000010716void Sema::LoadExternalVTableUses() {
10717 if (!ExternalSource)
10718 return;
10719
10720 SmallVector<ExternalVTableUse, 4> VTables;
10721 ExternalSource->ReadUsedVTables(VTables);
10722 SmallVector<VTableUse, 4> NewUses;
10723 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
10724 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
10725 = VTablesUsed.find(VTables[I].Record);
10726 // Even if a definition wasn't required before, it may be required now.
10727 if (Pos != VTablesUsed.end()) {
10728 if (!Pos->second && VTables[I].DefinitionRequired)
10729 Pos->second = true;
10730 continue;
10731 }
10732
10733 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
10734 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
10735 }
10736
10737 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
10738}
10739
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010740void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
10741 bool DefinitionRequired) {
10742 // Ignore any vtable uses in unevaluated operands or for classes that do
10743 // not have a vtable.
10744 if (!Class->isDynamicClass() || Class->isDependentContext() ||
10745 CurContext->isDependentContext() ||
Eli Friedman78a54242012-01-21 04:44:06 +000010746 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolabbf58bb2010-03-10 02:19:29 +000010747 return;
10748
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010749 // Try to insert this class into the map.
Douglas Gregordfe65432011-07-28 19:11:31 +000010750 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010751 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10752 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
10753 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
10754 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +000010755 // If we already had an entry, check to see if we are promoting this vtable
10756 // to required a definition. If so, we need to reappend to the VTableUses
10757 // list, since we may have already processed the first entry.
10758 if (DefinitionRequired && !Pos.first->second) {
10759 Pos.first->second = true;
10760 } else {
10761 // Otherwise, we can early exit.
10762 return;
10763 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010764 }
10765
10766 // Local classes need to have their virtual members marked
10767 // immediately. For all other classes, we mark their virtual members
10768 // at the end of the translation unit.
10769 if (Class->isLocalClass())
10770 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +000010771 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010772 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +000010773}
10774
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010775bool Sema::DefineUsedVTables() {
Douglas Gregordfe65432011-07-28 19:11:31 +000010776 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010777 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +000010778 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +000010779
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010780 // Note: The VTableUses vector could grow as a result of marking
10781 // the members of a class as "used", so we check the size each
Richard Smithb9d0b762012-07-27 04:22:15 +000010782 // time through the loop and prefer indices (which are stable) to
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010783 // iterators (which are not).
Douglas Gregor78844032011-04-22 22:25:37 +000010784 bool DefinedAnything = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010785 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +000010786 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010787 if (!Class)
10788 continue;
10789
10790 SourceLocation Loc = VTableUses[I].second;
10791
Richard Smithb9d0b762012-07-27 04:22:15 +000010792 bool DefineVTable = true;
10793
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010794 // If this class has a key function, but that key function is
10795 // defined in another translation unit, we don't need to emit the
10796 // vtable even though we're using it.
10797 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +000010798 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010799 switch (KeyFunction->getTemplateSpecializationKind()) {
10800 case TSK_Undeclared:
10801 case TSK_ExplicitSpecialization:
10802 case TSK_ExplicitInstantiationDeclaration:
10803 // The key function is in another translation unit.
Richard Smithb9d0b762012-07-27 04:22:15 +000010804 DefineVTable = false;
10805 break;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010806
10807 case TSK_ExplicitInstantiationDefinition:
10808 case TSK_ImplicitInstantiation:
10809 // We will be instantiating the key function.
10810 break;
10811 }
10812 } else if (!KeyFunction) {
10813 // If we have a class with no key function that is the subject
10814 // of an explicit instantiation declaration, suppress the
10815 // vtable; it will live with the explicit instantiation
10816 // definition.
10817 bool IsExplicitInstantiationDeclaration
10818 = Class->getTemplateSpecializationKind()
10819 == TSK_ExplicitInstantiationDeclaration;
10820 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
10821 REnd = Class->redecls_end();
10822 R != REnd; ++R) {
10823 TemplateSpecializationKind TSK
10824 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
10825 if (TSK == TSK_ExplicitInstantiationDeclaration)
10826 IsExplicitInstantiationDeclaration = true;
10827 else if (TSK == TSK_ExplicitInstantiationDefinition) {
10828 IsExplicitInstantiationDeclaration = false;
10829 break;
10830 }
10831 }
10832
10833 if (IsExplicitInstantiationDeclaration)
Richard Smithb9d0b762012-07-27 04:22:15 +000010834 DefineVTable = false;
10835 }
10836
10837 // The exception specifications for all virtual members may be needed even
10838 // if we are not providing an authoritative form of the vtable in this TU.
10839 // We may choose to emit it available_externally anyway.
10840 if (!DefineVTable) {
10841 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
10842 continue;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010843 }
10844
10845 // Mark all of the virtual members of this class as referenced, so
10846 // that we can build a vtable. Then, tell the AST consumer that a
10847 // vtable for this class is required.
Douglas Gregor78844032011-04-22 22:25:37 +000010848 DefinedAnything = true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010849 MarkVirtualMembersReferenced(Loc, Class);
10850 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10851 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
10852
10853 // Optionally warn if we're emitting a weak vtable.
10854 if (Class->getLinkage() == ExternalLinkage &&
10855 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Douglas Gregora120d012011-09-23 19:04:03 +000010856 const FunctionDecl *KeyFunctionDef = 0;
10857 if (!KeyFunction ||
10858 (KeyFunction->hasBody(KeyFunctionDef) &&
10859 KeyFunctionDef->isInlined()))
David Blaikie44d95b52011-12-09 18:32:50 +000010860 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
10861 TSK_ExplicitInstantiationDefinition
10862 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
10863 << Class;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010864 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010865 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010866 VTableUses.clear();
10867
Douglas Gregor78844032011-04-22 22:25:37 +000010868 return DefinedAnything;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010869}
Anders Carlssond6a637f2009-12-07 08:24:59 +000010870
Richard Smithb9d0b762012-07-27 04:22:15 +000010871void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
10872 const CXXRecordDecl *RD) {
10873 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
10874 E = RD->method_end(); I != E; ++I)
10875 if ((*I)->isVirtual() && !(*I)->isPure())
10876 ResolveExceptionSpec(Loc, (*I)->getType()->castAs<FunctionProtoType>());
10877}
10878
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010879void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
10880 const CXXRecordDecl *RD) {
Richard Smithff817f72012-07-07 06:59:51 +000010881 // Mark all functions which will appear in RD's vtable as used.
10882 CXXFinalOverriderMap FinalOverriders;
10883 RD->getFinalOverriders(FinalOverriders);
10884 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
10885 E = FinalOverriders.end();
10886 I != E; ++I) {
10887 for (OverridingMethods::const_iterator OI = I->second.begin(),
10888 OE = I->second.end();
10889 OI != OE; ++OI) {
10890 assert(OI->second.size() > 0 && "no final overrider");
10891 CXXMethodDecl *Overrider = OI->second.front().Method;
Anders Carlssond6a637f2009-12-07 08:24:59 +000010892
Richard Smithff817f72012-07-07 06:59:51 +000010893 // C++ [basic.def.odr]p2:
10894 // [...] A virtual member function is used if it is not pure. [...]
10895 if (!Overrider->isPure())
10896 MarkFunctionReferenced(Loc, Overrider);
10897 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000010898 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010899
10900 // Only classes that have virtual bases need a VTT.
10901 if (RD->getNumVBases() == 0)
10902 return;
10903
10904 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
10905 e = RD->bases_end(); i != e; ++i) {
10906 const CXXRecordDecl *Base =
10907 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010908 if (Base->getNumVBases() == 0)
10909 continue;
10910 MarkVirtualMembersReferenced(Loc, Base);
10911 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000010912}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010913
10914/// SetIvarInitializers - This routine builds initialization ASTs for the
10915/// Objective-C implementation whose ivars need be initialized.
10916void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikie4e4d0842012-03-11 07:00:24 +000010917 if (!getLangOpts().CPlusPlus)
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010918 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +000010919 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +000010920 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010921 CollectIvarsToConstructOrDestruct(OID, ivars);
10922 if (ivars.empty())
10923 return;
Chris Lattner5f9e2722011-07-23 10:55:15 +000010924 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010925 for (unsigned i = 0; i < ivars.size(); i++) {
10926 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010927 if (Field->isInvalidDecl())
10928 continue;
10929
Sean Huntcbb67482011-01-08 20:30:50 +000010930 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010931 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
10932 InitializationKind InitKind =
10933 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
10934
10935 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +000010936 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +000010937 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregor53c374f2010-12-07 00:41:46 +000010938 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010939 // Note, MemberInit could actually come back empty if no initialization
10940 // is required (e.g., because it would call a trivial default constructor)
10941 if (!MemberInit.get() || MemberInit.isInvalid())
10942 continue;
John McCallb4eb64d2010-10-08 02:01:28 +000010943
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010944 Member =
Sean Huntcbb67482011-01-08 20:30:50 +000010945 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
10946 SourceLocation(),
10947 MemberInit.takeAs<Expr>(),
10948 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010949 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010950
10951 // Be sure that the destructor is accessible and is marked as referenced.
10952 if (const RecordType *RecordTy
10953 = Context.getBaseElementType(Field->getType())
10954 ->getAs<RecordType>()) {
10955 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +000010956 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010957 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010958 CheckDestructorAccess(Field->getLocation(), Destructor,
10959 PDiag(diag::err_access_dtor_ivar)
10960 << Context.getBaseElementType(Field->getType()));
10961 }
10962 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010963 }
10964 ObjCImplementation->setIvarInitializers(Context,
10965 AllToInit.data(), AllToInit.size());
10966 }
10967}
Sean Huntfe57eef2011-05-04 05:57:24 +000010968
Sean Huntebcbe1d2011-05-04 23:29:54 +000010969static
10970void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
10971 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
10972 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
10973 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
10974 Sema &S) {
10975 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
10976 CE = Current.end();
10977 if (Ctor->isInvalidDecl())
10978 return;
10979
Richard Smitha8eaf002012-08-23 06:16:52 +000010980 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
10981
10982 // Target may not be determinable yet, for instance if this is a dependent
10983 // call in an uninstantiated template.
10984 if (Target) {
10985 const FunctionDecl *FNTarget = 0;
10986 (void)Target->hasBody(FNTarget);
10987 Target = const_cast<CXXConstructorDecl*>(
10988 cast_or_null<CXXConstructorDecl>(FNTarget));
10989 }
Sean Huntebcbe1d2011-05-04 23:29:54 +000010990
10991 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
10992 // Avoid dereferencing a null pointer here.
10993 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
10994
10995 if (!Current.insert(Canonical))
10996 return;
10997
10998 // We know that beyond here, we aren't chaining into a cycle.
10999 if (!Target || !Target->isDelegatingConstructor() ||
11000 Target->isInvalidDecl() || Valid.count(TCanonical)) {
11001 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11002 Valid.insert(*CI);
11003 Current.clear();
11004 // We've hit a cycle.
11005 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
11006 Current.count(TCanonical)) {
11007 // If we haven't diagnosed this cycle yet, do so now.
11008 if (!Invalid.count(TCanonical)) {
11009 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Sean Huntc1598702011-05-05 00:05:47 +000011010 diag::warn_delegating_ctor_cycle)
Sean Huntebcbe1d2011-05-04 23:29:54 +000011011 << Ctor;
11012
Richard Smitha8eaf002012-08-23 06:16:52 +000011013 // Don't add a note for a function delegating directly to itself.
Sean Huntebcbe1d2011-05-04 23:29:54 +000011014 if (TCanonical != Canonical)
11015 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
11016
11017 CXXConstructorDecl *C = Target;
11018 while (C->getCanonicalDecl() != Canonical) {
Richard Smitha8eaf002012-08-23 06:16:52 +000011019 const FunctionDecl *FNTarget = 0;
Sean Huntebcbe1d2011-05-04 23:29:54 +000011020 (void)C->getTargetConstructor()->hasBody(FNTarget);
11021 assert(FNTarget && "Ctor cycle through bodiless function");
11022
Richard Smitha8eaf002012-08-23 06:16:52 +000011023 C = const_cast<CXXConstructorDecl*>(
11024 cast<CXXConstructorDecl>(FNTarget));
Sean Huntebcbe1d2011-05-04 23:29:54 +000011025 S.Diag(C->getLocation(), diag::note_which_delegates_to);
11026 }
11027 }
11028
11029 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11030 Invalid.insert(*CI);
11031 Current.clear();
11032 } else {
11033 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
11034 }
11035}
11036
11037
Sean Huntfe57eef2011-05-04 05:57:24 +000011038void Sema::CheckDelegatingCtorCycles() {
11039 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
11040
Sean Huntebcbe1d2011-05-04 23:29:54 +000011041 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11042 CE = Current.end();
Sean Huntfe57eef2011-05-04 05:57:24 +000011043
Douglas Gregor0129b562011-07-27 21:57:17 +000011044 for (DelegatingCtorDeclsType::iterator
11045 I = DelegatingCtorDecls.begin(ExternalSource),
Sean Huntebcbe1d2011-05-04 23:29:54 +000011046 E = DelegatingCtorDecls.end();
Richard Smitha8eaf002012-08-23 06:16:52 +000011047 I != E; ++I)
11048 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Sean Huntebcbe1d2011-05-04 23:29:54 +000011049
11050 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
11051 (*CI)->setInvalidDecl();
Sean Huntfe57eef2011-05-04 05:57:24 +000011052}
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000011053
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011054namespace {
11055 /// \brief AST visitor that finds references to the 'this' expression.
11056 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
11057 Sema &S;
11058
11059 public:
11060 explicit FindCXXThisExpr(Sema &S) : S(S) { }
11061
11062 bool VisitCXXThisExpr(CXXThisExpr *E) {
11063 S.Diag(E->getLocation(), diag::err_this_static_member_func)
11064 << E->isImplicit();
11065 return false;
11066 }
11067 };
11068}
11069
11070bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
11071 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
11072 if (!TSInfo)
11073 return false;
11074
11075 TypeLoc TL = TSInfo->getTypeLoc();
11076 FunctionProtoTypeLoc *ProtoTL = dyn_cast<FunctionProtoTypeLoc>(&TL);
11077 if (!ProtoTL)
11078 return false;
11079
11080 // C++11 [expr.prim.general]p3:
11081 // [The expression this] shall not appear before the optional
11082 // cv-qualifier-seq and it shall not appear within the declaration of a
11083 // static member function (although its type and value category are defined
11084 // within a static member function as they are within a non-static member
11085 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumic86d1fd2012-04-21 09:40:04 +000011086 // until the complete declarator is known. - end note ]
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011087 const FunctionProtoType *Proto = ProtoTL->getTypePtr();
11088 FindCXXThisExpr Finder(*this);
11089
11090 // If the return type came after the cv-qualifier-seq, check it now.
11091 if (Proto->hasTrailingReturn() &&
11092 !Finder.TraverseTypeLoc(ProtoTL->getResultLoc()))
11093 return true;
11094
11095 // Check the exception specification.
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011096 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
11097 return true;
11098
11099 return checkThisInStaticMemberFunctionAttributes(Method);
11100}
11101
11102bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
11103 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
11104 if (!TSInfo)
11105 return false;
11106
11107 TypeLoc TL = TSInfo->getTypeLoc();
11108 FunctionProtoTypeLoc *ProtoTL = dyn_cast<FunctionProtoTypeLoc>(&TL);
11109 if (!ProtoTL)
11110 return false;
11111
11112 const FunctionProtoType *Proto = ProtoTL->getTypePtr();
11113 FindCXXThisExpr Finder(*this);
11114
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011115 switch (Proto->getExceptionSpecType()) {
Richard Smithe6975e92012-04-17 00:58:00 +000011116 case EST_Uninstantiated:
Richard Smithb9d0b762012-07-27 04:22:15 +000011117 case EST_Unevaluated:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011118 case EST_BasicNoexcept:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011119 case EST_DynamicNone:
11120 case EST_MSAny:
11121 case EST_None:
11122 break;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011123
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011124 case EST_ComputedNoexcept:
11125 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
11126 return true;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011127
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011128 case EST_Dynamic:
11129 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011130 EEnd = Proto->exception_end();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011131 E != EEnd; ++E) {
11132 if (!Finder.TraverseType(*E))
11133 return true;
11134 }
11135 break;
11136 }
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011137
11138 return false;
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011139}
11140
11141bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
11142 FindCXXThisExpr Finder(*this);
11143
11144 // Check attributes.
11145 for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end();
11146 A != AEnd; ++A) {
11147 // FIXME: This should be emitted by tblgen.
11148 Expr *Arg = 0;
11149 ArrayRef<Expr *> Args;
11150 if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A))
11151 Arg = G->getArg();
11152 else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A))
11153 Arg = G->getArg();
11154 else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A))
11155 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
11156 else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A))
11157 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
11158 else if (ExclusiveLockFunctionAttr *ELF
11159 = dyn_cast<ExclusiveLockFunctionAttr>(*A))
11160 Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size());
11161 else if (SharedLockFunctionAttr *SLF
11162 = dyn_cast<SharedLockFunctionAttr>(*A))
11163 Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size());
11164 else if (ExclusiveTrylockFunctionAttr *ETLF
11165 = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) {
11166 Arg = ETLF->getSuccessValue();
11167 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
11168 } else if (SharedTrylockFunctionAttr *STLF
11169 = dyn_cast<SharedTrylockFunctionAttr>(*A)) {
11170 Arg = STLF->getSuccessValue();
11171 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
11172 } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A))
11173 Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size());
11174 else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A))
11175 Arg = LR->getArg();
11176 else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A))
11177 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
11178 else if (ExclusiveLocksRequiredAttr *ELR
11179 = dyn_cast<ExclusiveLocksRequiredAttr>(*A))
11180 Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size());
11181 else if (SharedLocksRequiredAttr *SLR
11182 = dyn_cast<SharedLocksRequiredAttr>(*A))
11183 Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size());
11184
11185 if (Arg && !Finder.TraverseStmt(Arg))
11186 return true;
11187
11188 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
11189 if (!Finder.TraverseStmt(Args[I]))
11190 return true;
11191 }
11192 }
11193
11194 return false;
11195}
11196
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011197void
11198Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
11199 ArrayRef<ParsedType> DynamicExceptions,
11200 ArrayRef<SourceRange> DynamicExceptionRanges,
11201 Expr *NoexceptExpr,
11202 llvm::SmallVectorImpl<QualType> &Exceptions,
11203 FunctionProtoType::ExtProtoInfo &EPI) {
11204 Exceptions.clear();
11205 EPI.ExceptionSpecType = EST;
11206 if (EST == EST_Dynamic) {
11207 Exceptions.reserve(DynamicExceptions.size());
11208 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
11209 // FIXME: Preserve type source info.
11210 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
11211
11212 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
11213 collectUnexpandedParameterPacks(ET, Unexpanded);
11214 if (!Unexpanded.empty()) {
11215 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
11216 UPPC_ExceptionType,
11217 Unexpanded);
11218 continue;
11219 }
11220
11221 // Check that the type is valid for an exception spec, and
11222 // drop it if not.
11223 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
11224 Exceptions.push_back(ET);
11225 }
11226 EPI.NumExceptions = Exceptions.size();
11227 EPI.Exceptions = Exceptions.data();
11228 return;
11229 }
11230
11231 if (EST == EST_ComputedNoexcept) {
11232 // If an error occurred, there's no expression here.
11233 if (NoexceptExpr) {
11234 assert((NoexceptExpr->isTypeDependent() ||
11235 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
11236 Context.BoolTy) &&
11237 "Parser should have made sure that the expression is boolean");
11238 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
11239 EPI.ExceptionSpecType = EST_BasicNoexcept;
11240 return;
11241 }
11242
11243 if (!NoexceptExpr->isValueDependent())
11244 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0,
Douglas Gregorab41fe92012-05-04 22:38:52 +000011245 diag::err_noexcept_needs_constant_expression,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011246 /*AllowFold*/ false).take();
11247 EPI.NoexceptExpr = NoexceptExpr;
11248 }
11249 return;
11250 }
11251}
11252
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000011253/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
11254Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
11255 // Implicitly declared functions (e.g. copy constructors) are
11256 // __host__ __device__
11257 if (D->isImplicit())
11258 return CFT_HostDevice;
11259
11260 if (D->hasAttr<CUDAGlobalAttr>())
11261 return CFT_Global;
11262
11263 if (D->hasAttr<CUDADeviceAttr>()) {
11264 if (D->hasAttr<CUDAHostAttr>())
11265 return CFT_HostDevice;
11266 else
11267 return CFT_Device;
11268 }
11269
11270 return CFT_Host;
11271}
11272
11273bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
11274 CUDAFunctionTarget CalleeTarget) {
11275 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
11276 // Callable from the device only."
11277 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
11278 return true;
11279
11280 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
11281 // Callable from the host only."
11282 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
11283 // Callable from the host only."
11284 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
11285 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
11286 return true;
11287
11288 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
11289 return true;
11290
11291 return false;
11292}