blob: 3b1f67c07feb0b75fa9f0ebb5041c93307a910d0 [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"
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +000015#include "clang/AST/ASTConsumer.h"
Douglas Gregore37ac4f2008-04-13 21:30:24 +000016#include "clang/AST/ASTContext.h"
Faisal Valifad9e132013-09-26 19:54:12 +000017#include "clang/AST/ASTLambda.h"
Sebastian Redl58a2cd82011-04-24 16:28:06 +000018#include "clang/AST/ASTMutationListener.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000019#include "clang/AST/CXXInheritance.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000020#include "clang/AST/CharUnits.h"
Anders Carlsson8211eff2009-03-24 01:19:16 +000021#include "clang/AST/DeclVisitor.h"
Richard Trieude5e75c2012-06-14 23:11:34 +000022#include "clang/AST/EvaluatedExprVisitor.h"
Sean Hunt41717662011-02-26 19:13:13 +000023#include "clang/AST/ExprCXX.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000024#include "clang/AST/RecordLayout.h"
Douglas Gregorcefc3af2012-04-16 07:05:22 +000025#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000026#include "clang/AST/StmtVisitor.h"
Douglas Gregor802ab452009-12-02 22:36:29 +000027#include "clang/AST/TypeLoc.h"
Douglas Gregor02189362008-10-22 21:13:31 +000028#include "clang/AST/TypeOrdering.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000029#include "clang/Basic/PartialDiagnostic.h"
Aaron Ballmanfff32482012-12-09 17:45:41 +000030#include "clang/Basic/TargetInfo.h"
Richard Smith4ac537b2013-07-23 08:14:48 +000031#include "clang/Lex/LiteralSupport.h"
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +000032#include "clang/Lex/Preprocessor.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000033#include "clang/Sema/CXXFieldCollector.h"
34#include "clang/Sema/DeclSpec.h"
35#include "clang/Sema/Initialization.h"
36#include "clang/Sema/Lookup.h"
37#include "clang/Sema/ParsedTemplate.h"
38#include "clang/Sema/Scope.h"
39#include "clang/Sema/ScopeInfo.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000040#include "llvm/ADT/STLExtras.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000041#include "llvm/ADT/SmallString.h"
Douglas Gregorf8268ae2008-10-22 17:49:05 +000042#include <map>
Douglas Gregora8f32e02009-10-06 17:59:45 +000043#include <set>
Chris Lattner3d1cee32008-04-08 05:04:30 +000044
45using namespace clang;
46
Chris Lattner8123a952008-04-10 02:22:51 +000047//===----------------------------------------------------------------------===//
48// CheckDefaultArgumentVisitor
49//===----------------------------------------------------------------------===//
50
Chris Lattner9e979552008-04-12 23:52:44 +000051namespace {
52 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
53 /// the default argument of a parameter to determine whether it
54 /// contains any ill-formed subexpressions. For example, this will
55 /// diagnose the use of local variables or parameters within the
56 /// default argument expression.
Benjamin Kramer85b45212009-11-28 19:45:26 +000057 class CheckDefaultArgumentVisitor
Chris Lattnerb77792e2008-07-26 22:17:49 +000058 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattner9e979552008-04-12 23:52:44 +000059 Expr *DefaultArg;
60 Sema *S;
Chris Lattner8123a952008-04-10 02:22:51 +000061
Chris Lattner9e979552008-04-12 23:52:44 +000062 public:
Mike Stump1eb44332009-09-09 15:08:12 +000063 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattner9e979552008-04-12 23:52:44 +000064 : DefaultArg(defarg), S(s) {}
Chris Lattner8123a952008-04-10 02:22:51 +000065
Chris Lattner9e979552008-04-12 23:52:44 +000066 bool VisitExpr(Expr *Node);
67 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor796da182008-11-04 14:32:21 +000068 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Douglas Gregorf0459f82012-02-10 23:30:22 +000069 bool VisitLambdaExpr(LambdaExpr *Lambda);
John McCall045d2522013-04-09 01:56:28 +000070 bool VisitPseudoObjectExpr(PseudoObjectExpr *POE);
Chris Lattner9e979552008-04-12 23:52:44 +000071 };
Chris Lattner8123a952008-04-10 02:22:51 +000072
Chris Lattner9e979552008-04-12 23:52:44 +000073 /// VisitExpr - Visit all of the children of this expression.
74 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
75 bool IsInvalid = false;
John McCall7502c1d2011-02-13 04:07:26 +000076 for (Stmt::child_range I = Node->children(); I; ++I)
Chris Lattnerb77792e2008-07-26 22:17:49 +000077 IsInvalid |= Visit(*I);
Chris Lattner9e979552008-04-12 23:52:44 +000078 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000079 }
80
Chris Lattner9e979552008-04-12 23:52:44 +000081 /// VisitDeclRefExpr - Visit a reference to a declaration, to
82 /// determine whether this declaration can be used in the default
83 /// argument expression.
84 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000085 NamedDecl *Decl = DRE->getDecl();
Chris Lattner9e979552008-04-12 23:52:44 +000086 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
87 // C++ [dcl.fct.default]p9
88 // Default arguments are evaluated each time the function is
89 // called. The order of evaluation of function arguments is
90 // unspecified. Consequently, parameters of a function shall not
91 // be used in default argument expressions, even if they are not
92 // evaluated. Parameters of a function declared before a default
93 // argument expression are in scope and can hide namespace and
94 // class member names.
Daniel Dunbar96a00142012-03-09 18:35:03 +000095 return S->Diag(DRE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000096 diag::err_param_default_argument_references_param)
Chris Lattner08631c52008-11-23 21:45:46 +000097 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff248a7532008-04-15 22:42:06 +000098 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000099 // C++ [dcl.fct.default]p7
100 // Local variables shall not be used in default argument
101 // expressions.
John McCallb6bbcc92010-10-15 04:57:14 +0000102 if (VDecl->isLocalVarDecl())
Daniel Dunbar96a00142012-03-09 18:35:03 +0000103 return S->Diag(DRE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000104 diag::err_param_default_argument_references_local)
Chris Lattner08631c52008-11-23 21:45:46 +0000105 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000106 }
Chris Lattner8123a952008-04-10 02:22:51 +0000107
Douglas Gregor3996f232008-11-04 13:41:56 +0000108 return false;
109 }
Chris Lattner9e979552008-04-12 23:52:44 +0000110
Douglas Gregor796da182008-11-04 14:32:21 +0000111 /// VisitCXXThisExpr - Visit a C++ "this" expression.
112 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
113 // C++ [dcl.fct.default]p8:
114 // The keyword this shall not be used in a default argument of a
115 // member function.
Daniel Dunbar96a00142012-03-09 18:35:03 +0000116 return S->Diag(ThisE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000117 diag::err_param_default_argument_references_this)
118 << ThisE->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000119 }
Douglas Gregorf0459f82012-02-10 23:30:22 +0000120
John McCall045d2522013-04-09 01:56:28 +0000121 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
122 bool Invalid = false;
123 for (PseudoObjectExpr::semantics_iterator
124 i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) {
125 Expr *E = *i;
126
127 // Look through bindings.
128 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
129 E = OVE->getSourceExpr();
130 assert(E && "pseudo-object binding without source expression?");
131 }
132
133 Invalid |= Visit(E);
134 }
135 return Invalid;
136 }
137
Douglas Gregorf0459f82012-02-10 23:30:22 +0000138 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
139 // C++11 [expr.lambda.prim]p13:
140 // A lambda-expression appearing in a default argument shall not
141 // implicitly or explicitly capture any entity.
142 if (Lambda->capture_begin() == Lambda->capture_end())
143 return false;
144
145 return S->Diag(Lambda->getLocStart(),
146 diag::err_lambda_capture_default_arg);
147 }
Chris Lattner8123a952008-04-10 02:22:51 +0000148}
149
Richard Smith0b0ca472013-04-10 06:11:48 +0000150void
151Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
152 const CXXMethodDecl *Method) {
Richard Smithb9d0b762012-07-27 04:22:15 +0000153 // If we have an MSAny spec already, don't bother.
154 if (!Method || ComputedEST == EST_MSAny)
Sean Hunt001cad92011-05-10 00:49:42 +0000155 return;
156
157 const FunctionProtoType *Proto
158 = Method->getType()->getAs<FunctionProtoType>();
Richard Smithe6975e92012-04-17 00:58:00 +0000159 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
160 if (!Proto)
161 return;
Sean Hunt001cad92011-05-10 00:49:42 +0000162
163 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
164
165 // If this function can throw any exceptions, make a note of that.
Richard Smithb9d0b762012-07-27 04:22:15 +0000166 if (EST == EST_MSAny || EST == EST_None) {
Sean Hunt001cad92011-05-10 00:49:42 +0000167 ClearExceptions();
168 ComputedEST = EST;
169 return;
170 }
171
Richard Smith7a614d82011-06-11 17:19:42 +0000172 // FIXME: If the call to this decl is using any of its default arguments, we
173 // need to search them for potentially-throwing calls.
174
Sean Hunt001cad92011-05-10 00:49:42 +0000175 // If this function has a basic noexcept, it doesn't affect the outcome.
176 if (EST == EST_BasicNoexcept)
177 return;
178
179 // If we have a throw-all spec at this point, ignore the function.
180 if (ComputedEST == EST_None)
181 return;
182
183 // If we're still at noexcept(true) and there's a nothrow() callee,
184 // change to that specification.
185 if (EST == EST_DynamicNone) {
186 if (ComputedEST == EST_BasicNoexcept)
187 ComputedEST = EST_DynamicNone;
188 return;
189 }
190
191 // Check out noexcept specs.
192 if (EST == EST_ComputedNoexcept) {
Richard Smithe6975e92012-04-17 00:58:00 +0000193 FunctionProtoType::NoexceptResult NR =
194 Proto->getNoexceptSpec(Self->Context);
Sean Hunt001cad92011-05-10 00:49:42 +0000195 assert(NR != FunctionProtoType::NR_NoNoexcept &&
196 "Must have noexcept result for EST_ComputedNoexcept.");
197 assert(NR != FunctionProtoType::NR_Dependent &&
198 "Should not generate implicit declarations for dependent cases, "
199 "and don't know how to handle them anyway.");
200
201 // noexcept(false) -> no spec on the new function
202 if (NR == FunctionProtoType::NR_Throw) {
203 ClearExceptions();
204 ComputedEST = EST_None;
205 }
206 // noexcept(true) won't change anything either.
207 return;
208 }
209
210 assert(EST == EST_Dynamic && "EST case not considered earlier.");
211 assert(ComputedEST != EST_None &&
212 "Shouldn't collect exceptions when throw-all is guaranteed.");
213 ComputedEST = EST_Dynamic;
214 // Record the exceptions in this function's exception specification.
215 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
216 EEnd = Proto->exception_end();
217 E != EEnd; ++E)
Richard Smithe6975e92012-04-17 00:58:00 +0000218 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(*E)))
Sean Hunt001cad92011-05-10 00:49:42 +0000219 Exceptions.push_back(*E);
220}
221
Richard Smith7a614d82011-06-11 17:19:42 +0000222void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
Richard Smithb9d0b762012-07-27 04:22:15 +0000223 if (!E || ComputedEST == EST_MSAny)
Richard Smith7a614d82011-06-11 17:19:42 +0000224 return;
225
226 // FIXME:
227 //
228 // C++0x [except.spec]p14:
NAKAMURA Takumi48579472011-06-21 03:19:28 +0000229 // [An] implicit exception-specification specifies the type-id T if and
230 // only if T is allowed by the exception-specification of a function directly
231 // invoked by f's implicit definition; f shall allow all exceptions if any
Richard Smith7a614d82011-06-11 17:19:42 +0000232 // function it directly invokes allows all exceptions, and f shall allow no
233 // exceptions if every function it directly invokes allows no exceptions.
234 //
235 // Note in particular that if an implicit exception-specification is generated
236 // for a function containing a throw-expression, that specification can still
237 // be noexcept(true).
238 //
239 // Note also that 'directly invoked' is not defined in the standard, and there
240 // is no indication that we should only consider potentially-evaluated calls.
241 //
242 // Ultimately we should implement the intent of the standard: the exception
243 // specification should be the set of exceptions which can be thrown by the
244 // implicit definition. For now, we assume that any non-nothrow expression can
245 // throw any exception.
246
Richard Smithe6975e92012-04-17 00:58:00 +0000247 if (Self->canThrow(E))
Richard Smith7a614d82011-06-11 17:19:42 +0000248 ComputedEST = EST_None;
249}
250
Anders Carlssoned961f92009-08-25 02:29:20 +0000251bool
John McCall9ae2f072010-08-23 23:25:46 +0000252Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump1eb44332009-09-09 15:08:12 +0000253 SourceLocation EqualLoc) {
Anders Carlsson5653ca52009-08-25 13:46:13 +0000254 if (RequireCompleteType(Param->getLocation(), Param->getType(),
255 diag::err_typecheck_decl_incomplete_type)) {
256 Param->setInvalidDecl();
257 return true;
258 }
259
Anders Carlssoned961f92009-08-25 02:29:20 +0000260 // C++ [dcl.fct.default]p5
261 // A default argument expression is implicitly converted (clause
262 // 4) to the parameter type. The default argument expression has
263 // the same semantic constraints as the initializer expression in
264 // a declaration of a variable of the parameter type, using the
265 // copy-initialization semantics (8.5).
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000266 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
267 Param);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000268 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
269 EqualLoc);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +0000270 InitializationSequence InitSeq(*this, Entity, Kind, Arg);
Benjamin Kramer5354e772012-08-23 23:38:35 +0000271 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000272 if (Result.isInvalid())
Anders Carlsson9351c172009-08-25 03:18:48 +0000273 return true;
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000274 Arg = Result.takeAs<Expr>();
Anders Carlssoned961f92009-08-25 02:29:20 +0000275
Richard Smith6c3af3d2013-01-17 01:17:56 +0000276 CheckCompletedExpr(Arg, EqualLoc);
John McCall4765fa02010-12-06 08:20:24 +0000277 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000278
Anders Carlssoned961f92009-08-25 02:29:20 +0000279 // Okay: add the default argument to the parameter
280 Param->setDefaultArg(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000281
Douglas Gregor8cfb7a32010-10-12 18:23:32 +0000282 // We have already instantiated this parameter; provide each of the
283 // instantiations with the uninstantiated default argument.
284 UnparsedDefaultArgInstantiationsMap::iterator InstPos
285 = UnparsedDefaultArgInstantiations.find(Param);
286 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
287 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
288 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
289
290 // We're done tracking this parameter's instantiations.
291 UnparsedDefaultArgInstantiations.erase(InstPos);
292 }
293
Anders Carlsson9351c172009-08-25 03:18:48 +0000294 return false;
Anders Carlssoned961f92009-08-25 02:29:20 +0000295}
296
Chris Lattner8123a952008-04-10 02:22:51 +0000297/// ActOnParamDefaultArgument - Check whether the default argument
298/// provided for a function parameter is well-formed. If so, attach it
299/// to the parameter declaration.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000300void
John McCalld226f652010-08-21 09:40:31 +0000301Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000302 Expr *DefaultArg) {
303 if (!param || !DefaultArg)
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000304 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000305
John McCalld226f652010-08-21 09:40:31 +0000306 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000307 UnparsedDefaultArgLocs.erase(Param);
308
Chris Lattner3d1cee32008-04-08 05:04:30 +0000309 // Default arguments are only permitted in C++
David Blaikie4e4d0842012-03-11 07:00:24 +0000310 if (!getLangOpts().CPlusPlus) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000311 Diag(EqualLoc, diag::err_param_default_argument)
312 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000313 Param->setInvalidDecl();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000314 return;
315 }
316
Douglas Gregor6f526752010-12-16 08:48:57 +0000317 // Check for unexpanded parameter packs.
318 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
319 Param->setInvalidDecl();
320 return;
321 }
322
Anders Carlsson66e30672009-08-25 01:02:06 +0000323 // Check that the default argument is well-formed
John McCall9ae2f072010-08-23 23:25:46 +0000324 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
325 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlsson66e30672009-08-25 01:02:06 +0000326 Param->setInvalidDecl();
327 return;
328 }
Mike Stump1eb44332009-09-09 15:08:12 +0000329
John McCall9ae2f072010-08-23 23:25:46 +0000330 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000331}
332
Douglas Gregor61366e92008-12-24 00:01:03 +0000333/// ActOnParamUnparsedDefaultArgument - We've seen a default
334/// argument for a function parameter, but we can't parse it yet
335/// because we're inside a class definition. Note that this default
336/// argument will be parsed later.
John McCalld226f652010-08-21 09:40:31 +0000337void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson5e300d12009-06-12 16:51:40 +0000338 SourceLocation EqualLoc,
339 SourceLocation ArgLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000340 if (!param)
341 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000342
John McCalld226f652010-08-21 09:40:31 +0000343 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Nick Lewyckyee0bc3b2013-09-22 10:06:57 +0000344 Param->setUnparsedDefaultArg();
Anders Carlsson5e300d12009-06-12 16:51:40 +0000345 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor61366e92008-12-24 00:01:03 +0000346}
347
Douglas Gregor72b505b2008-12-16 21:30:33 +0000348/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
349/// the default argument for the parameter param failed.
John McCalld226f652010-08-21 09:40:31 +0000350void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000351 if (!param)
352 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000353
John McCalld226f652010-08-21 09:40:31 +0000354 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000355 Param->setInvalidDecl();
Anders Carlsson5e300d12009-06-12 16:51:40 +0000356 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000357}
358
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000359/// CheckExtraCXXDefaultArguments - Check for any extra default
360/// arguments in the declarator, which is not a function declaration
361/// or definition and therefore is not permitted to have default
362/// arguments. This routine should be invoked for every declarator
363/// that is not a function declaration or definition.
364void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
365 // C++ [dcl.fct.default]p3
366 // A default argument expression shall be specified only in the
367 // parameter-declaration-clause of a function declaration or in a
368 // template-parameter (14.1). It shall not be specified for a
369 // parameter pack. If it is specified in a
370 // parameter-declaration-clause, it shall not occur within a
371 // declarator or abstract-declarator of a parameter-declaration.
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000372 bool MightBeFunction = D.isFunctionDeclarationContext();
Chris Lattnerb28317a2009-03-28 19:18:32 +0000373 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000374 DeclaratorChunk &chunk = D.getTypeObject(i);
375 if (chunk.Kind == DeclaratorChunk::Function) {
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000376 if (MightBeFunction) {
377 // This is a function declaration. It can have default arguments, but
378 // keep looking in case its return type is a function type with default
379 // arguments.
380 MightBeFunction = false;
381 continue;
382 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000383 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
384 ParmVarDecl *Param =
John McCalld226f652010-08-21 09:40:31 +0000385 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000386 if (Param->hasUnparsedDefaultArg()) {
387 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000388 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000389 << SourceRange((*Toks)[1].getLocation(),
390 Toks->back().getLocation());
Douglas Gregor72b505b2008-12-16 21:30:33 +0000391 delete Toks;
392 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor61366e92008-12-24 00:01:03 +0000393 } else if (Param->getDefaultArg()) {
394 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
395 << Param->getDefaultArg()->getSourceRange();
396 Param->setDefaultArg(0);
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000397 }
398 }
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000399 } else if (chunk.Kind != DeclaratorChunk::Paren) {
400 MightBeFunction = false;
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000401 }
402 }
403}
404
David Majnemerf6a144f2013-06-25 23:09:30 +0000405static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
406 for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
407 const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
408 if (!PVD->hasDefaultArg())
409 return false;
410 if (!PVD->hasInheritedDefaultArg())
411 return true;
412 }
413 return false;
414}
415
Craig Topper1a6eac82012-09-21 04:33:26 +0000416/// MergeCXXFunctionDecl - Merge two declarations of the same C++
417/// function, once we already know that they have the same
418/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
419/// error, false otherwise.
James Molloy9cda03f2012-03-13 08:55:35 +0000420bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
421 Scope *S) {
Douglas Gregorcda9c672009-02-16 17:45:42 +0000422 bool Invalid = false;
423
Chris Lattner3d1cee32008-04-08 05:04:30 +0000424 // C++ [dcl.fct.default]p4:
Chris Lattner3d1cee32008-04-08 05:04:30 +0000425 // For non-template functions, default arguments can be added in
426 // later declarations of a function in the same
427 // scope. Declarations in different scopes have completely
428 // distinct sets of default arguments. That is, declarations in
429 // inner scopes do not acquire default arguments from
430 // declarations in outer scopes, and vice versa. In a given
431 // function declaration, all parameters subsequent to a
432 // parameter with a default argument shall have default
433 // arguments supplied in this or previous declarations. A
434 // default argument shall not be redefined by a later
435 // declaration (not even to the same value).
Douglas Gregor6cc15182009-09-11 18:44:32 +0000436 //
437 // C++ [dcl.fct.default]p6:
Richard Smitha41c97a2013-09-20 01:15:31 +0000438 // Except for member functions of class templates, the default arguments
439 // in a member function definition that appears outside of the class
440 // definition are added to the set of default arguments provided by the
Douglas Gregor6cc15182009-09-11 18:44:32 +0000441 // member function declaration in the class definition.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000442 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
443 ParmVarDecl *OldParam = Old->getParamDecl(p);
444 ParmVarDecl *NewParam = New->getParamDecl(p);
445
James Molloy9cda03f2012-03-13 08:55:35 +0000446 bool OldParamHasDfl = OldParam->hasDefaultArg();
447 bool NewParamHasDfl = NewParam->hasDefaultArg();
448
449 NamedDecl *ND = Old;
Richard Smitha41c97a2013-09-20 01:15:31 +0000450
451 // The declaration context corresponding to the scope is the semantic
452 // parent, unless this is a local function declaration, in which case
453 // it is that surrounding function.
454 DeclContext *ScopeDC = New->getLexicalDeclContext();
455 if (!ScopeDC->isFunctionOrMethod())
456 ScopeDC = New->getDeclContext();
457 if (S && !isDeclInScope(ND, ScopeDC, S) &&
458 !New->getDeclContext()->isRecord())
James Molloy9cda03f2012-03-13 08:55:35 +0000459 // Ignore default parameters of old decl if they are not in
Richard Smitha41c97a2013-09-20 01:15:31 +0000460 // the same scope and this is not an out-of-line definition of
461 // a member function.
James Molloy9cda03f2012-03-13 08:55:35 +0000462 OldParamHasDfl = false;
463
464 if (OldParamHasDfl && NewParamHasDfl) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000465
Francois Pichet8d051e02011-04-10 03:03:52 +0000466 unsigned DiagDefaultParamID =
467 diag::err_param_default_argument_redefinition;
468
469 // MSVC accepts that default parameters be redefined for member functions
470 // of template class. The new default parameter's value is ignored.
471 Invalid = true;
David Blaikie4e4d0842012-03-11 07:00:24 +0000472 if (getLangOpts().MicrosoftExt) {
Francois Pichet8d051e02011-04-10 03:03:52 +0000473 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
474 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000475 // Merge the old default argument into the new parameter.
476 NewParam->setHasInheritedDefaultArg();
477 if (OldParam->hasUninstantiatedDefaultArg())
478 NewParam->setUninstantiatedDefaultArg(
479 OldParam->getUninstantiatedDefaultArg());
480 else
481 NewParam->setDefaultArg(OldParam->getInit());
Francois Pichetcf320c62011-04-22 08:25:24 +0000482 DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
Francois Pichet8d051e02011-04-10 03:03:52 +0000483 Invalid = false;
484 }
485 }
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000486
Francois Pichet8cf90492011-04-10 04:58:30 +0000487 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
488 // hint here. Alternatively, we could walk the type-source information
489 // for NewParam to find the last source location in the type... but it
490 // isn't worth the effort right now. This is the kind of test case that
491 // is hard to get right:
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000492 // int f(int);
493 // void g(int (*fp)(int) = f);
494 // void g(int (*fp)(int) = &f);
Francois Pichet8d051e02011-04-10 03:03:52 +0000495 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000496 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000497
498 // Look for the function declaration where the default argument was
499 // actually written, which may be a declaration prior to Old.
Douglas Gregoref96ee02012-01-14 16:38:05 +0000500 for (FunctionDecl *Older = Old->getPreviousDecl();
501 Older; Older = Older->getPreviousDecl()) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000502 if (!Older->getParamDecl(p)->hasDefaultArg())
503 break;
504
505 OldParam = Older->getParamDecl(p);
506 }
507
508 Diag(OldParam->getLocation(), diag::note_previous_definition)
509 << OldParam->getDefaultArgRange();
James Molloy9cda03f2012-03-13 08:55:35 +0000510 } else if (OldParamHasDfl) {
John McCall3d6c1782010-05-04 01:53:42 +0000511 // Merge the old default argument into the new parameter.
512 // It's important to use getInit() here; getDefaultArg()
John McCall4765fa02010-12-06 08:20:24 +0000513 // strips off any top-level ExprWithCleanups.
John McCallbf73b352010-03-12 18:31:32 +0000514 NewParam->setHasInheritedDefaultArg();
Douglas Gregord85cef52009-09-17 19:51:30 +0000515 if (OldParam->hasUninstantiatedDefaultArg())
516 NewParam->setUninstantiatedDefaultArg(
517 OldParam->getUninstantiatedDefaultArg());
518 else
John McCall3d6c1782010-05-04 01:53:42 +0000519 NewParam->setDefaultArg(OldParam->getInit());
James Molloy9cda03f2012-03-13 08:55:35 +0000520 } else if (NewParamHasDfl) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000521 if (New->getDescribedFunctionTemplate()) {
522 // Paragraph 4, quoted above, only applies to non-template functions.
523 Diag(NewParam->getLocation(),
524 diag::err_param_default_argument_template_redecl)
525 << NewParam->getDefaultArgRange();
526 Diag(Old->getLocation(), diag::note_template_prev_declaration)
527 << false;
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000528 } else if (New->getTemplateSpecializationKind()
529 != TSK_ImplicitInstantiation &&
530 New->getTemplateSpecializationKind() != TSK_Undeclared) {
531 // C++ [temp.expr.spec]p21:
532 // Default function arguments shall not be specified in a declaration
533 // or a definition for one of the following explicit specializations:
534 // - the explicit specialization of a function template;
Douglas Gregor8c638ab2009-10-13 23:52:38 +0000535 // - the explicit specialization of a member function template;
536 // - the explicit specialization of a member function of a class
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000537 // template where the class template specialization to which the
538 // member function specialization belongs is implicitly
539 // instantiated.
540 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
541 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
542 << New->getDeclName()
543 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000544 } else if (New->getDeclContext()->isDependentContext()) {
545 // C++ [dcl.fct.default]p6 (DR217):
546 // Default arguments for a member function of a class template shall
547 // be specified on the initial declaration of the member function
548 // within the class template.
549 //
550 // Reading the tea leaves a bit in DR217 and its reference to DR205
551 // leads me to the conclusion that one cannot add default function
552 // arguments for an out-of-line definition of a member function of a
553 // dependent type.
554 int WhichKind = 2;
555 if (CXXRecordDecl *Record
556 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
557 if (Record->getDescribedClassTemplate())
558 WhichKind = 0;
559 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
560 WhichKind = 1;
561 else
562 WhichKind = 2;
563 }
564
565 Diag(NewParam->getLocation(),
566 diag::err_param_default_argument_member_template_redecl)
567 << WhichKind
568 << NewParam->getDefaultArgRange();
569 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000570 }
571 }
572
Richard Smithb8abff62012-11-28 03:45:24 +0000573 // DR1344: If a default argument is added outside a class definition and that
574 // default argument makes the function a special member function, the program
575 // is ill-formed. This can only happen for constructors.
576 if (isa<CXXConstructorDecl>(New) &&
577 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
578 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
579 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
580 if (NewSM != OldSM) {
581 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
582 assert(NewParam->hasDefaultArg());
583 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
584 << NewParam->getDefaultArgRange() << NewSM;
585 Diag(Old->getLocation(), diag::note_previous_declaration);
586 }
587 }
588
Richard Smithff234882012-02-20 23:28:05 +0000589 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
Richard Smith9f569cc2011-10-01 02:31:28 +0000590 // template has a constexpr specifier then all its declarations shall
Richard Smithff234882012-02-20 23:28:05 +0000591 // contain the constexpr specifier.
Richard Smith9f569cc2011-10-01 02:31:28 +0000592 if (New->isConstexpr() != Old->isConstexpr()) {
593 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
594 << New << New->isConstexpr();
595 Diag(Old->getLocation(), diag::note_previous_declaration);
596 Invalid = true;
597 }
598
David Majnemerf6a144f2013-06-25 23:09:30 +0000599 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
NAKAMURA Takumifd527a42013-07-17 17:57:52 +0000600 // argument expression, that declaration shall be a definition and shall be
David Majnemerf6a144f2013-06-25 23:09:30 +0000601 // the only declaration of the function or function template in the
602 // translation unit.
603 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
604 functionDeclHasDefaultArgument(Old)) {
605 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
606 Diag(Old->getLocation(), diag::note_previous_declaration);
607 Invalid = true;
608 }
609
Douglas Gregore13ad832010-02-12 07:32:17 +0000610 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000611 Invalid = true;
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000612
Douglas Gregorcda9c672009-02-16 17:45:42 +0000613 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000614}
615
Sebastian Redl60618fa2011-03-12 11:50:43 +0000616/// \brief Merge the exception specifications of two variable declarations.
617///
618/// This is called when there's a redeclaration of a VarDecl. The function
619/// checks if the redeclaration might have an exception specification and
620/// validates compatibility and merges the specs if necessary.
621void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
622 // Shortcut if exceptions are disabled.
David Blaikie4e4d0842012-03-11 07:00:24 +0000623 if (!getLangOpts().CXXExceptions)
Sebastian Redl60618fa2011-03-12 11:50:43 +0000624 return;
625
626 assert(Context.hasSameType(New->getType(), Old->getType()) &&
627 "Should only be called if types are otherwise the same.");
628
629 QualType NewType = New->getType();
630 QualType OldType = Old->getType();
631
632 // We're only interested in pointers and references to functions, as well
633 // as pointers to member functions.
634 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
635 NewType = R->getPointeeType();
636 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
637 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
638 NewType = P->getPointeeType();
639 OldType = OldType->getAs<PointerType>()->getPointeeType();
640 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
641 NewType = M->getPointeeType();
642 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
643 }
644
645 if (!NewType->isFunctionProtoType())
646 return;
647
648 // There's lots of special cases for functions. For function pointers, system
649 // libraries are hopefully not as broken so that we don't need these
650 // workarounds.
651 if (CheckEquivalentExceptionSpec(
652 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
653 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
654 New->setInvalidDecl();
655 }
656}
657
Chris Lattner3d1cee32008-04-08 05:04:30 +0000658/// CheckCXXDefaultArguments - Verify that the default arguments for a
659/// function declaration are well-formed according to C++
660/// [dcl.fct.default].
661void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
662 unsigned NumParams = FD->getNumParams();
663 unsigned p;
664
665 // Find first parameter with a default argument
666 for (p = 0; p < NumParams; ++p) {
667 ParmVarDecl *Param = FD->getParamDecl(p);
Richard Smith7974c602013-04-17 16:25:20 +0000668 if (Param->hasDefaultArg())
Chris Lattner3d1cee32008-04-08 05:04:30 +0000669 break;
670 }
671
672 // C++ [dcl.fct.default]p4:
673 // In a given function declaration, all parameters
674 // subsequent to a parameter with a default argument shall
675 // have default arguments supplied in this or previous
676 // declarations. A default argument shall not be redefined
677 // by a later declaration (not even to the same value).
678 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000679 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000680 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000681 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000682 if (Param->isInvalidDecl())
683 /* We already complained about this parameter. */;
684 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000685 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000686 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000687 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000688 else
Mike Stump1eb44332009-09-09 15:08:12 +0000689 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000690 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000691
Chris Lattner3d1cee32008-04-08 05:04:30 +0000692 LastMissingDefaultArg = p;
693 }
694 }
695
696 if (LastMissingDefaultArg > 0) {
697 // Some default arguments were missing. Clear out all of the
698 // default arguments up to (and including) the last missing
699 // default argument, so that we leave the function parameters
700 // in a semantically valid state.
701 for (p = 0; p <= LastMissingDefaultArg; ++p) {
702 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000703 if (Param->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000704 Param->setDefaultArg(0);
705 }
706 }
707 }
708}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000709
Richard Smith9f569cc2011-10-01 02:31:28 +0000710// CheckConstexprParameterTypes - Check whether a function's parameter types
711// are all literal types. If so, return true. If not, produce a suitable
Richard Smith86c3ae42012-02-13 03:54:03 +0000712// diagnostic and return false.
713static bool CheckConstexprParameterTypes(Sema &SemaRef,
714 const FunctionDecl *FD) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000715 unsigned ArgIndex = 0;
716 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
717 for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(),
718 e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) {
719 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
720 SourceLocation ParamLoc = PD->getLocation();
721 if (!(*i)->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000722 SemaRef.RequireLiteralType(ParamLoc, *i,
Douglas Gregorf502d8e2012-05-04 16:48:41 +0000723 diag::err_constexpr_non_literal_param,
724 ArgIndex+1, PD->getSourceRange(),
725 isa<CXXConstructorDecl>(FD)))
Richard Smith9f569cc2011-10-01 02:31:28 +0000726 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000727 }
Joao Matos17d35c32012-08-31 22:18:20 +0000728 return true;
729}
730
731/// \brief Get diagnostic %select index for tag kind for
732/// record diagnostic message.
733/// WARNING: Indexes apply to particular diagnostics only!
734///
735/// \returns diagnostic %select index.
Joao Matosf143ae92012-09-01 00:13:24 +0000736static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
Joao Matos17d35c32012-08-31 22:18:20 +0000737 switch (Tag) {
Joao Matosf143ae92012-09-01 00:13:24 +0000738 case TTK_Struct: return 0;
739 case TTK_Interface: return 1;
740 case TTK_Class: return 2;
741 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
Joao Matos17d35c32012-08-31 22:18:20 +0000742 }
Joao Matos17d35c32012-08-31 22:18:20 +0000743}
744
745// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
746// the requirements of a constexpr function definition or a constexpr
747// constructor definition. If so, return true. If not, produce appropriate
Richard Smith86c3ae42012-02-13 03:54:03 +0000748// diagnostics and return false.
Richard Smith9f569cc2011-10-01 02:31:28 +0000749//
Richard Smith86c3ae42012-02-13 03:54:03 +0000750// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
751bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
Richard Smith35340502012-01-13 04:54:00 +0000752 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
753 if (MD && MD->isInstance()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000754 // C++11 [dcl.constexpr]p4:
755 // The definition of a constexpr constructor shall satisfy the following
756 // constraints:
Richard Smith9f569cc2011-10-01 02:31:28 +0000757 // - the class shall not have any virtual base classes;
Joao Matos17d35c32012-08-31 22:18:20 +0000758 const CXXRecordDecl *RD = MD->getParent();
759 if (RD->getNumVBases()) {
760 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
761 << isa<CXXConstructorDecl>(NewFD)
762 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
763 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
764 E = RD->vbases_end(); I != E; ++I)
765 Diag(I->getLocStart(),
Richard Smith86c3ae42012-02-13 03:54:03 +0000766 diag::note_constexpr_virtual_base_here) << I->getSourceRange();
Richard Smith9f569cc2011-10-01 02:31:28 +0000767 return false;
768 }
Richard Smith35340502012-01-13 04:54:00 +0000769 }
770
771 if (!isa<CXXConstructorDecl>(NewFD)) {
772 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +0000773 // The definition of a constexpr function shall satisfy the following
774 // constraints:
775 // - it shall not be virtual;
776 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
777 if (Method && Method->isVirtual()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000778 Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
Richard Smith9f569cc2011-10-01 02:31:28 +0000779
Richard Smith86c3ae42012-02-13 03:54:03 +0000780 // If it's not obvious why this function is virtual, find an overridden
781 // function which uses the 'virtual' keyword.
782 const CXXMethodDecl *WrittenVirtual = Method;
783 while (!WrittenVirtual->isVirtualAsWritten())
784 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
785 if (WrittenVirtual != Method)
786 Diag(WrittenVirtual->getLocation(),
787 diag::note_overridden_virtual_function);
Richard Smith9f569cc2011-10-01 02:31:28 +0000788 return false;
789 }
790
791 // - its return type shall be a literal type;
792 QualType RT = NewFD->getResultType();
793 if (!RT->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000794 RequireLiteralType(NewFD->getLocation(), RT,
Douglas Gregorf502d8e2012-05-04 16:48:41 +0000795 diag::err_constexpr_non_literal_return))
Richard Smith9f569cc2011-10-01 02:31:28 +0000796 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000797 }
798
Richard Smith35340502012-01-13 04:54:00 +0000799 // - each of its parameter types shall be a literal type;
Richard Smith86c3ae42012-02-13 03:54:03 +0000800 if (!CheckConstexprParameterTypes(*this, NewFD))
Richard Smith35340502012-01-13 04:54:00 +0000801 return false;
802
Richard Smith9f569cc2011-10-01 02:31:28 +0000803 return true;
804}
805
806/// Check the given declaration statement is legal within a constexpr function
Richard Smitha10b9782013-04-22 15:31:51 +0000807/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
Richard Smith9f569cc2011-10-01 02:31:28 +0000808///
Richard Smitha10b9782013-04-22 15:31:51 +0000809/// \return true if the body is OK (maybe only as an extension), false if we
810/// have diagnosed a problem.
Richard Smith9f569cc2011-10-01 02:31:28 +0000811static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
Richard Smitha10b9782013-04-22 15:31:51 +0000812 DeclStmt *DS, SourceLocation &Cxx1yLoc) {
813 // C++11 [dcl.constexpr]p3 and p4:
Richard Smith9f569cc2011-10-01 02:31:28 +0000814 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
815 // contain only
816 for (DeclStmt::decl_iterator DclIt = DS->decl_begin(),
817 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
818 switch ((*DclIt)->getKind()) {
819 case Decl::StaticAssert:
820 case Decl::Using:
821 case Decl::UsingShadow:
822 case Decl::UsingDirective:
823 case Decl::UnresolvedUsingTypename:
Richard Smitha10b9782013-04-22 15:31:51 +0000824 case Decl::UnresolvedUsingValue:
Richard Smith9f569cc2011-10-01 02:31:28 +0000825 // - static_assert-declarations
826 // - using-declarations,
827 // - using-directives,
828 continue;
829
830 case Decl::Typedef:
831 case Decl::TypeAlias: {
832 // - typedef declarations and alias-declarations that do not define
833 // classes or enumerations,
834 TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt);
835 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
836 // Don't allow variably-modified types in constexpr functions.
837 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
838 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
839 << TL.getSourceRange() << TL.getType()
840 << isa<CXXConstructorDecl>(Dcl);
841 return false;
842 }
843 continue;
844 }
845
846 case Decl::Enum:
847 case Decl::CXXRecord:
Richard Smitha10b9782013-04-22 15:31:51 +0000848 // C++1y allows types to be defined, not just declared.
849 if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition())
850 SemaRef.Diag(DS->getLocStart(),
851 SemaRef.getLangOpts().CPlusPlus1y
852 ? diag::warn_cxx11_compat_constexpr_type_definition
853 : diag::ext_constexpr_type_definition)
Richard Smith9f569cc2011-10-01 02:31:28 +0000854 << isa<CXXConstructorDecl>(Dcl);
Richard Smith9f569cc2011-10-01 02:31:28 +0000855 continue;
856
Richard Smitha10b9782013-04-22 15:31:51 +0000857 case Decl::EnumConstant:
858 case Decl::IndirectField:
859 case Decl::ParmVar:
860 // These can only appear with other declarations which are banned in
861 // C++11 and permitted in C++1y, so ignore them.
862 continue;
863
864 case Decl::Var: {
865 // C++1y [dcl.constexpr]p3 allows anything except:
866 // a definition of a variable of non-literal type or of static or
867 // thread storage duration or for which no initialization is performed.
868 VarDecl *VD = cast<VarDecl>(*DclIt);
869 if (VD->isThisDeclarationADefinition()) {
870 if (VD->isStaticLocal()) {
871 SemaRef.Diag(VD->getLocation(),
872 diag::err_constexpr_local_var_static)
873 << isa<CXXConstructorDecl>(Dcl)
874 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
875 return false;
876 }
Richard Smithbebf5b12013-04-26 14:36:30 +0000877 if (!VD->getType()->isDependentType() &&
878 SemaRef.RequireLiteralType(
Richard Smitha10b9782013-04-22 15:31:51 +0000879 VD->getLocation(), VD->getType(),
880 diag::err_constexpr_local_var_non_literal_type,
881 isa<CXXConstructorDecl>(Dcl)))
882 return false;
883 if (!VD->hasInit()) {
884 SemaRef.Diag(VD->getLocation(),
885 diag::err_constexpr_local_var_no_init)
886 << isa<CXXConstructorDecl>(Dcl);
887 return false;
888 }
889 }
890 SemaRef.Diag(VD->getLocation(),
891 SemaRef.getLangOpts().CPlusPlus1y
892 ? diag::warn_cxx11_compat_constexpr_local_var
893 : diag::ext_constexpr_local_var)
Richard Smith9f569cc2011-10-01 02:31:28 +0000894 << isa<CXXConstructorDecl>(Dcl);
Richard Smitha10b9782013-04-22 15:31:51 +0000895 continue;
896 }
897
898 case Decl::NamespaceAlias:
899 case Decl::Function:
900 // These are disallowed in C++11 and permitted in C++1y. Allow them
901 // everywhere as an extension.
902 if (!Cxx1yLoc.isValid())
903 Cxx1yLoc = DS->getLocStart();
904 continue;
Richard Smith9f569cc2011-10-01 02:31:28 +0000905
906 default:
907 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
908 << isa<CXXConstructorDecl>(Dcl);
909 return false;
910 }
911 }
912
913 return true;
914}
915
916/// Check that the given field is initialized within a constexpr constructor.
917///
918/// \param Dcl The constexpr constructor being checked.
919/// \param Field The field being checked. This may be a member of an anonymous
920/// struct or union nested within the class being checked.
921/// \param Inits All declarations, including anonymous struct/union members and
922/// indirect members, for which any initialization was provided.
923/// \param Diagnosed Set to true if an error is produced.
924static void CheckConstexprCtorInitializer(Sema &SemaRef,
925 const FunctionDecl *Dcl,
926 FieldDecl *Field,
927 llvm::SmallSet<Decl*, 16> &Inits,
928 bool &Diagnosed) {
Eli Friedman5fb478b2013-06-28 21:07:41 +0000929 if (Field->isInvalidDecl())
930 return;
931
Douglas Gregord61db332011-10-10 17:22:13 +0000932 if (Field->isUnnamedBitfield())
933 return;
Richard Smith30ecfad2012-02-09 06:40:58 +0000934
935 if (Field->isAnonymousStructOrUnion() &&
936 Field->getType()->getAsCXXRecordDecl()->isEmpty())
937 return;
938
Richard Smith9f569cc2011-10-01 02:31:28 +0000939 if (!Inits.count(Field)) {
940 if (!Diagnosed) {
941 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
942 Diagnosed = true;
943 }
944 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
945 } else if (Field->isAnonymousStructOrUnion()) {
946 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
947 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
948 I != E; ++I)
949 // If an anonymous union contains an anonymous struct of which any member
950 // is initialized, all members must be initialized.
David Blaikie581deb32012-06-06 20:45:41 +0000951 if (!RD->isUnion() || Inits.count(*I))
952 CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed);
Richard Smith9f569cc2011-10-01 02:31:28 +0000953 }
954}
955
Richard Smitha10b9782013-04-22 15:31:51 +0000956/// Check the provided statement is allowed in a constexpr function
957/// definition.
958static bool
959CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
Robert Wilhelme7205c02013-08-10 12:33:24 +0000960 SmallVectorImpl<SourceLocation> &ReturnStmts,
Richard Smitha10b9782013-04-22 15:31:51 +0000961 SourceLocation &Cxx1yLoc) {
962 // - its function-body shall be [...] a compound-statement that contains only
963 switch (S->getStmtClass()) {
964 case Stmt::NullStmtClass:
965 // - null statements,
966 return true;
967
968 case Stmt::DeclStmtClass:
969 // - static_assert-declarations
970 // - using-declarations,
971 // - using-directives,
972 // - typedef declarations and alias-declarations that do not define
973 // classes or enumerations,
974 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
975 return false;
976 return true;
977
978 case Stmt::ReturnStmtClass:
979 // - and exactly one return statement;
980 if (isa<CXXConstructorDecl>(Dcl)) {
981 // C++1y allows return statements in constexpr constructors.
982 if (!Cxx1yLoc.isValid())
983 Cxx1yLoc = S->getLocStart();
984 return true;
985 }
986
987 ReturnStmts.push_back(S->getLocStart());
988 return true;
989
990 case Stmt::CompoundStmtClass: {
991 // C++1y allows compound-statements.
992 if (!Cxx1yLoc.isValid())
993 Cxx1yLoc = S->getLocStart();
994
995 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
996 for (CompoundStmt::body_iterator BodyIt = CompStmt->body_begin(),
997 BodyEnd = CompStmt->body_end(); BodyIt != BodyEnd; ++BodyIt) {
998 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, *BodyIt, ReturnStmts,
999 Cxx1yLoc))
1000 return false;
1001 }
1002 return true;
1003 }
1004
1005 case Stmt::AttributedStmtClass:
1006 if (!Cxx1yLoc.isValid())
1007 Cxx1yLoc = S->getLocStart();
1008 return true;
1009
1010 case Stmt::IfStmtClass: {
1011 // C++1y allows if-statements.
1012 if (!Cxx1yLoc.isValid())
1013 Cxx1yLoc = S->getLocStart();
1014
1015 IfStmt *If = cast<IfStmt>(S);
1016 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1017 Cxx1yLoc))
1018 return false;
1019 if (If->getElse() &&
1020 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1021 Cxx1yLoc))
1022 return false;
1023 return true;
1024 }
1025
1026 case Stmt::WhileStmtClass:
1027 case Stmt::DoStmtClass:
1028 case Stmt::ForStmtClass:
1029 case Stmt::CXXForRangeStmtClass:
1030 case Stmt::ContinueStmtClass:
1031 // C++1y allows all of these. We don't allow them as extensions in C++11,
1032 // because they don't make sense without variable mutation.
1033 if (!SemaRef.getLangOpts().CPlusPlus1y)
1034 break;
1035 if (!Cxx1yLoc.isValid())
1036 Cxx1yLoc = S->getLocStart();
1037 for (Stmt::child_range Children = S->children(); Children; ++Children)
1038 if (*Children &&
1039 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1040 Cxx1yLoc))
1041 return false;
1042 return true;
1043
1044 case Stmt::SwitchStmtClass:
1045 case Stmt::CaseStmtClass:
1046 case Stmt::DefaultStmtClass:
1047 case Stmt::BreakStmtClass:
1048 // C++1y allows switch-statements, and since they don't need variable
1049 // mutation, we can reasonably allow them in C++11 as an extension.
1050 if (!Cxx1yLoc.isValid())
1051 Cxx1yLoc = S->getLocStart();
1052 for (Stmt::child_range Children = S->children(); Children; ++Children)
1053 if (*Children &&
1054 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1055 Cxx1yLoc))
1056 return false;
1057 return true;
1058
1059 default:
1060 if (!isa<Expr>(S))
1061 break;
1062
1063 // C++1y allows expression-statements.
1064 if (!Cxx1yLoc.isValid())
1065 Cxx1yLoc = S->getLocStart();
1066 return true;
1067 }
1068
1069 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1070 << isa<CXXConstructorDecl>(Dcl);
1071 return false;
1072}
1073
Richard Smith9f569cc2011-10-01 02:31:28 +00001074/// Check the body for the given constexpr function declaration only contains
1075/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1076///
1077/// \return true if the body is OK, false if we have diagnosed a problem.
Richard Smith86c3ae42012-02-13 03:54:03 +00001078bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001079 if (isa<CXXTryStmt>(Body)) {
Richard Smith5ba73e12012-02-04 00:33:54 +00001080 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +00001081 // The definition of a constexpr function shall satisfy the following
1082 // constraints: [...]
1083 // - its function-body shall be = delete, = default, or a
1084 // compound-statement
1085 //
Richard Smith5ba73e12012-02-04 00:33:54 +00001086 // C++11 [dcl.constexpr]p4:
Richard Smith9f569cc2011-10-01 02:31:28 +00001087 // In the definition of a constexpr constructor, [...]
1088 // - its function-body shall not be a function-try-block;
1089 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1090 << isa<CXXConstructorDecl>(Dcl);
1091 return false;
1092 }
1093
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001094 SmallVector<SourceLocation, 4> ReturnStmts;
Richard Smitha10b9782013-04-22 15:31:51 +00001095
1096 // - its function-body shall be [...] a compound-statement that contains only
1097 // [... list of cases ...]
1098 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1099 SourceLocation Cxx1yLoc;
Richard Smith9f569cc2011-10-01 02:31:28 +00001100 for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(),
1101 BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) {
Richard Smitha10b9782013-04-22 15:31:51 +00001102 if (!CheckConstexprFunctionStmt(*this, Dcl, *BodyIt, ReturnStmts, Cxx1yLoc))
1103 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +00001104 }
1105
Richard Smitha10b9782013-04-22 15:31:51 +00001106 if (Cxx1yLoc.isValid())
1107 Diag(Cxx1yLoc,
1108 getLangOpts().CPlusPlus1y
1109 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1110 : diag::ext_constexpr_body_invalid_stmt)
1111 << isa<CXXConstructorDecl>(Dcl);
1112
Richard Smith9f569cc2011-10-01 02:31:28 +00001113 if (const CXXConstructorDecl *Constructor
1114 = dyn_cast<CXXConstructorDecl>(Dcl)) {
1115 const CXXRecordDecl *RD = Constructor->getParent();
Richard Smith30ecfad2012-02-09 06:40:58 +00001116 // DR1359:
1117 // - every non-variant non-static data member and base class sub-object
1118 // shall be initialized;
1119 // - if the class is a non-empty union, or for each non-empty anonymous
1120 // union member of a non-union class, exactly one non-static data member
1121 // shall be initialized;
Richard Smith9f569cc2011-10-01 02:31:28 +00001122 if (RD->isUnion()) {
Richard Smith30ecfad2012-02-09 06:40:58 +00001123 if (Constructor->getNumCtorInitializers() == 0 && !RD->isEmpty()) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001124 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1125 return false;
1126 }
Richard Smith6e433752011-10-10 16:38:04 +00001127 } else if (!Constructor->isDependentContext() &&
1128 !Constructor->isDelegatingConstructor()) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001129 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1130
1131 // Skip detailed checking if we have enough initializers, and we would
1132 // allow at most one initializer per member.
1133 bool AnyAnonStructUnionMembers = false;
1134 unsigned Fields = 0;
1135 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1136 E = RD->field_end(); I != E; ++I, ++Fields) {
David Blaikie262bc182012-04-30 02:36:29 +00001137 if (I->isAnonymousStructOrUnion()) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001138 AnyAnonStructUnionMembers = true;
1139 break;
1140 }
1141 }
1142 if (AnyAnonStructUnionMembers ||
1143 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1144 // Check initialization of non-static data members. Base classes are
1145 // always initialized so do not need to be checked. Dependent bases
1146 // might not have initializers in the member initializer list.
1147 llvm::SmallSet<Decl*, 16> Inits;
1148 for (CXXConstructorDecl::init_const_iterator
1149 I = Constructor->init_begin(), E = Constructor->init_end();
1150 I != E; ++I) {
1151 if (FieldDecl *FD = (*I)->getMember())
1152 Inits.insert(FD);
1153 else if (IndirectFieldDecl *ID = (*I)->getIndirectMember())
1154 Inits.insert(ID->chain_begin(), ID->chain_end());
1155 }
1156
1157 bool Diagnosed = false;
1158 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1159 E = RD->field_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001160 CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed);
Richard Smith9f569cc2011-10-01 02:31:28 +00001161 if (Diagnosed)
1162 return false;
1163 }
1164 }
Richard Smith9f569cc2011-10-01 02:31:28 +00001165 } else {
1166 if (ReturnStmts.empty()) {
Richard Smitha10b9782013-04-22 15:31:51 +00001167 // C++1y doesn't require constexpr functions to contain a 'return'
1168 // statement. We still do, unless the return type is void, because
1169 // otherwise if there's no return statement, the function cannot
1170 // be used in a core constant expression.
Richard Smithbebf5b12013-04-26 14:36:30 +00001171 bool OK = getLangOpts().CPlusPlus1y && Dcl->getResultType()->isVoidType();
Richard Smitha10b9782013-04-22 15:31:51 +00001172 Diag(Dcl->getLocation(),
Richard Smithbebf5b12013-04-26 14:36:30 +00001173 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
1174 : diag::err_constexpr_body_no_return);
1175 return OK;
Richard Smith9f569cc2011-10-01 02:31:28 +00001176 }
1177 if (ReturnStmts.size() > 1) {
Richard Smitha10b9782013-04-22 15:31:51 +00001178 Diag(ReturnStmts.back(),
1179 getLangOpts().CPlusPlus1y
1180 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
1181 : diag::ext_constexpr_body_multiple_return);
Richard Smith9f569cc2011-10-01 02:31:28 +00001182 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
1183 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
Richard Smith9f569cc2011-10-01 02:31:28 +00001184 }
1185 }
1186
Richard Smith5ba73e12012-02-04 00:33:54 +00001187 // C++11 [dcl.constexpr]p5:
1188 // if no function argument values exist such that the function invocation
1189 // substitution would produce a constant expression, the program is
1190 // ill-formed; no diagnostic required.
1191 // C++11 [dcl.constexpr]p3:
1192 // - every constructor call and implicit conversion used in initializing the
1193 // return value shall be one of those allowed in a constant expression.
1194 // C++11 [dcl.constexpr]p4:
1195 // - every constructor involved in initializing non-static data members and
1196 // base class sub-objects shall be a constexpr constructor.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001197 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith86c3ae42012-02-13 03:54:03 +00001198 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smithafee0ff2012-12-09 05:55:43 +00001199 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
Richard Smith745f5142012-01-27 01:14:48 +00001200 << isa<CXXConstructorDecl>(Dcl);
1201 for (size_t I = 0, N = Diags.size(); I != N; ++I)
1202 Diag(Diags[I].first, Diags[I].second);
Richard Smithafee0ff2012-12-09 05:55:43 +00001203 // Don't return false here: we allow this for compatibility in
1204 // system headers.
Richard Smith745f5142012-01-27 01:14:48 +00001205 }
1206
Richard Smith9f569cc2011-10-01 02:31:28 +00001207 return true;
1208}
1209
Douglas Gregorb48fe382008-10-31 09:07:45 +00001210/// isCurrentClassName - Determine whether the identifier II is the
1211/// name of the class type currently being defined. In the case of
1212/// nested classes, this will only return true if II is the name of
1213/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00001214bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1215 const CXXScopeSpec *SS) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001216 assert(getLangOpts().CPlusPlus && "No class names in C!");
Douglas Gregorb862b8f2010-01-11 23:29:10 +00001217
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001218 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +00001219 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +00001220 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001221 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1222 } else
1223 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1224
Douglas Gregor6f7a17b2010-02-05 06:12:42 +00001225 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregorb48fe382008-10-31 09:07:45 +00001226 return &II == CurDecl->getIdentifier();
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00001227 return false;
Douglas Gregorb48fe382008-10-31 09:07:45 +00001228}
1229
Richard Smithb79b17b2013-10-15 00:00:26 +00001230/// \brief Determine whether the identifier II is a typo for the name of
1231/// the class type currently being defined. If so, update it to the identifier
1232/// that should have been used.
1233bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
1234 assert(getLangOpts().CPlusPlus && "No class names in C!");
1235
1236 if (!getLangOpts().SpellChecking)
1237 return false;
1238
1239 CXXRecordDecl *CurDecl;
1240 if (SS && SS->isSet() && !SS->isInvalid()) {
1241 DeclContext *DC = computeDeclContext(*SS, true);
1242 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1243 } else
1244 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1245
1246 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
1247 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
1248 < II->getLength()) {
1249 II = CurDecl->getIdentifier();
1250 return true;
1251 }
1252
1253 return false;
1254}
1255
Douglas Gregor229d47a2012-11-10 07:24:09 +00001256/// \brief Determine whether the given class is a base class of the given
1257/// class, including looking at dependent bases.
1258static bool findCircularInheritance(const CXXRecordDecl *Class,
1259 const CXXRecordDecl *Current) {
1260 SmallVector<const CXXRecordDecl*, 8> Queue;
1261
1262 Class = Class->getCanonicalDecl();
1263 while (true) {
1264 for (CXXRecordDecl::base_class_const_iterator I = Current->bases_begin(),
1265 E = Current->bases_end();
1266 I != E; ++I) {
1267 CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
1268 if (!Base)
1269 continue;
1270
1271 Base = Base->getDefinition();
1272 if (!Base)
1273 continue;
1274
1275 if (Base->getCanonicalDecl() == Class)
1276 return true;
1277
1278 Queue.push_back(Base);
1279 }
1280
1281 if (Queue.empty())
1282 return false;
1283
Robert Wilhelm344472e2013-08-23 16:11:15 +00001284 Current = Queue.pop_back_val();
Douglas Gregor229d47a2012-11-10 07:24:09 +00001285 }
1286
1287 return false;
Douglas Gregord777e282012-11-10 01:18:17 +00001288}
1289
Mike Stump1eb44332009-09-09 15:08:12 +00001290/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001291///
1292/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1293/// and returns NULL otherwise.
1294CXXBaseSpecifier *
1295Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1296 SourceRange SpecifierRange,
1297 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001298 TypeSourceInfo *TInfo,
1299 SourceLocation EllipsisLoc) {
Nick Lewycky56062202010-07-26 16:56:01 +00001300 QualType BaseType = TInfo->getType();
1301
Douglas Gregor2943aed2009-03-03 04:44:36 +00001302 // C++ [class.union]p1:
1303 // A union shall not have base classes.
1304 if (Class->isUnion()) {
1305 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1306 << SpecifierRange;
1307 return 0;
1308 }
1309
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001310 if (EllipsisLoc.isValid() &&
1311 !TInfo->getType()->containsUnexpandedParameterPack()) {
1312 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1313 << TInfo->getTypeLoc().getSourceRange();
1314 EllipsisLoc = SourceLocation();
1315 }
Douglas Gregord777e282012-11-10 01:18:17 +00001316
1317 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1318
1319 if (BaseType->isDependentType()) {
1320 // Make sure that we don't have circular inheritance among our dependent
1321 // bases. For non-dependent bases, the check for completeness below handles
1322 // this.
1323 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1324 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1325 ((BaseDecl = BaseDecl->getDefinition()) &&
Douglas Gregor229d47a2012-11-10 07:24:09 +00001326 findCircularInheritance(Class, BaseDecl))) {
Douglas Gregord777e282012-11-10 01:18:17 +00001327 Diag(BaseLoc, diag::err_circular_inheritance)
1328 << BaseType << Context.getTypeDeclType(Class);
1329
1330 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1331 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1332 << BaseType;
1333
1334 return 0;
1335 }
1336 }
1337
Mike Stump1eb44332009-09-09 15:08:12 +00001338 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001339 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001340 Access, TInfo, EllipsisLoc);
Douglas Gregord777e282012-11-10 01:18:17 +00001341 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001342
1343 // Base specifiers must be record types.
1344 if (!BaseType->isRecordType()) {
1345 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1346 return 0;
1347 }
1348
1349 // C++ [class.union]p1:
1350 // A union shall not be used as a base class.
1351 if (BaseType->isUnionType()) {
1352 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1353 return 0;
1354 }
1355
1356 // C++ [class.derived]p2:
1357 // The class-name in a base-specifier shall not be an incompletely
1358 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +00001359 if (RequireCompleteType(BaseLoc, BaseType,
Douglas Gregord10099e2012-05-04 16:32:21 +00001360 diag::err_incomplete_base_class, SpecifierRange)) {
John McCall572fc622010-08-17 07:23:57 +00001361 Class->setInvalidDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001362 return 0;
John McCall572fc622010-08-17 07:23:57 +00001363 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001364
Eli Friedman1d954f62009-08-15 21:55:26 +00001365 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +00001366 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001367 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor952b0172010-02-11 01:04:33 +00001368 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001369 assert(BaseDecl && "Base type is not incomplete, but has no definition");
David Majnemer2f686692013-06-22 06:43:58 +00001370 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
Eli Friedman1d954f62009-08-15 21:55:26 +00001371 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +00001372
Anders Carlsson1d209272011-03-25 14:55:14 +00001373 // C++ [class]p3:
1374 // If a class is marked final and it appears as a base-type-specifier in
1375 // base-clause, the program is ill-formed.
David Majnemer7121bdb2013-10-18 00:33:31 +00001376 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
Anders Carlssondfc2f102011-01-22 17:51:53 +00001377 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
David Majnemer7121bdb2013-10-18 00:33:31 +00001378 << CXXBaseDecl->getDeclName()
1379 << FA->isSpelledAsSealed();
Anders Carlssondfc2f102011-01-22 17:51:53 +00001380 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1381 << CXXBaseDecl->getDeclName();
1382 return 0;
1383 }
1384
John McCall572fc622010-08-17 07:23:57 +00001385 if (BaseDecl->isInvalidDecl())
1386 Class->setInvalidDecl();
Anders Carlsson51f94042009-12-03 17:49:57 +00001387
1388 // Create the base specifier.
Anders Carlsson51f94042009-12-03 17:49:57 +00001389 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001390 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001391 Access, TInfo, EllipsisLoc);
Anders Carlsson51f94042009-12-03 17:49:57 +00001392}
1393
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001394/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1395/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +00001396/// example:
1397/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001398/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallf312b1e2010-08-26 23:41:50 +00001399BaseResult
John McCalld226f652010-08-21 09:40:31 +00001400Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Richard Smith05321402013-02-19 23:47:15 +00001401 ParsedAttributes &Attributes,
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001402 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001403 ParsedType basetype, SourceLocation BaseLoc,
1404 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001405 if (!classdecl)
1406 return true;
1407
Douglas Gregor40808ce2009-03-09 23:48:35 +00001408 AdjustDeclIfTemplate(classdecl);
John McCalld226f652010-08-21 09:40:31 +00001409 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregor5fe8c042010-02-27 00:25:28 +00001410 if (!Class)
1411 return true;
1412
Richard Smith05321402013-02-19 23:47:15 +00001413 // We do not support any C++11 attributes on base-specifiers yet.
1414 // Diagnose any attributes we see.
1415 if (!Attributes.empty()) {
1416 for (AttributeList *Attr = Attributes.getList(); Attr;
1417 Attr = Attr->getNext()) {
1418 if (Attr->isInvalid() ||
1419 Attr->getKind() == AttributeList::IgnoredAttribute)
1420 continue;
1421 Diag(Attr->getLoc(),
1422 Attr->getKind() == AttributeList::UnknownAttribute
1423 ? diag::warn_unknown_attribute_ignored
1424 : diag::err_base_specifier_attribute)
1425 << Attr->getName();
1426 }
1427 }
1428
Nick Lewycky56062202010-07-26 16:56:01 +00001429 TypeSourceInfo *TInfo = 0;
1430 GetTypeFromParser(basetype, &TInfo);
Douglas Gregord0937222010-12-13 22:49:22 +00001431
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001432 if (EllipsisLoc.isInvalid() &&
1433 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregord0937222010-12-13 22:49:22 +00001434 UPPC_BaseType))
1435 return true;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001436
Douglas Gregor2943aed2009-03-03 04:44:36 +00001437 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001438 Virtual, Access, TInfo,
1439 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +00001440 return BaseSpec;
Douglas Gregor8a50fe02012-07-02 21:00:41 +00001441 else
1442 Class->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001443
Douglas Gregor2943aed2009-03-03 04:44:36 +00001444 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001445}
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001446
Douglas Gregor2943aed2009-03-03 04:44:36 +00001447/// \brief Performs the actual work of attaching the given base class
1448/// specifiers to a C++ class.
1449bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1450 unsigned NumBases) {
1451 if (NumBases == 0)
1452 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001453
1454 // Used to keep track of which base types we have already seen, so
1455 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +00001456 // that the key is always the unqualified canonical type of the base
1457 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001458 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1459
1460 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +00001461 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +00001462 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +00001463 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001464 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +00001465 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +00001466 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Benjamin Kramer52c16682012-03-05 17:20:04 +00001467
1468 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1469 if (KnownBase) {
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001470 // C++ [class.mi]p3:
1471 // A class shall not be specified as a direct base class of a
1472 // derived class more than once.
Daniel Dunbar96a00142012-03-09 18:35:03 +00001473 Diag(Bases[idx]->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001474 diag::err_duplicate_base_class)
Benjamin Kramer52c16682012-03-05 17:20:04 +00001475 << KnownBase->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +00001476 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +00001477
1478 // Delete the duplicate base class specifier; we're going to
1479 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001480 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001481
1482 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001483 } else {
1484 // Okay, add this new base class.
Benjamin Kramer52c16682012-03-05 17:20:04 +00001485 KnownBase = Bases[idx];
Douglas Gregor2943aed2009-03-03 04:44:36 +00001486 Bases[NumGoodBases++] = Bases[idx];
John McCalle402e722012-09-25 07:32:39 +00001487 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1488 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1489 if (Class->isInterface() &&
1490 (!RD->isInterface() ||
1491 KnownBase->getAccessSpecifier() != AS_public)) {
1492 // The Microsoft extension __interface does not permit bases that
1493 // are not themselves public interfaces.
1494 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1495 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1496 << RD->getSourceRange();
1497 Invalid = true;
1498 }
1499 if (RD->hasAttr<WeakAttr>())
1500 Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context));
1501 }
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001502 }
1503 }
1504
1505 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +00001506 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +00001507
1508 // Delete the remaining (good) base class specifiers, since their
1509 // data has been copied into the CXXRecordDecl.
1510 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001511 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001512
1513 return Invalid;
1514}
1515
1516/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1517/// class, after checking whether there are any duplicate base
1518/// classes.
Richard Trieu90ab75b2011-09-09 03:18:59 +00001519void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001520 unsigned NumBases) {
1521 if (!ClassDecl || !Bases || !NumBases)
1522 return;
1523
1524 AdjustDeclIfTemplate(ClassDecl);
Robert Wilhelm0d317a02013-07-22 05:04:01 +00001525 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases, NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001526}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001527
Douglas Gregora8f32e02009-10-06 17:59:45 +00001528/// \brief Determine whether the type \p Derived is a C++ class that is
1529/// derived from the type \p Base.
1530bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001531 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001532 return false;
John McCall3cb0ebd2010-03-10 03:28:59 +00001533
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001534 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001535 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001536 return false;
1537
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001538 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001539 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001540 return false;
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001541
1542 // If either the base or the derived type is invalid, don't try to
1543 // check whether one is derived from the other.
1544 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
1545 return false;
1546
John McCall86ff3082010-02-04 22:26:26 +00001547 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1548 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001549}
1550
1551/// \brief Determine whether the type \p Derived is a C++ class that is
1552/// derived from the type \p Base.
1553bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001554 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001555 return false;
1556
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001557 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001558 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001559 return false;
1560
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001561 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001562 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001563 return false;
1564
Douglas Gregora8f32e02009-10-06 17:59:45 +00001565 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1566}
1567
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001568void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallf871d0c2010-08-07 06:22:56 +00001569 CXXCastPath &BasePathArray) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001570 assert(BasePathArray.empty() && "Base path array must be empty!");
1571 assert(Paths.isRecordingPaths() && "Must record paths!");
1572
1573 const CXXBasePath &Path = Paths.front();
1574
1575 // We first go backward and check if we have a virtual base.
1576 // FIXME: It would be better if CXXBasePath had the base specifier for
1577 // the nearest virtual base.
1578 unsigned Start = 0;
1579 for (unsigned I = Path.size(); I != 0; --I) {
1580 if (Path[I - 1].Base->isVirtual()) {
1581 Start = I - 1;
1582 break;
1583 }
1584 }
1585
1586 // Now add all bases.
1587 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallf871d0c2010-08-07 06:22:56 +00001588 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001589}
1590
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001591/// \brief Determine whether the given base path includes a virtual
1592/// base class.
John McCallf871d0c2010-08-07 06:22:56 +00001593bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1594 for (CXXCastPath::const_iterator B = BasePath.begin(),
1595 BEnd = BasePath.end();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001596 B != BEnd; ++B)
1597 if ((*B)->isVirtual())
1598 return true;
1599
1600 return false;
1601}
1602
Douglas Gregora8f32e02009-10-06 17:59:45 +00001603/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1604/// conversion (where Derived and Base are class types) is
1605/// well-formed, meaning that the conversion is unambiguous (and
1606/// that all of the base classes are accessible). Returns true
1607/// and emits a diagnostic if the code is ill-formed, returns false
1608/// otherwise. Loc is the location where this routine should point to
1609/// if there is an error, and Range is the source range to highlight
1610/// if there is an error.
1611bool
1612Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall58e6f342010-03-16 05:22:47 +00001613 unsigned InaccessibleBaseID,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001614 unsigned AmbigiousBaseConvID,
1615 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001616 DeclarationName Name,
John McCallf871d0c2010-08-07 06:22:56 +00001617 CXXCastPath *BasePath) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001618 // First, determine whether the path from Derived to Base is
1619 // ambiguous. This is slightly more expensive than checking whether
1620 // the Derived to Base conversion exists, because here we need to
1621 // explore multiple paths to determine if there is an ambiguity.
1622 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1623 /*DetectVirtual=*/false);
1624 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1625 assert(DerivationOkay &&
1626 "Can only be used with a derived-to-base conversion");
1627 (void)DerivationOkay;
1628
1629 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001630 if (InaccessibleBaseID) {
1631 // Check that the base class can be accessed.
1632 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1633 InaccessibleBaseID)) {
1634 case AR_inaccessible:
1635 return true;
1636 case AR_accessible:
1637 case AR_dependent:
1638 case AR_delayed:
1639 break;
Anders Carlssone25a96c2010-04-24 17:11:09 +00001640 }
John McCall6b2accb2010-02-10 09:31:12 +00001641 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001642
1643 // Build a base path if necessary.
1644 if (BasePath)
1645 BuildBasePathArray(Paths, *BasePath);
1646 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001647 }
1648
David Majnemer2f686692013-06-22 06:43:58 +00001649 if (AmbigiousBaseConvID) {
1650 // We know that the derived-to-base conversion is ambiguous, and
1651 // we're going to produce a diagnostic. Perform the derived-to-base
1652 // search just one more time to compute all of the possible paths so
1653 // that we can print them out. This is more expensive than any of
1654 // the previous derived-to-base checks we've done, but at this point
1655 // performance isn't as much of an issue.
1656 Paths.clear();
1657 Paths.setRecordingPaths(true);
1658 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1659 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1660 (void)StillOkay;
1661
1662 // Build up a textual representation of the ambiguous paths, e.g.,
1663 // D -> B -> A, that will be used to illustrate the ambiguous
1664 // conversions in the diagnostic. We only print one of the paths
1665 // to each base class subobject.
1666 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1667
1668 Diag(Loc, AmbigiousBaseConvID)
1669 << Derived << Base << PathDisplayStr << Range << Name;
1670 }
Douglas Gregora8f32e02009-10-06 17:59:45 +00001671 return true;
1672}
1673
1674bool
1675Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001676 SourceLocation Loc, SourceRange Range,
John McCallf871d0c2010-08-07 06:22:56 +00001677 CXXCastPath *BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001678 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001679 return CheckDerivedToBaseConversion(Derived, Base,
John McCall58e6f342010-03-16 05:22:47 +00001680 IgnoreAccess ? 0
1681 : diag::err_upcast_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001682 diag::err_ambiguous_derived_to_base_conv,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001683 Loc, Range, DeclarationName(),
1684 BasePath);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001685}
1686
1687
1688/// @brief Builds a string representing ambiguous paths from a
1689/// specific derived class to different subobjects of the same base
1690/// class.
1691///
1692/// This function builds a string that can be used in error messages
1693/// to show the different paths that one can take through the
1694/// inheritance hierarchy to go from the derived class to different
1695/// subobjects of a base class. The result looks something like this:
1696/// @code
1697/// struct D -> struct B -> struct A
1698/// struct D -> struct C -> struct A
1699/// @endcode
1700std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1701 std::string PathDisplayStr;
1702 std::set<unsigned> DisplayedPaths;
1703 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1704 Path != Paths.end(); ++Path) {
1705 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1706 // We haven't displayed a path to this particular base
1707 // class subobject yet.
1708 PathDisplayStr += "\n ";
1709 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1710 for (CXXBasePath::const_iterator Element = Path->begin();
1711 Element != Path->end(); ++Element)
1712 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1713 }
1714 }
1715
1716 return PathDisplayStr;
1717}
1718
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001719//===----------------------------------------------------------------------===//
1720// C++ class member Handling
1721//===----------------------------------------------------------------------===//
1722
Abramo Bagnara6206d532010-06-05 05:09:32 +00001723/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001724bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1725 SourceLocation ASLoc,
1726 SourceLocation ColonLoc,
1727 AttributeList *Attrs) {
Abramo Bagnara6206d532010-06-05 05:09:32 +00001728 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCalld226f652010-08-21 09:40:31 +00001729 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnara6206d532010-06-05 05:09:32 +00001730 ASLoc, ColonLoc);
1731 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001732 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnara6206d532010-06-05 05:09:32 +00001733}
1734
Richard Smitha4b39652012-08-06 03:25:17 +00001735/// CheckOverrideControl - Check C++11 override control semantics.
Eli Friedmandae92712013-09-05 23:51:03 +00001736void Sema::CheckOverrideControl(NamedDecl *D) {
Richard Smithcddbc1d2012-09-06 18:32:18 +00001737 if (D->isInvalidDecl())
1738 return;
1739
Eli Friedmandae92712013-09-05 23:51:03 +00001740 // We only care about "override" and "final" declarations.
1741 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
1742 return;
Anders Carlsson9e682d92011-01-20 05:57:14 +00001743
Eli Friedmandae92712013-09-05 23:51:03 +00001744 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlsson3ffe1832011-01-20 06:33:26 +00001745
Eli Friedmandae92712013-09-05 23:51:03 +00001746 // We can't check dependent instance methods.
1747 if (MD && MD->isInstance() &&
1748 (MD->getParent()->hasAnyDependentBases() ||
1749 MD->getType()->isDependentType()))
1750 return;
1751
1752 if (MD && !MD->isVirtual()) {
1753 // If we have a non-virtual method, check if if hides a virtual method.
1754 // (In that case, it's most likely the method has the wrong type.)
1755 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
1756 FindHiddenVirtualMethods(MD, OverloadedMethods);
1757
1758 if (!OverloadedMethods.empty()) {
Richard Smitha4b39652012-08-06 03:25:17 +00001759 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1760 Diag(OA->getLocation(),
Eli Friedmandae92712013-09-05 23:51:03 +00001761 diag::override_keyword_hides_virtual_member_function)
1762 << "override" << (OverloadedMethods.size() > 1);
1763 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
Richard Smitha4b39652012-08-06 03:25:17 +00001764 Diag(FA->getLocation(),
Eli Friedmandae92712013-09-05 23:51:03 +00001765 diag::override_keyword_hides_virtual_member_function)
David Majnemer7121bdb2013-10-18 00:33:31 +00001766 << (FA->isSpelledAsSealed() ? "sealed" : "final")
1767 << (OverloadedMethods.size() > 1);
Richard Smitha4b39652012-08-06 03:25:17 +00001768 }
Eli Friedmandae92712013-09-05 23:51:03 +00001769 NoteHiddenVirtualMethods(MD, OverloadedMethods);
1770 MD->setInvalidDecl();
1771 return;
1772 }
1773 // Fall through into the general case diagnostic.
1774 // FIXME: We might want to attempt typo correction here.
1775 }
1776
1777 if (!MD || !MD->isVirtual()) {
1778 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1779 Diag(OA->getLocation(),
1780 diag::override_keyword_only_allowed_on_virtual_member_functions)
1781 << "override" << FixItHint::CreateRemoval(OA->getLocation());
1782 D->dropAttr<OverrideAttr>();
1783 }
1784 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1785 Diag(FA->getLocation(),
1786 diag::override_keyword_only_allowed_on_virtual_member_functions)
David Majnemer7121bdb2013-10-18 00:33:31 +00001787 << (FA->isSpelledAsSealed() ? "sealed" : "final")
1788 << FixItHint::CreateRemoval(FA->getLocation());
Eli Friedmandae92712013-09-05 23:51:03 +00001789 D->dropAttr<FinalAttr>();
Richard Smitha4b39652012-08-06 03:25:17 +00001790 }
Anders Carlsson9e682d92011-01-20 05:57:14 +00001791 return;
1792 }
Richard Smitha4b39652012-08-06 03:25:17 +00001793
Richard Smitha4b39652012-08-06 03:25:17 +00001794 // C++11 [class.virtual]p5:
1795 // If a virtual function is marked with the virt-specifier override and
1796 // does not override a member function of a base class, the program is
1797 // ill-formed.
1798 bool HasOverriddenMethods =
1799 MD->begin_overridden_methods() != MD->end_overridden_methods();
1800 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1801 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1802 << MD->getDeclName();
Anders Carlsson9e682d92011-01-20 05:57:14 +00001803}
1804
Richard Smitha4b39652012-08-06 03:25:17 +00001805/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001806/// function overrides a virtual member function marked 'final', according to
Richard Smitha4b39652012-08-06 03:25:17 +00001807/// C++11 [class.virtual]p4.
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001808bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1809 const CXXMethodDecl *Old) {
David Majnemer7121bdb2013-10-18 00:33:31 +00001810 FinalAttr *FA = Old->getAttr<FinalAttr>();
1811 if (!FA)
Anders Carlssonf89e0422011-01-23 21:07:30 +00001812 return false;
1813
1814 Diag(New->getLocation(), diag::err_final_function_overridden)
David Majnemer7121bdb2013-10-18 00:33:31 +00001815 << New->getDeclName()
1816 << FA->isSpelledAsSealed();
Anders Carlssonf89e0422011-01-23 21:07:30 +00001817 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1818 return true;
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001819}
1820
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001821static bool InitializationHasSideEffects(const FieldDecl &FD) {
Richard Smith0b8220a2012-08-07 21:30:42 +00001822 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1823 // FIXME: Destruction of ObjC lifetime types has side-effects.
1824 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1825 return !RD->isCompleteDefinition() ||
1826 !RD->hasTrivialDefaultConstructor() ||
1827 !RD->hasTrivialDestructor();
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001828 return false;
1829}
1830
John McCall76da55d2013-04-16 07:28:30 +00001831static AttributeList *getMSPropertyAttr(AttributeList *list) {
1832 for (AttributeList* it = list; it != 0; it = it->getNext())
1833 if (it->isDeclspecPropertyAttribute())
1834 return it;
1835 return 0;
1836}
1837
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001838/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1839/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith7a614d82011-06-11 17:19:42 +00001840/// bitfield width if there is one, 'InitExpr' specifies the initializer if
Richard Smithca523302012-06-10 03:12:00 +00001841/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1842/// present (but parsing it has been deferred).
Rafael Espindolafc35cbc2013-01-08 20:44:06 +00001843NamedDecl *
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001844Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +00001845 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001846 Expr *BW, const VirtSpecifiers &VS,
Richard Smithca523302012-06-10 03:12:00 +00001847 InClassInitStyle InitStyle) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001848 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00001849 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1850 DeclarationName Name = NameInfo.getName();
1851 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001852
1853 // For anonymous bitfields, the location should point to the type.
1854 if (Loc.isInvalid())
Daniel Dunbar96a00142012-03-09 18:35:03 +00001855 Loc = D.getLocStart();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001856
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001857 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001858
John McCall4bde1e12010-06-04 08:34:12 +00001859 assert(isa<CXXRecordDecl>(CurContext));
John McCall67d1a672009-08-06 02:15:43 +00001860 assert(!DS.isFriendSpecified());
1861
Richard Smith1ab0d902011-06-25 02:28:38 +00001862 bool isFunc = D.isDeclarationOfFunction();
John McCall4bde1e12010-06-04 08:34:12 +00001863
John McCalle402e722012-09-25 07:32:39 +00001864 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
1865 // The Microsoft extension __interface only permits public member functions
1866 // and prohibits constructors, destructors, operators, non-public member
1867 // functions, static methods and data members.
1868 unsigned InvalidDecl;
1869 bool ShowDeclName = true;
1870 if (!isFunc)
1871 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
1872 else if (AS != AS_public)
1873 InvalidDecl = 2;
1874 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
1875 InvalidDecl = 3;
1876 else switch (Name.getNameKind()) {
1877 case DeclarationName::CXXConstructorName:
1878 InvalidDecl = 4;
1879 ShowDeclName = false;
1880 break;
1881
1882 case DeclarationName::CXXDestructorName:
1883 InvalidDecl = 5;
1884 ShowDeclName = false;
1885 break;
1886
1887 case DeclarationName::CXXOperatorName:
1888 case DeclarationName::CXXConversionFunctionName:
1889 InvalidDecl = 6;
1890 break;
1891
1892 default:
1893 InvalidDecl = 0;
1894 break;
1895 }
1896
1897 if (InvalidDecl) {
1898 if (ShowDeclName)
1899 Diag(Loc, diag::err_invalid_member_in_interface)
1900 << (InvalidDecl-1) << Name;
1901 else
1902 Diag(Loc, diag::err_invalid_member_in_interface)
1903 << (InvalidDecl-1) << "";
1904 return 0;
1905 }
1906 }
1907
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001908 // C++ 9.2p6: A member shall not be declared to have automatic storage
1909 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001910 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1911 // data members and cannot be applied to names declared const or static,
1912 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001913 switch (DS.getStorageClassSpec()) {
Richard Smithec642442013-04-12 22:46:28 +00001914 case DeclSpec::SCS_unspecified:
1915 case DeclSpec::SCS_typedef:
1916 case DeclSpec::SCS_static:
1917 break;
1918 case DeclSpec::SCS_mutable:
1919 if (isFunc) {
1920 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +00001921
Richard Smithec642442013-04-12 22:46:28 +00001922 // FIXME: It would be nicer if the keyword was ignored only for this
1923 // declarator. Otherwise we could get follow-up errors.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001924 D.getMutableDeclSpec().ClearStorageClassSpecs();
Richard Smithec642442013-04-12 22:46:28 +00001925 }
1926 break;
1927 default:
1928 Diag(DS.getStorageClassSpecLoc(),
1929 diag::err_storageclass_invalid_for_member);
1930 D.getMutableDeclSpec().ClearStorageClassSpecs();
1931 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001932 }
1933
Sebastian Redl669d5d72008-11-14 23:42:31 +00001934 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1935 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +00001936 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001937
David Blaikie1d87fba2013-01-30 01:22:18 +00001938 if (DS.isConstexprSpecified() && isInstField) {
1939 SemaDiagnosticBuilder B =
1940 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
1941 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
1942 if (InitStyle == ICIS_NoInit) {
1943 B << 0 << 0 << FixItHint::CreateReplacement(ConstexprLoc, "const");
1944 D.getMutableDeclSpec().ClearConstexprSpec();
1945 const char *PrevSpec;
1946 unsigned DiagID;
1947 bool Failed = D.getMutableDeclSpec().SetTypeQual(DeclSpec::TQ_const, ConstexprLoc,
1948 PrevSpec, DiagID, getLangOpts());
Matt Beaumont-Gay3e55e3e2013-01-31 00:08:03 +00001949 (void)Failed;
David Blaikie1d87fba2013-01-30 01:22:18 +00001950 assert(!Failed && "Making a constexpr member const shouldn't fail");
1951 } else {
1952 B << 1;
1953 const char *PrevSpec;
1954 unsigned DiagID;
David Blaikie1d87fba2013-01-30 01:22:18 +00001955 if (D.getMutableDeclSpec().SetStorageClassSpec(
1956 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID)) {
Matt Beaumont-Gay3e55e3e2013-01-31 00:08:03 +00001957 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
David Blaikie1d87fba2013-01-30 01:22:18 +00001958 "This is the only DeclSpec that should fail to be applied");
1959 B << 1;
1960 } else {
1961 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
1962 isInstField = false;
1963 }
1964 }
1965 }
1966
Rafael Espindolafc35cbc2013-01-08 20:44:06 +00001967 NamedDecl *Member;
Chris Lattner24793662009-03-05 22:45:59 +00001968 if (isInstField) {
Douglas Gregor922fff22010-10-13 22:19:53 +00001969 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorb5a01872011-10-09 18:55:59 +00001970
1971 // Data members must have identifiers for names.
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001972 if (!Name.isIdentifier()) {
Douglas Gregorb5a01872011-10-09 18:55:59 +00001973 Diag(Loc, diag::err_bad_variable_name)
1974 << Name;
1975 return 0;
1976 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001977
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001978 IdentifierInfo *II = Name.getAsIdentifierInfo();
1979
Douglas Gregorf2503652011-09-21 14:40:46 +00001980 // Member field could not be with "template" keyword.
1981 // So TemplateParameterLists should be empty in this case.
1982 if (TemplateParameterLists.size()) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001983 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
Douglas Gregorf2503652011-09-21 14:40:46 +00001984 if (TemplateParams->size()) {
1985 // There is no such thing as a member field template.
1986 Diag(D.getIdentifierLoc(), diag::err_template_member)
1987 << II
1988 << SourceRange(TemplateParams->getTemplateLoc(),
1989 TemplateParams->getRAngleLoc());
1990 } else {
1991 // There is an extraneous 'template<>' for this member.
1992 Diag(TemplateParams->getTemplateLoc(),
1993 diag::err_template_member_noparams)
1994 << II
1995 << SourceRange(TemplateParams->getTemplateLoc(),
1996 TemplateParams->getRAngleLoc());
1997 }
1998 return 0;
1999 }
2000
Douglas Gregor922fff22010-10-13 22:19:53 +00002001 if (SS.isSet() && !SS.isInvalid()) {
2002 // The user provided a superfluous scope specifier inside a class
2003 // definition:
2004 //
2005 // class X {
2006 // int X::member;
2007 // };
Douglas Gregor69605872012-03-28 16:01:27 +00002008 if (DeclContext *DC = computeDeclContext(SS, false))
2009 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
Douglas Gregor922fff22010-10-13 22:19:53 +00002010 else
2011 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
2012 << Name << SS.getRange();
Douglas Gregor5d8419c2011-11-01 22:13:30 +00002013
Douglas Gregor922fff22010-10-13 22:19:53 +00002014 SS.clear();
2015 }
Douglas Gregorf2503652011-09-21 14:40:46 +00002016
John McCall76da55d2013-04-16 07:28:30 +00002017 AttributeList *MSPropertyAttr =
2018 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
Eli Friedmanb26f0122013-06-28 20:48:34 +00002019 if (MSPropertyAttr) {
2020 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2021 BitWidth, InitStyle, AS, MSPropertyAttr);
2022 if (!Member)
2023 return 0;
2024 isInstField = false;
2025 } else {
2026 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2027 BitWidth, InitStyle, AS);
2028 assert(Member && "HandleField never returns null");
2029 }
2030 } else {
2031 assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static);
2032
2033 Member = HandleDeclarator(S, D, TemplateParameterLists);
2034 if (!Member)
2035 return 0;
2036
2037 // Non-instance-fields can't have a bitfield.
2038 if (BitWidth) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00002039 if (Member->isInvalidDecl()) {
2040 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00002041 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00002042 // C++ 9.6p3: A bit-field shall not be a static member.
2043 // "static member 'A' cannot be a bit-field"
2044 Diag(Loc, diag::err_static_not_bitfield)
2045 << Name << BitWidth->getSourceRange();
2046 } else if (isa<TypedefDecl>(Member)) {
2047 // "typedef member 'x' cannot be a bit-field"
2048 Diag(Loc, diag::err_typedef_not_bitfield)
2049 << Name << BitWidth->getSourceRange();
2050 } else {
2051 // A function typedef ("typedef int f(); f a;").
2052 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
2053 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +00002054 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +00002055 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +00002056 }
Mike Stump1eb44332009-09-09 15:08:12 +00002057
Chris Lattner8b963ef2009-03-05 23:01:03 +00002058 BitWidth = 0;
2059 Member->setInvalidDecl();
2060 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +00002061
2062 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +00002063
Larisse Voufoef4579c2013-08-06 01:03:05 +00002064 // If we have declared a member function template or static data member
2065 // template, set the access of the templated declaration as well.
Douglas Gregor37b372b2009-08-20 22:52:58 +00002066 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
2067 FunTmpl->getTemplatedDecl()->setAccess(AS);
Larisse Voufoef4579c2013-08-06 01:03:05 +00002068 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
2069 VarTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +00002070 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002071
Richard Smitha4b39652012-08-06 03:25:17 +00002072 if (VS.isOverrideSpecified())
2073 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
2074 if (VS.isFinalSpecified())
David Majnemer7121bdb2013-10-18 00:33:31 +00002075 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
2076 VS.isFinalSpelledSealed()));
Anders Carlsson9e682d92011-01-20 05:57:14 +00002077
Douglas Gregorf5251602011-03-08 17:10:18 +00002078 if (VS.getLastLocation().isValid()) {
2079 // Update the end location of a method that has a virt-specifiers.
2080 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
2081 MD->setRangeEnd(VS.getLastLocation());
2082 }
Richard Smitha4b39652012-08-06 03:25:17 +00002083
Anders Carlsson4ebf1602011-01-20 06:29:02 +00002084 CheckOverrideControl(Member);
Anders Carlsson9e682d92011-01-20 05:57:14 +00002085
Douglas Gregor10bd3682008-11-17 22:58:34 +00002086 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002087
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002088 if (isInstField) {
2089 FieldDecl *FD = cast<FieldDecl>(Member);
2090 FieldCollector->Add(FD);
2091
2092 if (Diags.getDiagnosticLevel(diag::warn_unused_private_field,
2093 FD->getLocation())
2094 != DiagnosticsEngine::Ignored) {
2095 // Remember all explicit private FieldDecls that have a name, no side
2096 // effects and are not part of a dependent type declaration.
2097 if (!FD->isImplicit() && FD->getDeclName() &&
2098 FD->getAccess() == AS_private &&
Daniel Jasper568eae42012-06-13 18:31:09 +00002099 !FD->hasAttr<UnusedAttr>() &&
Richard Smith0b8220a2012-08-07 21:30:42 +00002100 !FD->getParent()->isDependentContext() &&
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002101 !InitializationHasSideEffects(*FD))
2102 UnusedPrivateFields.insert(FD);
2103 }
2104 }
2105
John McCalld226f652010-08-21 09:40:31 +00002106 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002107}
2108
Hans Wennborg471f9852012-09-18 15:58:06 +00002109namespace {
2110 class UninitializedFieldVisitor
2111 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2112 Sema &S;
Richard Trieu858d2ba2013-10-25 00:56:00 +00002113 // List of Decls to generate a warning on. Also remove Decls that become
2114 // initialized.
Richard Trieuef8f90c2013-09-20 03:03:06 +00002115 llvm::SmallPtrSet<ValueDecl*, 4> &Decls;
Richard Trieuef8f90c2013-09-20 03:03:06 +00002116 // If non-null, add a note to the warning pointing back to the constructor.
2117 const CXXConstructorDecl *Constructor;
Hans Wennborg471f9852012-09-18 15:58:06 +00002118 public:
2119 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
Richard Trieu858d2ba2013-10-25 00:56:00 +00002120 UninitializedFieldVisitor(Sema &S,
Richard Trieuef8f90c2013-09-20 03:03:06 +00002121 llvm::SmallPtrSet<ValueDecl*, 4> &Decls,
Richard Trieuef8f90c2013-09-20 03:03:06 +00002122 const CXXConstructorDecl *Constructor)
Richard Trieu858d2ba2013-10-25 00:56:00 +00002123 : Inherited(S.Context), S(S), Decls(Decls),
2124 Constructor(Constructor) { }
Hans Wennborg471f9852012-09-18 15:58:06 +00002125
Richard Trieu3ddec882013-09-16 20:46:50 +00002126 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly) {
Richard Trieufbb08b52013-09-13 03:20:53 +00002127 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
2128 return;
Hans Wennborg471f9852012-09-18 15:58:06 +00002129
Richard Trieufbb08b52013-09-13 03:20:53 +00002130 // FieldME is the inner-most MemberExpr that is not an anonymous struct
2131 // or union.
2132 MemberExpr *FieldME = ME;
2133
2134 Expr *Base = ME;
2135 while (isa<MemberExpr>(Base)) {
2136 ME = cast<MemberExpr>(Base);
2137
2138 if (isa<VarDecl>(ME->getMemberDecl()))
2139 return;
2140
2141 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2142 if (!FD->isAnonymousStructOrUnion())
2143 FieldME = ME;
2144
2145 Base = ME->getBase();
2146 }
2147
Richard Trieu3ddec882013-09-16 20:46:50 +00002148 if (!isa<CXXThisExpr>(Base))
2149 return;
2150
Richard Trieuef8f90c2013-09-20 03:03:06 +00002151 ValueDecl* FoundVD = FieldME->getMemberDecl();
2152
Richard Trieu858d2ba2013-10-25 00:56:00 +00002153 if (!Decls.count(FoundVD))
Richard Trieuef8f90c2013-09-20 03:03:06 +00002154 return;
2155
Richard Trieu858d2ba2013-10-25 00:56:00 +00002156 const bool IsReference = FoundVD->getType()->isReferenceType();
Richard Trieuef8f90c2013-09-20 03:03:06 +00002157
Richard Trieu858d2ba2013-10-25 00:56:00 +00002158 // Prevent double warnings on use of unbounded references.
2159 if (IsReference != CheckReferenceOnly)
2160 return;
2161
2162 unsigned diag = IsReference
2163 ? diag::warn_reference_field_is_uninit
2164 : diag::warn_field_is_uninit;
2165 S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
2166 if (Constructor)
2167 S.Diag(Constructor->getLocation(),
2168 diag::note_uninit_in_this_constructor)
2169 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
2170
Hans Wennborg471f9852012-09-18 15:58:06 +00002171 }
2172
2173 void HandleValue(Expr *E) {
2174 E = E->IgnoreParens();
2175
2176 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
Richard Trieu3ddec882013-09-16 20:46:50 +00002177 HandleMemberExpr(ME, false /*CheckReferenceOnly*/);
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002178 return;
Hans Wennborg471f9852012-09-18 15:58:06 +00002179 }
2180
2181 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2182 HandleValue(CO->getTrueExpr());
2183 HandleValue(CO->getFalseExpr());
2184 return;
2185 }
2186
2187 if (BinaryConditionalOperator *BCO =
2188 dyn_cast<BinaryConditionalOperator>(E)) {
2189 HandleValue(BCO->getCommon());
2190 HandleValue(BCO->getFalseExpr());
2191 return;
2192 }
2193
2194 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2195 switch (BO->getOpcode()) {
2196 default:
2197 return;
2198 case(BO_PtrMemD):
2199 case(BO_PtrMemI):
2200 HandleValue(BO->getLHS());
2201 return;
2202 case(BO_Comma):
2203 HandleValue(BO->getRHS());
2204 return;
2205 }
2206 }
2207 }
2208
Richard Trieufbb08b52013-09-13 03:20:53 +00002209 void VisitMemberExpr(MemberExpr *ME) {
Richard Trieu858d2ba2013-10-25 00:56:00 +00002210 // All uses of unbounded reference fields will warn.
Richard Trieu3ddec882013-09-16 20:46:50 +00002211 HandleMemberExpr(ME, true /*CheckReferenceOnly*/);
Richard Trieufbb08b52013-09-13 03:20:53 +00002212
2213 Inherited::VisitMemberExpr(ME);
2214 }
2215
Hans Wennborg471f9852012-09-18 15:58:06 +00002216 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
2217 if (E->getCastKind() == CK_LValueToRValue)
2218 HandleValue(E->getSubExpr());
2219
2220 Inherited::VisitImplicitCastExpr(E);
2221 }
2222
Richard Trieufbb08b52013-09-13 03:20:53 +00002223 void VisitCXXConstructExpr(CXXConstructExpr *E) {
Richard Trieuef8f90c2013-09-20 03:03:06 +00002224 if (E->getConstructor()->isCopyConstructor())
Richard Trieufbb08b52013-09-13 03:20:53 +00002225 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(E->getArg(0)))
2226 if (ICE->getCastKind() == CK_NoOp)
2227 if (MemberExpr *ME = dyn_cast<MemberExpr>(ICE->getSubExpr()))
Richard Trieu3ddec882013-09-16 20:46:50 +00002228 HandleMemberExpr(ME, false /*CheckReferenceOnly*/);
Richard Trieufbb08b52013-09-13 03:20:53 +00002229
2230 Inherited::VisitCXXConstructExpr(E);
2231 }
2232
Hans Wennborg471f9852012-09-18 15:58:06 +00002233 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2234 Expr *Callee = E->getCallee();
2235 if (isa<MemberExpr>(Callee))
2236 HandleValue(Callee);
2237
2238 Inherited::VisitCXXMemberCallExpr(E);
2239 }
Richard Trieuef8f90c2013-09-20 03:03:06 +00002240
2241 void VisitBinaryOperator(BinaryOperator *E) {
2242 // If a field assignment is detected, remove the field from the
2243 // uninitiailized field set.
2244 if (E->getOpcode() == BO_Assign)
2245 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
2246 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
Richard Trieu858d2ba2013-10-25 00:56:00 +00002247 if (!FD->getType()->isReferenceType())
2248 Decls.erase(FD);
Richard Trieuef8f90c2013-09-20 03:03:06 +00002249
2250 Inherited::VisitBinaryOperator(E);
2251 }
Hans Wennborg471f9852012-09-18 15:58:06 +00002252 };
Richard Trieuef8f90c2013-09-20 03:03:06 +00002253 static void CheckInitExprContainsUninitializedFields(
Richard Trieu858d2ba2013-10-25 00:56:00 +00002254 Sema &S, Expr *E, llvm::SmallPtrSet<ValueDecl*, 4> &Decls,
2255 const CXXConstructorDecl *Constructor) {
2256 if (Decls.size() == 0)
Richard Trieuef8f90c2013-09-20 03:03:06 +00002257 return;
2258
Richard Trieu858d2ba2013-10-25 00:56:00 +00002259 if (!E)
2260 return;
2261
2262 if (CXXDefaultInitExpr *Default = dyn_cast<CXXDefaultInitExpr>(E)) {
2263 E = Default->getExpr();
2264 if (!E)
2265 return;
2266 // In class initializers will point to the constructor.
2267 UninitializedFieldVisitor(S, Decls, Constructor).Visit(E);
2268 } else {
2269 UninitializedFieldVisitor(S, Decls, 0).Visit(E);
2270 }
2271 }
2272
2273 // Diagnose value-uses of fields to initialize themselves, e.g.
2274 // foo(foo)
2275 // where foo is not also a parameter to the constructor.
2276 // Also diagnose across field uninitialized use such as
2277 // x(y), y(x)
2278 // TODO: implement -Wuninitialized and fold this into that framework.
2279 static void DiagnoseUninitializedFields(
2280 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
2281
2282 if (SemaRef.getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit,
2283 Constructor->getLocation())
2284 == DiagnosticsEngine::Ignored) {
2285 return;
2286 }
2287
2288 if (Constructor->isInvalidDecl())
2289 return;
2290
2291 const CXXRecordDecl *RD = Constructor->getParent();
2292
2293 // Holds fields that are uninitialized.
2294 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
2295
2296 // At the beginning, all fields are uninitialized.
2297 for (DeclContext::decl_iterator I = RD->decls_begin(), E = RD->decls_end();
2298 I != E; ++I) {
2299 if (FieldDecl *FD = dyn_cast<FieldDecl>(*I)) {
2300 UninitializedFields.insert(FD);
2301 } else if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(*I)) {
2302 UninitializedFields.insert(IFD->getAnonField());
2303 }
2304 }
2305
2306 for (CXXConstructorDecl::init_const_iterator FieldInit =
2307 Constructor->init_begin(),
2308 FieldInitEnd = Constructor->init_end();
2309 FieldInit != FieldInitEnd; ++FieldInit) {
2310
2311 Expr *InitExpr = (*FieldInit)->getInit();
2312
2313 CheckInitExprContainsUninitializedFields(
2314 SemaRef, InitExpr, UninitializedFields, Constructor);
2315
2316 if (FieldDecl *Field = (*FieldInit)->getAnyMember())
2317 UninitializedFields.erase(Field);
2318 }
Hans Wennborg471f9852012-09-18 15:58:06 +00002319 }
2320} // namespace
2321
Richard Smith7a614d82011-06-11 17:19:42 +00002322/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
Richard Smith0ff6f8f2011-07-20 00:12:52 +00002323/// in-class initializer for a non-static C++ class member, and after
2324/// instantiating an in-class initializer in a class template. Such actions
2325/// are deferred until the class is complete.
Richard Smith7a614d82011-06-11 17:19:42 +00002326void
Richard Smithca523302012-06-10 03:12:00 +00002327Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation InitLoc,
Richard Smith7a614d82011-06-11 17:19:42 +00002328 Expr *InitExpr) {
2329 FieldDecl *FD = cast<FieldDecl>(D);
Richard Smithca523302012-06-10 03:12:00 +00002330 assert(FD->getInClassInitStyle() != ICIS_NoInit &&
2331 "must set init style when field is created");
Richard Smith7a614d82011-06-11 17:19:42 +00002332
2333 if (!InitExpr) {
2334 FD->setInvalidDecl();
2335 FD->removeInClassInitializer();
2336 return;
2337 }
2338
Peter Collingbournefef21892011-10-23 18:59:44 +00002339 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
2340 FD->setInvalidDecl();
2341 FD->removeInClassInitializer();
2342 return;
2343 }
2344
Richard Smith7a614d82011-06-11 17:19:42 +00002345 ExprResult Init = InitExpr;
Richard Smithc83c2302012-12-19 01:39:02 +00002346 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
Sebastian Redl33deb352012-02-22 10:50:08 +00002347 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
Richard Smithca523302012-06-10 03:12:00 +00002348 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
Sebastian Redl33deb352012-02-22 10:50:08 +00002349 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
Richard Smithca523302012-06-10 03:12:00 +00002350 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002351 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2352 Init = Seq.Perform(*this, Entity, Kind, InitExpr);
Richard Smith7a614d82011-06-11 17:19:42 +00002353 if (Init.isInvalid()) {
2354 FD->setInvalidDecl();
2355 return;
2356 }
Richard Smith7a614d82011-06-11 17:19:42 +00002357 }
2358
Richard Smith41956372013-01-14 22:39:08 +00002359 // C++11 [class.base.init]p7:
Richard Smith7a614d82011-06-11 17:19:42 +00002360 // The initialization of each base and member constitutes a
2361 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002362 Init = ActOnFinishFullExpr(Init.take(), InitLoc);
Richard Smith7a614d82011-06-11 17:19:42 +00002363 if (Init.isInvalid()) {
2364 FD->setInvalidDecl();
2365 return;
2366 }
2367
2368 InitExpr = Init.release();
2369
2370 FD->setInClassInitializer(InitExpr);
2371}
2372
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002373/// \brief Find the direct and/or virtual base specifiers that
2374/// correspond to the given base type, for use in base initialization
2375/// within a constructor.
2376static bool FindBaseInitializer(Sema &SemaRef,
2377 CXXRecordDecl *ClassDecl,
2378 QualType BaseType,
2379 const CXXBaseSpecifier *&DirectBaseSpec,
2380 const CXXBaseSpecifier *&VirtualBaseSpec) {
2381 // First, check for a direct base class.
2382 DirectBaseSpec = 0;
2383 for (CXXRecordDecl::base_class_const_iterator Base
2384 = ClassDecl->bases_begin();
2385 Base != ClassDecl->bases_end(); ++Base) {
2386 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
2387 // We found a direct base of this type. That's what we're
2388 // initializing.
2389 DirectBaseSpec = &*Base;
2390 break;
2391 }
2392 }
2393
2394 // Check for a virtual base class.
2395 // FIXME: We might be able to short-circuit this if we know in advance that
2396 // there are no virtual bases.
2397 VirtualBaseSpec = 0;
2398 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2399 // We haven't found a base yet; search the class hierarchy for a
2400 // virtual base class.
2401 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2402 /*DetectVirtual=*/false);
2403 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2404 BaseType, Paths)) {
2405 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2406 Path != Paths.end(); ++Path) {
2407 if (Path->back().Base->isVirtual()) {
2408 VirtualBaseSpec = Path->back().Base;
2409 break;
2410 }
2411 }
2412 }
2413 }
2414
2415 return DirectBaseSpec || VirtualBaseSpec;
2416}
2417
Sebastian Redl6df65482011-09-24 17:48:25 +00002418/// \brief Handle a C++ member initializer using braced-init-list syntax.
2419MemInitResult
2420Sema::ActOnMemInitializer(Decl *ConstructorD,
2421 Scope *S,
2422 CXXScopeSpec &SS,
2423 IdentifierInfo *MemberOrBase,
2424 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002425 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00002426 SourceLocation IdLoc,
2427 Expr *InitList,
2428 SourceLocation EllipsisLoc) {
2429 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002430 DS, IdLoc, InitList,
David Blaikief2116622012-01-24 06:03:59 +00002431 EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002432}
2433
2434/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallf312b1e2010-08-26 23:41:50 +00002435MemInitResult
John McCalld226f652010-08-21 09:40:31 +00002436Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002437 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00002438 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002439 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00002440 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002441 const DeclSpec &DS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002442 SourceLocation IdLoc,
2443 SourceLocation LParenLoc,
Dmitri Gribenkoa36bbac2013-05-09 23:51:52 +00002444 ArrayRef<Expr *> Args,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002445 SourceLocation RParenLoc,
2446 SourceLocation EllipsisLoc) {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002447 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
Dmitri Gribenkoa36bbac2013-05-09 23:51:52 +00002448 Args, RParenLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002449 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002450 DS, IdLoc, List, EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002451}
2452
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002453namespace {
2454
Kaelyn Uhraindc98cd02012-01-11 21:17:51 +00002455// Callback to only accept typo corrections that can be a valid C++ member
2456// intializer: either a non-static field member or a base class.
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002457class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00002458public:
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002459 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2460 : ClassDecl(ClassDecl) {}
2461
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00002462 bool ValidateCandidate(const TypoCorrection &candidate) LLVM_OVERRIDE {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002463 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2464 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2465 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00002466 return isa<TypeDecl>(ND);
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002467 }
2468 return false;
2469 }
2470
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00002471private:
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002472 CXXRecordDecl *ClassDecl;
2473};
2474
2475}
2476
Sebastian Redl6df65482011-09-24 17:48:25 +00002477/// \brief Handle a C++ member initializer.
2478MemInitResult
2479Sema::BuildMemInitializer(Decl *ConstructorD,
2480 Scope *S,
2481 CXXScopeSpec &SS,
2482 IdentifierInfo *MemberOrBase,
2483 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002484 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00002485 SourceLocation IdLoc,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002486 Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002487 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002488 if (!ConstructorD)
2489 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002490
Douglas Gregorefd5bda2009-08-24 11:57:43 +00002491 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00002492
2493 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002494 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002495 if (!Constructor) {
2496 // The user wrote a constructor initializer on a function that is
2497 // not a C++ constructor. Ignore the error for now, because we may
2498 // have more member initializers coming; we'll diagnose it just
2499 // once in ActOnMemInitializers.
2500 return true;
2501 }
2502
2503 CXXRecordDecl *ClassDecl = Constructor->getParent();
2504
2505 // C++ [class.base.init]p2:
2506 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky7663f392010-11-20 01:29:55 +00002507 // constructor's class and, if not found in that scope, are looked
2508 // up in the scope containing the constructor's definition.
2509 // [Note: if the constructor's class contains a member with the
2510 // same name as a direct or virtual base class of the class, a
2511 // mem-initializer-id naming the member or base class and composed
2512 // of a single identifier refers to the class member. A
Douglas Gregor7ad83902008-11-05 04:29:56 +00002513 // mem-initializer-id for the hidden base class may be specified
2514 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00002515 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00002516 // Look for a member, first.
Mike Stump1eb44332009-09-09 15:08:12 +00002517 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00002518 = ClassDecl->lookup(MemberOrBase);
David Blaikie3bc93e32012-12-19 00:45:41 +00002519 if (!Result.empty()) {
Peter Collingbournedc69be22011-10-23 18:59:37 +00002520 ValueDecl *Member;
David Blaikie3bc93e32012-12-19 00:45:41 +00002521 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2522 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002523 if (EllipsisLoc.isValid())
2524 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002525 << MemberOrBase
2526 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002527
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002528 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002529 }
Francois Pichet00eb3f92010-12-04 09:14:42 +00002530 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00002531 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00002532 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00002533 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00002534 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00002535
2536 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00002537 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikief2116622012-01-24 06:03:59 +00002538 } else if (DS.getTypeSpecType() == TST_decltype) {
2539 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCall2b194412009-12-21 10:41:20 +00002540 } else {
2541 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2542 LookupParsedName(R, S, &SS);
2543
2544 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2545 if (!TyD) {
2546 if (R.isAmbiguous()) return true;
2547
John McCallfd225442010-04-09 19:01:14 +00002548 // We don't want access-control diagnostics here.
2549 R.suppressDiagnostics();
2550
Douglas Gregor7a886e12010-01-19 06:46:48 +00002551 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2552 bool NotUnknownSpecialization = false;
2553 DeclContext *DC = computeDeclContext(SS, false);
2554 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2555 NotUnknownSpecialization = !Record->hasAnyDependentBases();
2556
2557 if (!NotUnknownSpecialization) {
2558 // When the scope specifier can refer to a member of an unknown
2559 // specialization, we take it as a type name.
Douglas Gregore29425b2011-02-28 22:42:13 +00002560 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2561 SS.getWithLocInContext(Context),
2562 *MemberOrBase, IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00002563 if (BaseType.isNull())
2564 return true;
2565
Douglas Gregor7a886e12010-01-19 06:46:48 +00002566 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00002567 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002568 }
2569 }
2570
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002571 // If no results were found, try to correct typos.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002572 TypoCorrection Corr;
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002573 MemInitializerValidatorCCC Validator(ClassDecl);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002574 if (R.empty() && BaseType.isNull() &&
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002575 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00002576 Validator, ClassDecl))) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002577 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002578 // We have found a non-static data member with a similar
2579 // name to what was typed; complain and initialize that
2580 // member.
Richard Smith2d670972013-08-17 00:46:16 +00002581 diagnoseTypo(Corr,
2582 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2583 << MemberOrBase << true);
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002584 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002585 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002586 const CXXBaseSpecifier *DirectBaseSpec;
2587 const CXXBaseSpecifier *VirtualBaseSpec;
2588 if (FindBaseInitializer(*this, ClassDecl,
2589 Context.getTypeDeclType(Type),
2590 DirectBaseSpec, VirtualBaseSpec)) {
2591 // We have found a direct or virtual base class with a
2592 // similar name to what was typed; complain and initialize
2593 // that base class.
Richard Smith2d670972013-08-17 00:46:16 +00002594 diagnoseTypo(Corr,
2595 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2596 << MemberOrBase << false,
2597 PDiag() /*Suppress note, we provide our own.*/);
Douglas Gregor0d535c82010-01-07 00:26:25 +00002598
Richard Smith2d670972013-08-17 00:46:16 +00002599 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
2600 : VirtualBaseSpec;
Daniel Dunbar96a00142012-03-09 18:35:03 +00002601 Diag(BaseSpec->getLocStart(),
Douglas Gregor0d535c82010-01-07 00:26:25 +00002602 diag::note_base_class_specified_here)
2603 << BaseSpec->getType()
2604 << BaseSpec->getSourceRange();
2605
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002606 TyD = Type;
2607 }
2608 }
2609 }
2610
Douglas Gregor7a886e12010-01-19 06:46:48 +00002611 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002612 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002613 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002614 return true;
2615 }
John McCall2b194412009-12-21 10:41:20 +00002616 }
2617
Douglas Gregor7a886e12010-01-19 06:46:48 +00002618 if (BaseType.isNull()) {
2619 BaseType = Context.getTypeDeclType(TyD);
2620 if (SS.isSet()) {
2621 NestedNameSpecifier *Qualifier =
2622 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00002623
Douglas Gregor7a886e12010-01-19 06:46:48 +00002624 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002625 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002626 }
John McCall2b194412009-12-21 10:41:20 +00002627 }
2628 }
Mike Stump1eb44332009-09-09 15:08:12 +00002629
John McCalla93c9342009-12-07 02:54:59 +00002630 if (!TInfo)
2631 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002632
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002633 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00002634}
2635
Chandler Carruth81c64772011-09-03 01:14:15 +00002636/// Checks a member initializer expression for cases where reference (or
2637/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth81c64772011-09-03 01:14:15 +00002638static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2639 Expr *Init,
2640 SourceLocation IdLoc) {
2641 QualType MemberTy = Member->getType();
2642
2643 // We only handle pointers and references currently.
2644 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2645 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2646 return;
2647
2648 const bool IsPointer = MemberTy->isPointerType();
2649 if (IsPointer) {
2650 if (const UnaryOperator *Op
2651 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2652 // The only case we're worried about with pointers requires taking the
2653 // address.
2654 if (Op->getOpcode() != UO_AddrOf)
2655 return;
2656
2657 Init = Op->getSubExpr();
2658 } else {
2659 // We only handle address-of expression initializers for pointers.
2660 return;
2661 }
2662 }
2663
Richard Smitha4bb99c2013-06-12 21:51:50 +00002664 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002665 // We only warn when referring to a non-reference parameter declaration.
2666 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2667 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth81c64772011-09-03 01:14:15 +00002668 return;
2669
2670 S.Diag(Init->getExprLoc(),
2671 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2672 : diag::warn_bind_ref_member_to_parameter)
2673 << Member << Parameter << Init->getSourceRange();
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002674 } else {
2675 // Other initializers are fine.
2676 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002677 }
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002678
2679 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2680 << (unsigned)IsPointer;
Chandler Carruth81c64772011-09-03 01:14:15 +00002681}
2682
John McCallf312b1e2010-08-26 23:41:50 +00002683MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002684Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002685 SourceLocation IdLoc) {
Chandler Carruth894aed92010-12-06 09:23:57 +00002686 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2687 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2688 assert((DirectMember || IndirectMember) &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00002689 "Member must be a FieldDecl or IndirectFieldDecl");
2690
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002691 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbournefef21892011-10-23 18:59:44 +00002692 return true;
2693
Douglas Gregor464b2f02010-11-05 22:21:31 +00002694 if (Member->isInvalidDecl())
2695 return true;
Chandler Carruth894aed92010-12-06 09:23:57 +00002696
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002697 MultiExprArg Args;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002698 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002699 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Richard Smithc83c2302012-12-19 01:39:02 +00002700 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002701 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Richard Smithc83c2302012-12-19 01:39:02 +00002702 } else {
2703 // Template instantiation doesn't reconstruct ParenListExprs for us.
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002704 Args = Init;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002705 }
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002706
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002707 SourceRange InitRange = Init->getSourceRange();
Eli Friedman59c04372009-07-29 19:44:27 +00002708
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002709 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002710 // Can't check initialization for a member of dependent type or when
2711 // any of the arguments are type-dependent expressions.
John McCallf85e1932011-06-15 23:02:42 +00002712 DiscardCleanupsInEvaluationContext();
Chandler Carruth894aed92010-12-06 09:23:57 +00002713 } else {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002714 bool InitList = false;
2715 if (isa<InitListExpr>(Init)) {
2716 InitList = true;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002717 Args = Init;
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002718 }
2719
Chandler Carruth894aed92010-12-06 09:23:57 +00002720 // Initialize the member.
2721 InitializedEntity MemberEntity =
2722 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2723 : InitializedEntity::InitializeMember(IndirectMember, 0);
2724 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002725 InitList ? InitializationKind::CreateDirectList(IdLoc)
2726 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2727 InitRange.getEnd());
John McCallb4eb64d2010-10-08 02:01:28 +00002728
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002729 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
2730 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 0);
Chandler Carruth894aed92010-12-06 09:23:57 +00002731 if (MemberInit.isInvalid())
2732 return true;
2733
Richard Smith8a07cd32013-06-12 20:42:33 +00002734 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
2735
Richard Smith41956372013-01-14 22:39:08 +00002736 // C++11 [class.base.init]p7:
Chandler Carruth894aed92010-12-06 09:23:57 +00002737 // The initialization of each base and member constitutes a
2738 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002739 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
Chandler Carruth894aed92010-12-06 09:23:57 +00002740 if (MemberInit.isInvalid())
2741 return true;
2742
Richard Smithc83c2302012-12-19 01:39:02 +00002743 Init = MemberInit.get();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002744 }
2745
Chandler Carruth894aed92010-12-06 09:23:57 +00002746 if (DirectMember) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002747 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2748 InitRange.getBegin(), Init,
2749 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002750 } else {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002751 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2752 InitRange.getBegin(), Init,
2753 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002754 }
Eli Friedman59c04372009-07-29 19:44:27 +00002755}
2756
John McCallf312b1e2010-08-26 23:41:50 +00002757MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002758Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Sean Hunt41717662011-02-26 19:13:13 +00002759 CXXRecordDecl *ClassDecl) {
Douglas Gregor76852c22011-11-01 01:16:03 +00002760 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Richard Smith80ad52f2013-01-02 11:42:31 +00002761 if (!LangOpts.CPlusPlus11)
Douglas Gregor76852c22011-11-01 01:16:03 +00002762 return Diag(NameLoc, diag::err_delegating_ctor)
Sean Hunt97fcc492011-01-08 19:20:43 +00002763 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor76852c22011-11-01 01:16:03 +00002764 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redlf9c32eb2011-03-12 13:53:51 +00002765
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002766 bool InitList = true;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002767 MultiExprArg Args = Init;
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002768 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2769 InitList = false;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002770 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002771 }
2772
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002773 SourceRange InitRange = Init->getSourceRange();
Sean Hunt41717662011-02-26 19:13:13 +00002774 // Initialize the object.
2775 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2776 QualType(ClassDecl->getTypeForDecl(), 0));
2777 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002778 InitList ? InitializationKind::CreateDirectList(NameLoc)
2779 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2780 InitRange.getEnd());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002781 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002782 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002783 Args, 0);
Sean Hunt41717662011-02-26 19:13:13 +00002784 if (DelegationInit.isInvalid())
2785 return true;
2786
Matt Beaumont-Gay2eb0ce32011-11-01 18:10:22 +00002787 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2788 "Delegating constructor with no target?");
Sean Hunt41717662011-02-26 19:13:13 +00002789
Richard Smith41956372013-01-14 22:39:08 +00002790 // C++11 [class.base.init]p7:
Sean Hunt41717662011-02-26 19:13:13 +00002791 // The initialization of each base and member constitutes a
2792 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002793 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
2794 InitRange.getBegin());
Sean Hunt41717662011-02-26 19:13:13 +00002795 if (DelegationInit.isInvalid())
2796 return true;
2797
Eli Friedmand21016f2012-05-19 23:35:23 +00002798 // If we are in a dependent context, template instantiation will
2799 // perform this type-checking again. Just save the arguments that we
2800 // received in a ParenListExpr.
2801 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2802 // of the information that we have about the base
2803 // initializer. However, deconstructing the ASTs is a dicey process,
2804 // and this approach is far more likely to get the corner cases right.
2805 if (CurContext->isDependentContext())
2806 DelegationInit = Owned(Init);
2807
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002808 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Sean Hunt41717662011-02-26 19:13:13 +00002809 DelegationInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002810 InitRange.getEnd());
Sean Hunt97fcc492011-01-08 19:20:43 +00002811}
2812
2813MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00002814Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002815 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002816 SourceLocation EllipsisLoc) {
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002817 SourceLocation BaseLoc
2818 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redl6df65482011-09-24 17:48:25 +00002819
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002820 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2821 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2822 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2823
2824 // C++ [class.base.init]p2:
2825 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00002826 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002827 // of that class, the mem-initializer is ill-formed. A
2828 // mem-initializer-list can initialize a base class using any
2829 // name that denotes that base class type.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002830 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002831
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002832 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002833 if (EllipsisLoc.isValid()) {
2834 // This is a pack expansion.
2835 if (!BaseType->containsUnexpandedParameterPack()) {
2836 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002837 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002838
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002839 EllipsisLoc = SourceLocation();
2840 }
2841 } else {
2842 // Check for any unexpanded parameter packs.
2843 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2844 return true;
Sebastian Redl6df65482011-09-24 17:48:25 +00002845
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002846 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redl6df65482011-09-24 17:48:25 +00002847 return true;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002848 }
Sebastian Redl6df65482011-09-24 17:48:25 +00002849
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002850 // Check for direct and virtual base classes.
2851 const CXXBaseSpecifier *DirectBaseSpec = 0;
2852 const CXXBaseSpecifier *VirtualBaseSpec = 0;
2853 if (!Dependent) {
Sean Hunt97fcc492011-01-08 19:20:43 +00002854 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2855 BaseType))
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002856 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Sean Hunt97fcc492011-01-08 19:20:43 +00002857
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002858 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2859 VirtualBaseSpec);
2860
2861 // C++ [base.class.init]p2:
2862 // Unless the mem-initializer-id names a nonstatic data member of the
2863 // constructor's class or a direct or virtual base of that class, the
2864 // mem-initializer is ill-formed.
2865 if (!DirectBaseSpec && !VirtualBaseSpec) {
2866 // If the class has any dependent bases, then it's possible that
2867 // one of those types will resolve to the same type as
2868 // BaseType. Therefore, just treat this as a dependent base
2869 // class initialization. FIXME: Should we try to check the
2870 // initialization anyway? It seems odd.
2871 if (ClassDecl->hasAnyDependentBases())
2872 Dependent = true;
2873 else
2874 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2875 << BaseType << Context.getTypeDeclType(ClassDecl)
2876 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2877 }
2878 }
2879
2880 if (Dependent) {
John McCallf85e1932011-06-15 23:02:42 +00002881 DiscardCleanupsInEvaluationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002882
Sebastian Redl6df65482011-09-24 17:48:25 +00002883 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2884 /*IsVirtual=*/false,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002885 InitRange.getBegin(), Init,
2886 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002887 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002888
2889 // C++ [base.class.init]p2:
2890 // If a mem-initializer-id is ambiguous because it designates both
2891 // a direct non-virtual base class and an inherited virtual base
2892 // class, the mem-initializer is ill-formed.
2893 if (DirectBaseSpec && VirtualBaseSpec)
2894 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002895 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002896
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00002897 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002898 if (!BaseSpec)
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00002899 BaseSpec = VirtualBaseSpec;
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002900
2901 // Initialize the base.
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002902 bool InitList = true;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002903 MultiExprArg Args = Init;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002904 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002905 InitList = false;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002906 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002907 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002908
2909 InitializedEntity BaseEntity =
2910 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2911 InitializationKind Kind =
2912 InitList ? InitializationKind::CreateDirectList(BaseLoc)
2913 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2914 InitRange.getEnd());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002915 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
2916 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, 0);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002917 if (BaseInit.isInvalid())
2918 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00002919
Richard Smith41956372013-01-14 22:39:08 +00002920 // C++11 [class.base.init]p7:
2921 // The initialization of each base and member constitutes a
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002922 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002923 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002924 if (BaseInit.isInvalid())
2925 return true;
2926
2927 // If we are in a dependent context, template instantiation will
2928 // perform this type-checking again. Just save the arguments that we
2929 // received in a ParenListExpr.
2930 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2931 // of the information that we have about the base
2932 // initializer. However, deconstructing the ASTs is a dicey process,
2933 // and this approach is far more likely to get the corner cases right.
Sebastian Redl6df65482011-09-24 17:48:25 +00002934 if (CurContext->isDependentContext())
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002935 BaseInit = Owned(Init);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002936
Sean Huntcbb67482011-01-08 20:30:50 +00002937 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00002938 BaseSpec->isVirtual(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002939 InitRange.getBegin(),
Sebastian Redl6df65482011-09-24 17:48:25 +00002940 BaseInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002941 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002942}
2943
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002944// Create a static_cast\<T&&>(expr).
Richard Smith07b0fdc2013-03-18 21:12:30 +00002945static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
2946 if (T.isNull()) T = E->getType();
2947 QualType TargetType = SemaRef.BuildReferenceType(
2948 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002949 SourceLocation ExprLoc = E->getLocStart();
2950 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2951 TargetType, ExprLoc);
2952
2953 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2954 SourceRange(ExprLoc, ExprLoc),
2955 E->getSourceRange()).take();
2956}
2957
Anders Carlssone5ef7402010-04-23 03:10:23 +00002958/// ImplicitInitializerKind - How an implicit base or member initializer should
2959/// initialize its base or member.
2960enum ImplicitInitializerKind {
2961 IIK_Default,
2962 IIK_Copy,
Richard Smith07b0fdc2013-03-18 21:12:30 +00002963 IIK_Move,
2964 IIK_Inherit
Anders Carlssone5ef7402010-04-23 03:10:23 +00002965};
2966
Anders Carlssondefefd22010-04-23 02:00:02 +00002967static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002968BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002969 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002970 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00002971 bool IsInheritedVirtualBase,
Sean Huntcbb67482011-01-08 20:30:50 +00002972 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00002973 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00002974 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2975 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00002976
John McCall60d7b3a2010-08-24 06:29:42 +00002977 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002978
2979 switch (ImplicitInitKind) {
Richard Smith07b0fdc2013-03-18 21:12:30 +00002980 case IIK_Inherit: {
2981 const CXXRecordDecl *Inherited =
2982 Constructor->getInheritedConstructor()->getParent();
2983 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
2984 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
2985 // C++11 [class.inhctor]p8:
2986 // Each expression in the expression-list is of the form
2987 // static_cast<T&&>(p), where p is the name of the corresponding
2988 // constructor parameter and T is the declared type of p.
2989 SmallVector<Expr*, 16> Args;
2990 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
2991 ParmVarDecl *PD = Constructor->getParamDecl(I);
2992 ExprResult ArgExpr =
2993 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
2994 VK_LValue, SourceLocation());
2995 if (ArgExpr.isInvalid())
2996 return true;
2997 Args.push_back(CastForMoving(SemaRef, ArgExpr.take(), PD->getType()));
2998 }
2999
3000 InitializationKind InitKind = InitializationKind::CreateDirect(
3001 Constructor->getLocation(), SourceLocation(), SourceLocation());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003002 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args);
Richard Smith07b0fdc2013-03-18 21:12:30 +00003003 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
3004 break;
3005 }
3006 }
3007 // Fall through.
Anders Carlssone5ef7402010-04-23 03:10:23 +00003008 case IIK_Default: {
3009 InitializationKind InitKind
3010 = InitializationKind::CreateDefault(Constructor->getLocation());
Dmitri Gribenko62ed8892013-05-05 20:40:26 +00003011 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3012 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
Anders Carlssone5ef7402010-04-23 03:10:23 +00003013 break;
3014 }
Anders Carlsson84688f22010-04-20 23:11:20 +00003015
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003016 case IIK_Move:
Anders Carlssone5ef7402010-04-23 03:10:23 +00003017 case IIK_Copy: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003018 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssone5ef7402010-04-23 03:10:23 +00003019 ParmVarDecl *Param = Constructor->getParamDecl(0);
3020 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedmancf7c14c2012-01-16 21:00:51 +00003021
Anders Carlssone5ef7402010-04-23 03:10:23 +00003022 Expr *CopyCtorArg =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00003023 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00003024 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00003025 Constructor->getLocation(), ParamType,
3026 VK_LValue, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003027
Eli Friedman5f2987c2012-02-02 03:46:19 +00003028 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
3029
Anders Carlssonc7957502010-04-24 22:02:54 +00003030 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00003031 QualType ArgTy =
3032 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
3033 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00003034
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003035 if (Moving) {
3036 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
3037 }
3038
John McCallf871d0c2010-08-07 06:22:56 +00003039 CXXCastPath BasePath;
3040 BasePath.push_back(BaseSpec);
John Wiegley429bb272011-04-08 18:41:53 +00003041 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
3042 CK_UncheckedDerivedToBase,
Sebastian Redl74e611a2011-09-04 18:14:28 +00003043 Moving ? VK_XValue : VK_LValue,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003044 &BasePath).take();
Anders Carlssonc7957502010-04-24 22:02:54 +00003045
Anders Carlssone5ef7402010-04-23 03:10:23 +00003046 InitializationKind InitKind
3047 = InitializationKind::CreateDirect(Constructor->getLocation(),
3048 SourceLocation(), SourceLocation());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003049 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
3050 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
Anders Carlssone5ef7402010-04-23 03:10:23 +00003051 break;
3052 }
Anders Carlssone5ef7402010-04-23 03:10:23 +00003053 }
John McCall9ae2f072010-08-23 23:25:46 +00003054
Douglas Gregor53c374f2010-12-07 00:41:46 +00003055 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00003056 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00003057 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00003058
Anders Carlssondefefd22010-04-23 02:00:02 +00003059 CXXBaseInit =
Sean Huntcbb67482011-01-08 20:30:50 +00003060 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlsson84688f22010-04-20 23:11:20 +00003061 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
3062 SourceLocation()),
3063 BaseSpec->isVirtual(),
3064 SourceLocation(),
3065 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003066 SourceLocation(),
Anders Carlsson84688f22010-04-20 23:11:20 +00003067 SourceLocation());
3068
Anders Carlssondefefd22010-04-23 02:00:02 +00003069 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00003070}
3071
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003072static bool RefersToRValueRef(Expr *MemRef) {
3073 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
3074 return Referenced->getType()->isRValueReferenceType();
3075}
3076
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003077static bool
3078BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003079 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003080 FieldDecl *Field, IndirectFieldDecl *Indirect,
Sean Huntcbb67482011-01-08 20:30:50 +00003081 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00003082 if (Field->isInvalidDecl())
3083 return true;
3084
Chandler Carruthf186b542010-06-29 23:50:44 +00003085 SourceLocation Loc = Constructor->getLocation();
3086
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003087 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
3088 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssonf6513ed2010-04-23 16:04:08 +00003089 ParmVarDecl *Param = Constructor->getParamDecl(0);
3090 QualType ParamType = Param->getType().getNonReferenceType();
John McCallb77115d2011-06-17 00:18:42 +00003091
3092 // Suppress copying zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003093 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
3094 return false;
Douglas Gregorddb21472011-11-02 23:04:16 +00003095
Anders Carlssonf6513ed2010-04-23 16:04:08 +00003096 Expr *MemberExprBase =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00003097 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00003098 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00003099 Loc, ParamType, VK_LValue, 0);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003100
Eli Friedman5f2987c2012-02-02 03:46:19 +00003101 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
3102
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003103 if (Moving) {
3104 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
3105 }
3106
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003107 // Build a reference to this field within the parameter.
3108 CXXScopeSpec SS;
3109 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
3110 Sema::LookupMemberName);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003111 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
3112 : cast<ValueDecl>(Field), AS_public);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003113 MemberLookup.resolveKind();
Sebastian Redl74e611a2011-09-04 18:14:28 +00003114 ExprResult CtorArg
John McCall9ae2f072010-08-23 23:25:46 +00003115 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003116 ParamType, Loc,
3117 /*IsArrow=*/false,
3118 SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00003119 /*TemplateKWLoc=*/SourceLocation(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003120 /*FirstQualifierInScope=*/0,
3121 MemberLookup,
3122 /*TemplateArgs=*/0);
Sebastian Redl74e611a2011-09-04 18:14:28 +00003123 if (CtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00003124 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003125
3126 // C++11 [class.copy]p15:
3127 // - if a member m has rvalue reference type T&&, it is direct-initialized
3128 // with static_cast<T&&>(x.m);
Sebastian Redl74e611a2011-09-04 18:14:28 +00003129 if (RefersToRValueRef(CtorArg.get())) {
3130 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003131 }
3132
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003133 // When the field we are copying is an array, create index variables for
3134 // each dimension of the array. We use these index variables to subscript
3135 // the source array, and other clients (e.g., CodeGen) will perform the
3136 // necessary iteration with these index variables.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003137 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003138 QualType BaseType = Field->getType();
3139 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003140 bool InitializingArray = false;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003141 while (const ConstantArrayType *Array
3142 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003143 InitializingArray = true;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003144 // Create the iteration variable for this array index.
3145 IdentifierInfo *IterationVarName = 0;
3146 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003147 SmallString<8> Str;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003148 llvm::raw_svector_ostream OS(Str);
3149 OS << "__i" << IndexVariables.size();
3150 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
3151 }
3152 VarDecl *IterationVar
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003153 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003154 IterationVarName, SizeType,
3155 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00003156 SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003157 IndexVariables.push_back(IterationVar);
3158
3159 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00003160 ExprResult IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00003161 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003162 assert(!IterationVarRef.isInvalid() &&
3163 "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00003164 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
3165 assert(!IterationVarRef.isInvalid() &&
3166 "Conversion of invented variable cannot fail!");
Sebastian Redl74e611a2011-09-04 18:14:28 +00003167
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003168 // Subscript the array with this iteration variable.
Sebastian Redl74e611a2011-09-04 18:14:28 +00003169 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCall9ae2f072010-08-23 23:25:46 +00003170 IterationVarRef.take(),
Sebastian Redl74e611a2011-09-04 18:14:28 +00003171 Loc);
3172 if (CtorArg.isInvalid())
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003173 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003174
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003175 BaseType = Array->getElementType();
3176 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003177
3178 // The array subscript expression is an lvalue, which is wrong for moving.
3179 if (Moving && InitializingArray)
Sebastian Redl74e611a2011-09-04 18:14:28 +00003180 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003181
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003182 // Construct the entity that we will be initializing. For an array, this
3183 // will be first element in the array, which may require several levels
3184 // of array-subscript entities.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003185 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003186 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003187 if (Indirect)
3188 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
3189 else
3190 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003191 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
3192 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
3193 0,
3194 Entities.back()));
3195
3196 // Direct-initialize to use the copy constructor.
3197 InitializationKind InitKind =
3198 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
3199
Sebastian Redl74e611a2011-09-04 18:14:28 +00003200 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003201 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, CtorArgE);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003202
John McCall60d7b3a2010-08-24 06:29:42 +00003203 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003204 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00003205 MultiExprArg(&CtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00003206 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003207 if (MemberInit.isInvalid())
3208 return true;
3209
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003210 if (Indirect) {
3211 assert(IndexVariables.size() == 0 &&
3212 "Indirect field improperly initialized");
3213 CXXMemberInit
3214 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3215 Loc, Loc,
3216 MemberInit.takeAs<Expr>(),
3217 Loc);
3218 } else
3219 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
3220 Loc, MemberInit.takeAs<Expr>(),
3221 Loc,
3222 IndexVariables.data(),
3223 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00003224 return false;
3225 }
3226
Richard Smith07b0fdc2013-03-18 21:12:30 +00003227 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
3228 "Unhandled implicit init kind!");
Anders Carlssonf6513ed2010-04-23 16:04:08 +00003229
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003230 QualType FieldBaseElementType =
3231 SemaRef.Context.getBaseElementType(Field->getType());
3232
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003233 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003234 InitializedEntity InitEntity
3235 = Indirect? InitializedEntity::InitializeMember(Indirect)
3236 : InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00003237 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00003238 InitializationKind::CreateDefault(Loc);
Dmitri Gribenko62ed8892013-05-05 20:40:26 +00003239
3240 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3241 ExprResult MemberInit =
3242 InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
John McCall9ae2f072010-08-23 23:25:46 +00003243
Douglas Gregor53c374f2010-12-07 00:41:46 +00003244 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003245 if (MemberInit.isInvalid())
3246 return true;
3247
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003248 if (Indirect)
3249 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3250 Indirect, Loc,
3251 Loc,
3252 MemberInit.get(),
3253 Loc);
3254 else
3255 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3256 Field, Loc, Loc,
3257 MemberInit.get(),
3258 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003259 return false;
3260 }
Anders Carlsson114a2972010-04-23 03:07:47 +00003261
Sean Hunt1f2f3842011-05-17 00:19:05 +00003262 if (!Field->getParent()->isUnion()) {
3263 if (FieldBaseElementType->isReferenceType()) {
3264 SemaRef.Diag(Constructor->getLocation(),
3265 diag::err_uninitialized_member_in_ctor)
3266 << (int)Constructor->isImplicit()
3267 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3268 << 0 << Field->getDeclName();
3269 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3270 return true;
3271 }
Anders Carlsson114a2972010-04-23 03:07:47 +00003272
Sean Hunt1f2f3842011-05-17 00:19:05 +00003273 if (FieldBaseElementType.isConstQualified()) {
3274 SemaRef.Diag(Constructor->getLocation(),
3275 diag::err_uninitialized_member_in_ctor)
3276 << (int)Constructor->isImplicit()
3277 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3278 << 1 << Field->getDeclName();
3279 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3280 return true;
3281 }
Anders Carlsson114a2972010-04-23 03:07:47 +00003282 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003283
David Blaikie4e4d0842012-03-11 07:00:24 +00003284 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00003285 FieldBaseElementType->isObjCRetainableType() &&
3286 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3287 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
Douglas Gregor3fe52ff2012-07-23 04:23:39 +00003288 // ARC:
John McCallf85e1932011-06-15 23:02:42 +00003289 // Default-initialize Objective-C pointers to NULL.
3290 CXXMemberInit
3291 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3292 Loc, Loc,
3293 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3294 Loc);
3295 return false;
3296 }
3297
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003298 // Nothing to initialize.
3299 CXXMemberInit = 0;
3300 return false;
3301}
John McCallf1860e52010-05-20 23:23:51 +00003302
3303namespace {
3304struct BaseAndFieldInfo {
3305 Sema &S;
3306 CXXConstructorDecl *Ctor;
3307 bool AnyErrorsInInits;
3308 ImplicitInitializerKind IIK;
Sean Huntcbb67482011-01-08 20:30:50 +00003309 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003310 SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallf1860e52010-05-20 23:23:51 +00003311
3312 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3313 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003314 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3315 if (Generated && Ctor->isCopyConstructor())
John McCallf1860e52010-05-20 23:23:51 +00003316 IIK = IIK_Copy;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003317 else if (Generated && Ctor->isMoveConstructor())
3318 IIK = IIK_Move;
Richard Smith07b0fdc2013-03-18 21:12:30 +00003319 else if (Ctor->getInheritedConstructor())
3320 IIK = IIK_Inherit;
John McCallf1860e52010-05-20 23:23:51 +00003321 else
3322 IIK = IIK_Default;
3323 }
Douglas Gregorf4853882011-11-28 20:03:15 +00003324
3325 bool isImplicitCopyOrMove() const {
3326 switch (IIK) {
3327 case IIK_Copy:
3328 case IIK_Move:
3329 return true;
3330
3331 case IIK_Default:
Richard Smith07b0fdc2013-03-18 21:12:30 +00003332 case IIK_Inherit:
Douglas Gregorf4853882011-11-28 20:03:15 +00003333 return false;
3334 }
David Blaikie30263482012-01-20 21:50:17 +00003335
3336 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregorf4853882011-11-28 20:03:15 +00003337 }
Richard Smith0b8220a2012-08-07 21:30:42 +00003338
3339 bool addFieldInitializer(CXXCtorInitializer *Init) {
3340 AllToInit.push_back(Init);
3341
3342 // Check whether this initializer makes the field "used".
Richard Smithc3bf52c2013-04-20 22:23:05 +00003343 if (Init->getInit()->HasSideEffects(S.Context))
Richard Smith0b8220a2012-08-07 21:30:42 +00003344 S.UnusedPrivateFields.remove(Init->getAnyMember());
3345
3346 return false;
3347 }
John McCallf1860e52010-05-20 23:23:51 +00003348};
3349}
3350
Richard Smitha4950662011-09-19 13:34:43 +00003351/// \brief Determine whether the given indirect field declaration is somewhere
3352/// within an anonymous union.
3353static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
3354 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
3355 CEnd = F->chain_end();
3356 C != CEnd; ++C)
3357 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
3358 if (Record->isUnion())
3359 return true;
3360
3361 return false;
3362}
3363
Douglas Gregorddb21472011-11-02 23:04:16 +00003364/// \brief Determine whether the given type is an incomplete or zero-lenfgth
3365/// array type.
3366static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3367 if (T->isIncompleteArrayType())
3368 return true;
3369
3370 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3371 if (!ArrayT->getSize())
3372 return true;
3373
3374 T = ArrayT->getElementType();
3375 }
3376
3377 return false;
3378}
3379
Richard Smith7a614d82011-06-11 17:19:42 +00003380static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003381 FieldDecl *Field,
3382 IndirectFieldDecl *Indirect = 0) {
Eli Friedman5fb478b2013-06-28 21:07:41 +00003383 if (Field->isInvalidDecl())
3384 return false;
John McCallf1860e52010-05-20 23:23:51 +00003385
Chandler Carruthe861c602010-06-30 02:59:29 +00003386 // Overwhelmingly common case: we have a direct initializer for this field.
Richard Smith0b8220a2012-08-07 21:30:42 +00003387 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field))
3388 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00003389
Richard Smith0b8220a2012-08-07 21:30:42 +00003390 // C++11 [class.base.init]p8: if the entity is a non-static data member that
Richard Smith7a614d82011-06-11 17:19:42 +00003391 // has a brace-or-equal-initializer, the entity is initialized as specified
3392 // in [dcl.init].
Douglas Gregorf4853882011-11-28 20:03:15 +00003393 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Richard Smithc3bf52c2013-04-20 22:23:05 +00003394 Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context,
3395 Info.Ctor->getLocation(), Field);
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003396 CXXCtorInitializer *Init;
3397 if (Indirect)
3398 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3399 SourceLocation(),
Richard Smithc3bf52c2013-04-20 22:23:05 +00003400 SourceLocation(), DIE,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003401 SourceLocation());
3402 else
3403 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3404 SourceLocation(),
Richard Smithc3bf52c2013-04-20 22:23:05 +00003405 SourceLocation(), DIE,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003406 SourceLocation());
Richard Smith0b8220a2012-08-07 21:30:42 +00003407 return Info.addFieldInitializer(Init);
Richard Smith7a614d82011-06-11 17:19:42 +00003408 }
3409
Richard Smithc115f632011-09-18 11:14:50 +00003410 // Don't build an implicit initializer for union members if none was
3411 // explicitly specified.
Richard Smitha4950662011-09-19 13:34:43 +00003412 if (Field->getParent()->isUnion() ||
3413 (Indirect && isWithinAnonymousUnion(Indirect)))
Richard Smithc115f632011-09-18 11:14:50 +00003414 return false;
3415
Douglas Gregorddb21472011-11-02 23:04:16 +00003416 // Don't initialize incomplete or zero-length arrays.
3417 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3418 return false;
3419
John McCallf1860e52010-05-20 23:23:51 +00003420 // Don't try to build an implicit initializer if there were semantic
3421 // errors in any of the initializers (and therefore we might be
3422 // missing some that the user actually wrote).
Eli Friedman5fb478b2013-06-28 21:07:41 +00003423 if (Info.AnyErrorsInInits)
John McCallf1860e52010-05-20 23:23:51 +00003424 return false;
3425
Sean Huntcbb67482011-01-08 20:30:50 +00003426 CXXCtorInitializer *Init = 0;
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003427 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3428 Indirect, Init))
John McCallf1860e52010-05-20 23:23:51 +00003429 return true;
John McCallf1860e52010-05-20 23:23:51 +00003430
Richard Smith0b8220a2012-08-07 21:30:42 +00003431 if (!Init)
3432 return false;
Francois Pichet00eb3f92010-12-04 09:14:42 +00003433
Richard Smith0b8220a2012-08-07 21:30:42 +00003434 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00003435}
Sean Hunt059ce0d2011-05-01 07:04:31 +00003436
3437bool
3438Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3439 CXXCtorInitializer *Initializer) {
Sean Huntfe57eef2011-05-04 05:57:24 +00003440 assert(Initializer->isDelegatingInitializer());
Sean Hunt01aacc02011-05-03 20:43:02 +00003441 Constructor->setNumCtorInitializers(1);
3442 CXXCtorInitializer **initializer =
3443 new (Context) CXXCtorInitializer*[1];
3444 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3445 Constructor->setCtorInitializers(initializer);
3446
Sean Huntb76af9c2011-05-03 23:05:34 +00003447 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00003448 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Sean Huntb76af9c2011-05-03 23:05:34 +00003449 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3450 }
3451
Sean Huntc1598702011-05-05 00:05:47 +00003452 DelegatingCtorDecls.push_back(Constructor);
Sean Huntfe57eef2011-05-04 05:57:24 +00003453
Sean Hunt059ce0d2011-05-01 07:04:31 +00003454 return false;
3455}
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003456
David Blaikie93c86172013-01-17 05:26:25 +00003457bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3458 ArrayRef<CXXCtorInitializer *> Initializers) {
Douglas Gregord836c0d2011-09-22 23:04:35 +00003459 if (Constructor->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003460 // Just store the initializers as written, they will be checked during
3461 // instantiation.
David Blaikie93c86172013-01-17 05:26:25 +00003462 if (!Initializers.empty()) {
3463 Constructor->setNumCtorInitializers(Initializers.size());
Sean Huntcbb67482011-01-08 20:30:50 +00003464 CXXCtorInitializer **baseOrMemberInitializers =
David Blaikie93c86172013-01-17 05:26:25 +00003465 new (Context) CXXCtorInitializer*[Initializers.size()];
3466 memcpy(baseOrMemberInitializers, Initializers.data(),
3467 Initializers.size() * sizeof(CXXCtorInitializer*));
Sean Huntcbb67482011-01-08 20:30:50 +00003468 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003469 }
Richard Smith54b3ba82012-09-25 00:23:05 +00003470
3471 // Let template instantiation know whether we had errors.
3472 if (AnyErrors)
3473 Constructor->setInvalidDecl();
3474
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003475 return false;
3476 }
3477
John McCallf1860e52010-05-20 23:23:51 +00003478 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00003479
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003480 // We need to build the initializer AST according to order of construction
3481 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00003482 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00003483 if (!ClassDecl)
3484 return true;
3485
Eli Friedman80c30da2009-11-09 19:20:36 +00003486 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003487
David Blaikie93c86172013-01-17 05:26:25 +00003488 for (unsigned i = 0; i < Initializers.size(); i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003489 CXXCtorInitializer *Member = Initializers[i];
Richard Smithcbc820a2013-07-22 02:56:56 +00003490
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003491 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00003492 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003493 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00003494 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003495 }
3496
Anders Carlsson711f34a2010-04-21 19:52:01 +00003497 // Keep track of the direct virtual bases.
3498 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
3499 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
3500 E = ClassDecl->bases_end(); I != E; ++I) {
3501 if (I->isVirtual())
3502 DirectVBases.insert(I);
3503 }
3504
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003505 // Push virtual bases before others.
3506 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3507 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
3508
Sean Huntcbb67482011-01-08 20:30:50 +00003509 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00003510 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
Richard Smithcbc820a2013-07-22 02:56:56 +00003511 // [class.base.init]p7, per DR257:
3512 // A mem-initializer where the mem-initializer-id names a virtual base
3513 // class is ignored during execution of a constructor of any class that
3514 // is not the most derived class.
3515 if (ClassDecl->isAbstract()) {
3516 // FIXME: Provide a fixit to remove the base specifier. This requires
3517 // tracking the location of the associated comma for a base specifier.
3518 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
3519 << VBase->getType() << ClassDecl;
3520 DiagnoseAbstractType(ClassDecl);
3521 }
3522
John McCallf1860e52010-05-20 23:23:51 +00003523 Info.AllToInit.push_back(Value);
Richard Smithcbc820a2013-07-22 02:56:56 +00003524 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
3525 // [class.base.init]p8, per DR257:
3526 // If a given [...] base class is not named by a mem-initializer-id
3527 // [...] and the entity is not a virtual base class of an abstract
3528 // class, then [...] the entity is default-initialized.
Anders Carlsson711f34a2010-04-21 19:52:01 +00003529 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00003530 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003531 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Richard Smithcbc820a2013-07-22 02:56:56 +00003532 VBase, IsInheritedVirtualBase,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003533 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003534 HadError = true;
3535 continue;
3536 }
Anders Carlsson84688f22010-04-20 23:11:20 +00003537
John McCallf1860e52010-05-20 23:23:51 +00003538 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003539 }
3540 }
Mike Stump1eb44332009-09-09 15:08:12 +00003541
John McCallf1860e52010-05-20 23:23:51 +00003542 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003543 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3544 E = ClassDecl->bases_end(); Base != E; ++Base) {
3545 // Virtuals are in the virtual base list and already constructed.
3546 if (Base->isVirtual())
3547 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00003548
Sean Huntcbb67482011-01-08 20:30:50 +00003549 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00003550 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
3551 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003552 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00003553 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003554 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003555 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00003556 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003557 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003558 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003559 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00003560
John McCallf1860e52010-05-20 23:23:51 +00003561 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003562 }
3563 }
Mike Stump1eb44332009-09-09 15:08:12 +00003564
John McCallf1860e52010-05-20 23:23:51 +00003565 // Fields.
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003566 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
3567 MemEnd = ClassDecl->decls_end();
3568 Mem != MemEnd; ++Mem) {
3569 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
Douglas Gregord61db332011-10-10 17:22:13 +00003570 // C++ [class.bit]p2:
3571 // A declaration for a bit-field that omits the identifier declares an
3572 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
3573 // initialized.
3574 if (F->isUnnamedBitfield())
3575 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003576
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003577 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003578 // handle anonymous struct/union fields based on their individual
3579 // indirect fields.
Richard Smith07b0fdc2013-03-18 21:12:30 +00003580 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003581 continue;
3582
3583 if (CollectFieldInitializer(*this, Info, F))
3584 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003585 continue;
3586 }
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003587
3588 // Beyond this point, we only consider default initialization.
Richard Smith07b0fdc2013-03-18 21:12:30 +00003589 if (Info.isImplicitCopyOrMove())
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003590 continue;
3591
3592 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
3593 if (F->getType()->isIncompleteArrayType()) {
3594 assert(ClassDecl->hasFlexibleArrayMember() &&
3595 "Incomplete array type is not valid");
3596 continue;
3597 }
3598
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003599 // Initialize each field of an anonymous struct individually.
3600 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3601 HadError = true;
3602
3603 continue;
3604 }
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003605 }
Mike Stump1eb44332009-09-09 15:08:12 +00003606
David Blaikie93c86172013-01-17 05:26:25 +00003607 unsigned NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003608 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00003609 Constructor->setNumCtorInitializers(NumInitializers);
3610 CXXCtorInitializer **baseOrMemberInitializers =
3611 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00003612 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00003613 NumInitializers * sizeof(CXXCtorInitializer*));
3614 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00003615
John McCallef027fe2010-03-16 21:39:52 +00003616 // Constructors implicitly reference the base and member
3617 // destructors.
3618 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3619 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003620 }
Eli Friedman80c30da2009-11-09 19:20:36 +00003621
3622 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003623}
3624
David Blaikieee000bb2013-01-17 08:49:22 +00003625static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003626 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
David Blaikieee000bb2013-01-17 08:49:22 +00003627 const RecordDecl *RD = RT->getDecl();
3628 if (RD->isAnonymousStructOrUnion()) {
3629 for (RecordDecl::field_iterator Field = RD->field_begin(),
3630 E = RD->field_end(); Field != E; ++Field)
3631 PopulateKeysForFields(*Field, IdealInits);
3632 return;
3633 }
Eli Friedman6347f422009-07-21 19:28:10 +00003634 }
David Blaikieee000bb2013-01-17 08:49:22 +00003635 IdealInits.push_back(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00003636}
3637
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003638static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
3639 return Context.getCanonicalType(BaseType).getTypePtr();
Anders Carlssoncdc83c72009-09-01 06:22:14 +00003640}
3641
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003642static const void *GetKeyForMember(ASTContext &Context,
3643 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003644 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00003645 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00003646
David Blaikieee000bb2013-01-17 08:49:22 +00003647 return Member->getAnyMember();
Eli Friedman6347f422009-07-21 19:28:10 +00003648}
3649
David Blaikie93c86172013-01-17 05:26:25 +00003650static void DiagnoseBaseOrMemInitializerOrder(
3651 Sema &SemaRef, const CXXConstructorDecl *Constructor,
3652 ArrayRef<CXXCtorInitializer *> Inits) {
John McCalld6ca8da2010-04-10 07:37:23 +00003653 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00003654 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003655
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003656 // Don't check initializers order unless the warning is enabled at the
3657 // location of at least one initializer.
3658 bool ShouldCheckOrder = false;
David Blaikie93c86172013-01-17 05:26:25 +00003659 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003660 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003661 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3662 Init->getSourceLocation())
David Blaikied6471f72011-09-25 23:23:43 +00003663 != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003664 ShouldCheckOrder = true;
3665 break;
3666 }
3667 }
3668 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003669 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003670
John McCalld6ca8da2010-04-10 07:37:23 +00003671 // Build the list of bases and members in the order that they'll
3672 // actually be initialized. The explicit initializers should be in
3673 // this same order but may be missing things.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003674 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00003675
Anders Carlsson071d6102010-04-02 03:38:04 +00003676 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3677
John McCalld6ca8da2010-04-10 07:37:23 +00003678 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003679 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003680 ClassDecl->vbases_begin(),
3681 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00003682 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003683
John McCalld6ca8da2010-04-10 07:37:23 +00003684 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003685 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003686 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003687 if (Base->isVirtual())
3688 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00003689 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003690 }
Mike Stump1eb44332009-09-09 15:08:12 +00003691
John McCalld6ca8da2010-04-10 07:37:23 +00003692 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003693 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Douglas Gregord61db332011-10-10 17:22:13 +00003694 E = ClassDecl->field_end(); Field != E; ++Field) {
3695 if (Field->isUnnamedBitfield())
3696 continue;
3697
David Blaikieee000bb2013-01-17 08:49:22 +00003698 PopulateKeysForFields(*Field, IdealInitKeys);
Douglas Gregord61db332011-10-10 17:22:13 +00003699 }
3700
John McCalld6ca8da2010-04-10 07:37:23 +00003701 unsigned NumIdealInits = IdealInitKeys.size();
3702 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00003703
Sean Huntcbb67482011-01-08 20:30:50 +00003704 CXXCtorInitializer *PrevInit = 0;
David Blaikie93c86172013-01-17 05:26:25 +00003705 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003706 CXXCtorInitializer *Init = Inits[InitIndex];
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003707 const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00003708
3709 // Scan forward to try to find this initializer in the idealized
3710 // initializers list.
3711 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3712 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003713 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003714
3715 // If we didn't find this initializer, it must be because we
3716 // scanned past it on a previous iteration. That can only
3717 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00003718 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00003719 Sema::SemaDiagnosticBuilder D =
3720 SemaRef.Diag(PrevInit->getSourceLocation(),
3721 diag::warn_initializer_out_of_order);
3722
Francois Pichet00eb3f92010-12-04 09:14:42 +00003723 if (PrevInit->isAnyMemberInitializer())
3724 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003725 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003726 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003727
Francois Pichet00eb3f92010-12-04 09:14:42 +00003728 if (Init->isAnyMemberInitializer())
3729 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003730 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003731 D << 1 << Init->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003732
3733 // Move back to the initializer's location in the ideal list.
3734 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3735 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003736 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003737
3738 assert(IdealIndex != NumIdealInits &&
3739 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003740 }
John McCalld6ca8da2010-04-10 07:37:23 +00003741
3742 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003743 }
Anders Carlssona7b35212009-03-25 02:58:17 +00003744}
3745
John McCall3c3ccdb2010-04-10 09:28:51 +00003746namespace {
3747bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003748 CXXCtorInitializer *Init,
3749 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003750 if (!PrevInit) {
3751 PrevInit = Init;
3752 return false;
3753 }
3754
Douglas Gregordc392c12013-03-25 23:28:23 +00003755 if (FieldDecl *Field = Init->getAnyMember())
John McCall3c3ccdb2010-04-10 09:28:51 +00003756 S.Diag(Init->getSourceLocation(),
3757 diag::err_multiple_mem_initialization)
3758 << Field->getDeclName()
3759 << Init->getSourceRange();
3760 else {
John McCallf4c73712011-01-19 06:33:43 +00003761 const Type *BaseClass = Init->getBaseClass();
John McCall3c3ccdb2010-04-10 09:28:51 +00003762 assert(BaseClass && "neither field nor base");
3763 S.Diag(Init->getSourceLocation(),
3764 diag::err_multiple_base_initialization)
3765 << QualType(BaseClass, 0)
3766 << Init->getSourceRange();
3767 }
3768 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3769 << 0 << PrevInit->getSourceRange();
3770
3771 return true;
3772}
3773
Sean Huntcbb67482011-01-08 20:30:50 +00003774typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00003775typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3776
3777bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003778 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00003779 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003780 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003781 RecordDecl *Parent = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003782 NamedDecl *Child = Field;
David Blaikie6fe29652011-11-17 06:01:57 +00003783
3784 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003785 if (Parent->isUnion()) {
3786 UnionEntry &En = Unions[Parent];
3787 if (En.first && En.first != Child) {
3788 S.Diag(Init->getSourceLocation(),
3789 diag::err_multiple_mem_union_initialization)
3790 << Field->getDeclName()
3791 << Init->getSourceRange();
3792 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3793 << 0 << En.second->getSourceRange();
3794 return true;
David Blaikie5bbe8162011-11-12 20:54:14 +00003795 }
3796 if (!En.first) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003797 En.first = Child;
3798 En.second = Init;
3799 }
David Blaikie6fe29652011-11-17 06:01:57 +00003800 if (!Parent->isAnonymousStructOrUnion())
3801 return false;
John McCall3c3ccdb2010-04-10 09:28:51 +00003802 }
3803
3804 Child = Parent;
3805 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie6fe29652011-11-17 06:01:57 +00003806 }
John McCall3c3ccdb2010-04-10 09:28:51 +00003807
3808 return false;
3809}
3810}
3811
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003812/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00003813void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003814 SourceLocation ColonLoc,
David Blaikie93c86172013-01-17 05:26:25 +00003815 ArrayRef<CXXCtorInitializer*> MemInits,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003816 bool AnyErrors) {
3817 if (!ConstructorDecl)
3818 return;
3819
3820 AdjustDeclIfTemplate(ConstructorDecl);
3821
3822 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003823 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003824
3825 if (!Constructor) {
3826 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3827 return;
3828 }
3829
John McCall3c3ccdb2010-04-10 09:28:51 +00003830 // Mapping for the duplicate initializers check.
3831 // For member initializers, this is keyed with a FieldDecl*.
3832 // For base initializers, this is keyed with a Type*.
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003833 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00003834
3835 // Mapping for the inconsistent anonymous-union initializers check.
3836 RedundantUnionMap MemberUnions;
3837
Anders Carlssonea356fb2010-04-02 05:42:15 +00003838 bool HadError = false;
David Blaikie93c86172013-01-17 05:26:25 +00003839 for (unsigned i = 0; i < MemInits.size(); i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003840 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003841
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00003842 // Set the source order index.
3843 Init->setSourceOrder(i);
3844
Francois Pichet00eb3f92010-12-04 09:14:42 +00003845 if (Init->isAnyMemberInitializer()) {
3846 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003847 if (CheckRedundantInit(*this, Init, Members[Field]) ||
3848 CheckRedundantUnionInit(*this, Init, MemberUnions))
3849 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003850 } else if (Init->isBaseInitializer()) {
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003851 const void *Key =
3852 GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
John McCall3c3ccdb2010-04-10 09:28:51 +00003853 if (CheckRedundantInit(*this, Init, Members[Key]))
3854 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003855 } else {
3856 assert(Init->isDelegatingInitializer());
3857 // This must be the only initializer
David Blaikie93c86172013-01-17 05:26:25 +00003858 if (MemInits.size() != 1) {
Richard Smitha6ddea62012-09-14 18:21:10 +00003859 Diag(Init->getSourceLocation(),
Sean Hunt41717662011-02-26 19:13:13 +00003860 diag::err_delegating_initializer_alone)
Richard Smitha6ddea62012-09-14 18:21:10 +00003861 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
Sean Hunt059ce0d2011-05-01 07:04:31 +00003862 // We will treat this as being the only initializer.
Sean Hunt41717662011-02-26 19:13:13 +00003863 }
Sean Huntfe57eef2011-05-04 05:57:24 +00003864 SetDelegatingInitializer(Constructor, MemInits[i]);
Sean Hunt059ce0d2011-05-01 07:04:31 +00003865 // Return immediately as the initializer is set.
3866 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003867 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003868 }
3869
Anders Carlssonea356fb2010-04-02 05:42:15 +00003870 if (HadError)
3871 return;
3872
David Blaikie93c86172013-01-17 05:26:25 +00003873 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00003874
David Blaikie93c86172013-01-17 05:26:25 +00003875 SetCtorInitializers(Constructor, AnyErrors, MemInits);
Richard Trieu225e9822013-09-16 21:54:53 +00003876
Richard Trieu858d2ba2013-10-25 00:56:00 +00003877 DiagnoseUninitializedFields(*this, Constructor);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003878}
3879
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003880void
John McCallef027fe2010-03-16 21:39:52 +00003881Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3882 CXXRecordDecl *ClassDecl) {
Richard Smith416f63e2011-09-18 12:11:43 +00003883 // Ignore dependent contexts. Also ignore unions, since their members never
3884 // have destructors implicitly called.
3885 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003886 return;
John McCall58e6f342010-03-16 05:22:47 +00003887
3888 // FIXME: all the access-control diagnostics are positioned on the
3889 // field/base declaration. That's probably good; that said, the
3890 // user might reasonably want to know why the destructor is being
3891 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003892
Anders Carlsson9f853df2009-11-17 04:44:12 +00003893 // Non-static data members.
3894 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3895 E = ClassDecl->field_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00003896 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00003897 if (Field->isInvalidDecl())
3898 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003899
3900 // Don't destroy incomplete or zero-length arrays.
3901 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3902 continue;
3903
Anders Carlsson9f853df2009-11-17 04:44:12 +00003904 QualType FieldType = Context.getBaseElementType(Field->getType());
3905
3906 const RecordType* RT = FieldType->getAs<RecordType>();
3907 if (!RT)
3908 continue;
3909
3910 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003911 if (FieldClassDecl->isInvalidDecl())
3912 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003913 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003914 continue;
Richard Smith9a561d52012-02-26 09:11:52 +00003915 // The destructor for an implicit anonymous union member is never invoked.
3916 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3917 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00003918
Douglas Gregordb89f282010-07-01 22:47:18 +00003919 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003920 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003921 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003922 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00003923 << Field->getDeclName()
3924 << FieldType);
3925
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003926 MarkFunctionReferenced(Location, Dtor);
Richard Smith213d70b2012-02-18 04:13:32 +00003927 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003928 }
3929
John McCall58e6f342010-03-16 05:22:47 +00003930 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3931
Anders Carlsson9f853df2009-11-17 04:44:12 +00003932 // Bases.
3933 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3934 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00003935 // Bases are always records in a well-formed non-dependent class.
3936 const RecordType *RT = Base->getType()->getAs<RecordType>();
3937
3938 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003939 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00003940 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003941
John McCall58e6f342010-03-16 05:22:47 +00003942 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003943 // If our base class is invalid, we probably can't get its dtor anyway.
3944 if (BaseClassDecl->isInvalidDecl())
3945 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003946 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003947 continue;
John McCall58e6f342010-03-16 05:22:47 +00003948
Douglas Gregordb89f282010-07-01 22:47:18 +00003949 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003950 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003951
3952 // FIXME: caret should be on the start of the class name
Daniel Dunbar96a00142012-03-09 18:35:03 +00003953 CheckDestructorAccess(Base->getLocStart(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003954 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00003955 << Base->getType()
John McCallb9abd8722012-04-07 03:04:20 +00003956 << Base->getSourceRange(),
3957 Context.getTypeDeclType(ClassDecl));
Anders Carlsson9f853df2009-11-17 04:44:12 +00003958
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003959 MarkFunctionReferenced(Location, Dtor);
Richard Smith213d70b2012-02-18 04:13:32 +00003960 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003961 }
3962
3963 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003964 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3965 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00003966
3967 // Bases are always records in a well-formed non-dependent class.
John McCall63f55782012-04-09 21:51:56 +00003968 const RecordType *RT = VBase->getType()->castAs<RecordType>();
John McCall58e6f342010-03-16 05:22:47 +00003969
3970 // Ignore direct virtual bases.
3971 if (DirectVirtualBases.count(RT))
3972 continue;
3973
John McCall58e6f342010-03-16 05:22:47 +00003974 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003975 // If our base class is invalid, we probably can't get its dtor anyway.
3976 if (BaseClassDecl->isInvalidDecl())
3977 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003978 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003979 continue;
John McCall58e6f342010-03-16 05:22:47 +00003980
Douglas Gregordb89f282010-07-01 22:47:18 +00003981 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003982 assert(Dtor && "No dtor found for BaseClassDecl!");
David Majnemer2f686692013-06-22 06:43:58 +00003983 if (CheckDestructorAccess(
3984 ClassDecl->getLocation(), Dtor,
3985 PDiag(diag::err_access_dtor_vbase)
3986 << Context.getTypeDeclType(ClassDecl) << VBase->getType(),
3987 Context.getTypeDeclType(ClassDecl)) ==
3988 AR_accessible) {
3989 CheckDerivedToBaseConversion(
3990 Context.getTypeDeclType(ClassDecl), VBase->getType(),
3991 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
3992 SourceRange(), DeclarationName(), 0);
3993 }
John McCall58e6f342010-03-16 05:22:47 +00003994
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003995 MarkFunctionReferenced(Location, Dtor);
Richard Smith213d70b2012-02-18 04:13:32 +00003996 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003997 }
3998}
3999
John McCalld226f652010-08-21 09:40:31 +00004000void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00004001 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00004002 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004003
Mike Stump1eb44332009-09-09 15:08:12 +00004004 if (CXXConstructorDecl *Constructor
Richard Trieu858d2ba2013-10-25 00:56:00 +00004005 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
David Blaikie93c86172013-01-17 05:26:25 +00004006 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
Richard Trieu858d2ba2013-10-25 00:56:00 +00004007 DiagnoseUninitializedFields(*this, Constructor);
4008 }
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00004009}
4010
Mike Stump1eb44332009-09-09 15:08:12 +00004011bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00004012 unsigned DiagID, AbstractDiagSelID SelID) {
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00004013 class NonAbstractTypeDiagnoser : public TypeDiagnoser {
4014 unsigned DiagID;
4015 AbstractDiagSelID SelID;
4016
4017 public:
4018 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
4019 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00004020
4021 void diagnose(Sema &S, SourceLocation Loc, QualType T) LLVM_OVERRIDE {
Eli Friedman2217f852012-08-14 02:06:07 +00004022 if (Suppressed) return;
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00004023 if (SelID == -1)
4024 S.Diag(Loc, DiagID) << T;
4025 else
4026 S.Diag(Loc, DiagID) << SelID << T;
4027 }
4028 } Diagnoser(DiagID, SelID);
4029
4030 return RequireNonAbstractType(Loc, T, Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00004031}
4032
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00004033bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00004034 TypeDiagnoser &Diagnoser) {
David Blaikie4e4d0842012-03-11 07:00:24 +00004035 if (!getLangOpts().CPlusPlus)
Anders Carlsson4681ebd2009-03-22 20:18:17 +00004036 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004037
Anders Carlsson11f21a02009-03-23 19:10:31 +00004038 if (const ArrayType *AT = Context.getAsArrayType(T))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00004039 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00004040
Ted Kremenek6217b802009-07-29 21:53:49 +00004041 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00004042 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00004043 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00004044 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00004045
Anders Carlsson5eff73c2009-03-24 01:46:45 +00004046 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00004047 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00004048 }
Mike Stump1eb44332009-09-09 15:08:12 +00004049
Ted Kremenek6217b802009-07-29 21:53:49 +00004050 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00004051 if (!RT)
4052 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004053
John McCall86ff3082010-02-04 22:26:26 +00004054 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00004055
John McCall94c3b562010-08-18 09:41:07 +00004056 // We can't answer whether something is abstract until it has a
4057 // definition. If it's currently being defined, we'll walk back
4058 // over all the declarations when we have a full definition.
4059 const CXXRecordDecl *Def = RD->getDefinition();
4060 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00004061 return false;
4062
Anders Carlsson4681ebd2009-03-22 20:18:17 +00004063 if (!RD->isAbstract())
4064 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004065
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00004066 Diagnoser.diagnose(*this, Loc, T);
John McCall94c3b562010-08-18 09:41:07 +00004067 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00004068
John McCall94c3b562010-08-18 09:41:07 +00004069 return true;
4070}
4071
4072void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
4073 // Check if we've already emitted the list of pure virtual functions
4074 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00004075 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00004076 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004077
Richard Smithcbc820a2013-07-22 02:56:56 +00004078 // If the diagnostic is suppressed, don't emit the notes. We're only
4079 // going to emit them once, so try to attach them to a diagnostic we're
4080 // actually going to show.
4081 if (Diags.isLastDiagnosticIgnored())
4082 return;
4083
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00004084 CXXFinalOverriderMap FinalOverriders;
4085 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00004086
Anders Carlssonffdb2d22010-06-03 01:00:02 +00004087 // Keep a set of seen pure methods so we won't diagnose the same method
4088 // more than once.
4089 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
4090
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00004091 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
4092 MEnd = FinalOverriders.end();
4093 M != MEnd;
4094 ++M) {
4095 for (OverridingMethods::iterator SO = M->second.begin(),
4096 SOEnd = M->second.end();
4097 SO != SOEnd; ++SO) {
4098 // C++ [class.abstract]p4:
4099 // A class is abstract if it contains or inherits at least one
4100 // pure virtual function for which the final overrider is pure
4101 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00004102
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00004103 //
4104 if (SO->second.size() != 1)
4105 continue;
4106
4107 if (!SO->second.front().Method->isPure())
4108 continue;
4109
Anders Carlssonffdb2d22010-06-03 01:00:02 +00004110 if (!SeenPureMethods.insert(SO->second.front().Method))
4111 continue;
4112
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00004113 Diag(SO->second.front().Method->getLocation(),
4114 diag::note_pure_virtual_function)
Chandler Carruth45f11b72011-02-18 23:59:51 +00004115 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00004116 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00004117 }
4118
4119 if (!PureVirtualClassDiagSet)
4120 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
4121 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00004122}
4123
Anders Carlsson8211eff2009-03-24 01:19:16 +00004124namespace {
John McCall94c3b562010-08-18 09:41:07 +00004125struct AbstractUsageInfo {
4126 Sema &S;
4127 CXXRecordDecl *Record;
4128 CanQualType AbstractType;
4129 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00004130
John McCall94c3b562010-08-18 09:41:07 +00004131 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
4132 : S(S), Record(Record),
4133 AbstractType(S.Context.getCanonicalType(
4134 S.Context.getTypeDeclType(Record))),
4135 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00004136
John McCall94c3b562010-08-18 09:41:07 +00004137 void DiagnoseAbstractType() {
4138 if (Invalid) return;
4139 S.DiagnoseAbstractType(Record);
4140 Invalid = true;
4141 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00004142
John McCall94c3b562010-08-18 09:41:07 +00004143 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
4144};
4145
4146struct CheckAbstractUsage {
4147 AbstractUsageInfo &Info;
4148 const NamedDecl *Ctx;
4149
4150 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
4151 : Info(Info), Ctx(Ctx) {}
4152
4153 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4154 switch (TL.getTypeLocClass()) {
4155#define ABSTRACT_TYPELOC(CLASS, PARENT)
4156#define TYPELOC(CLASS, PARENT) \
David Blaikie39e6ab42013-02-18 22:06:02 +00004157 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
John McCall94c3b562010-08-18 09:41:07 +00004158#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00004159 }
John McCall94c3b562010-08-18 09:41:07 +00004160 }
Mike Stump1eb44332009-09-09 15:08:12 +00004161
John McCall94c3b562010-08-18 09:41:07 +00004162 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4163 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
4164 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor70191862011-02-22 23:21:06 +00004165 if (!TL.getArg(I))
4166 continue;
4167
John McCall94c3b562010-08-18 09:41:07 +00004168 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
4169 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00004170 }
John McCall94c3b562010-08-18 09:41:07 +00004171 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00004172
John McCall94c3b562010-08-18 09:41:07 +00004173 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4174 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
4175 }
Mike Stump1eb44332009-09-09 15:08:12 +00004176
John McCall94c3b562010-08-18 09:41:07 +00004177 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4178 // Visit the type parameters from a permissive context.
4179 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
4180 TemplateArgumentLoc TAL = TL.getArgLoc(I);
4181 if (TAL.getArgument().getKind() == TemplateArgument::Type)
4182 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
4183 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
4184 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00004185 }
John McCall94c3b562010-08-18 09:41:07 +00004186 }
Mike Stump1eb44332009-09-09 15:08:12 +00004187
John McCall94c3b562010-08-18 09:41:07 +00004188 // Visit pointee types from a permissive context.
4189#define CheckPolymorphic(Type) \
4190 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
4191 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
4192 }
4193 CheckPolymorphic(PointerTypeLoc)
4194 CheckPolymorphic(ReferenceTypeLoc)
4195 CheckPolymorphic(MemberPointerTypeLoc)
4196 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedmanb001de72011-10-06 23:00:33 +00004197 CheckPolymorphic(AtomicTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00004198
John McCall94c3b562010-08-18 09:41:07 +00004199 /// Handle all the types we haven't given a more specific
4200 /// implementation for above.
4201 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4202 // Every other kind of type that we haven't called out already
4203 // that has an inner type is either (1) sugar or (2) contains that
4204 // inner type in some way as a subobject.
4205 if (TypeLoc Next = TL.getNextTypeLoc())
4206 return Visit(Next, Sel);
4207
4208 // If there's no inner type and we're in a permissive context,
4209 // don't diagnose.
4210 if (Sel == Sema::AbstractNone) return;
4211
4212 // Check whether the type matches the abstract type.
4213 QualType T = TL.getType();
4214 if (T->isArrayType()) {
4215 Sel = Sema::AbstractArrayType;
4216 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00004217 }
John McCall94c3b562010-08-18 09:41:07 +00004218 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
4219 if (CT != Info.AbstractType) return;
4220
4221 // It matched; do some magic.
4222 if (Sel == Sema::AbstractArrayType) {
4223 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
4224 << T << TL.getSourceRange();
4225 } else {
4226 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
4227 << Sel << T << TL.getSourceRange();
4228 }
4229 Info.DiagnoseAbstractType();
4230 }
4231};
4232
4233void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
4234 Sema::AbstractDiagSelID Sel) {
4235 CheckAbstractUsage(*this, D).Visit(TL, Sel);
4236}
4237
4238}
4239
4240/// Check for invalid uses of an abstract type in a method declaration.
4241static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4242 CXXMethodDecl *MD) {
4243 // No need to do the check on definitions, which require that
4244 // the return/param types be complete.
Sean Hunt10620eb2011-05-06 20:44:56 +00004245 if (MD->doesThisDeclarationHaveABody())
John McCall94c3b562010-08-18 09:41:07 +00004246 return;
4247
4248 // For safety's sake, just ignore it if we don't have type source
4249 // information. This should never happen for non-implicit methods,
4250 // but...
4251 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
4252 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
4253}
4254
4255/// Check for invalid uses of an abstract type within a class definition.
4256static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4257 CXXRecordDecl *RD) {
4258 for (CXXRecordDecl::decl_iterator
4259 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
4260 Decl *D = *I;
4261 if (D->isImplicit()) continue;
4262
4263 // Methods and method templates.
4264 if (isa<CXXMethodDecl>(D)) {
4265 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
4266 } else if (isa<FunctionTemplateDecl>(D)) {
4267 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
4268 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
4269
4270 // Fields and static variables.
4271 } else if (isa<FieldDecl>(D)) {
4272 FieldDecl *FD = cast<FieldDecl>(D);
4273 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
4274 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
4275 } else if (isa<VarDecl>(D)) {
4276 VarDecl *VD = cast<VarDecl>(D);
4277 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
4278 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
4279
4280 // Nested classes and class templates.
4281 } else if (isa<CXXRecordDecl>(D)) {
4282 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
4283 } else if (isa<ClassTemplateDecl>(D)) {
4284 CheckAbstractClassUsage(Info,
4285 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
4286 }
4287 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00004288}
4289
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004290/// \brief Perform semantic checks on a class definition that has been
4291/// completing, introducing implicitly-declared members, checking for
4292/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00004293void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00004294 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004295 return;
4296
John McCall94c3b562010-08-18 09:41:07 +00004297 if (Record->isAbstract() && !Record->isInvalidDecl()) {
4298 AbstractUsageInfo Info(*this, Record);
4299 CheckAbstractClassUsage(Info, Record);
4300 }
Douglas Gregor325e5932010-04-15 00:00:53 +00004301
4302 // If this is not an aggregate type and has no user-declared constructor,
4303 // complain about any non-static data members of reference or const scalar
4304 // type, since they will never get initializers.
4305 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregor5e058eb2012-02-09 02:20:38 +00004306 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
4307 !Record->isLambda()) {
Douglas Gregor325e5932010-04-15 00:00:53 +00004308 bool Complained = false;
4309 for (RecordDecl::field_iterator F = Record->field_begin(),
4310 FEnd = Record->field_end();
4311 F != FEnd; ++F) {
Douglas Gregord61db332011-10-10 17:22:13 +00004312 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith7a614d82011-06-11 17:19:42 +00004313 continue;
4314
Douglas Gregor325e5932010-04-15 00:00:53 +00004315 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00004316 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00004317 if (!Complained) {
4318 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
4319 << Record->getTagKind() << Record;
4320 Complained = true;
4321 }
4322
4323 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4324 << F->getType()->isReferenceType()
4325 << F->getDeclName();
4326 }
4327 }
4328 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004329
Anders Carlssona5c6c2a2011-01-25 18:08:22 +00004330 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004331 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00004332
4333 if (Record->getIdentifier()) {
4334 // C++ [class.mem]p13:
4335 // If T is the name of a class, then each of the following shall have a
4336 // name different from T:
4337 // - every member of every anonymous union that is a member of class T.
4338 //
4339 // C++ [class.mem]p14:
4340 // In addition, if class T has a user-declared constructor (12.1), every
4341 // non-static data member of class T shall have a name different from T.
David Blaikie3bc93e32012-12-19 00:45:41 +00004342 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4343 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4344 ++I) {
4345 NamedDecl *D = *I;
Francois Pichet87c2e122010-11-21 06:08:52 +00004346 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4347 isa<IndirectFieldDecl>(D)) {
4348 Diag(D->getLocation(), diag::err_member_name_of_class)
4349 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00004350 break;
4351 }
Francois Pichet87c2e122010-11-21 06:08:52 +00004352 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00004353 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004354
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00004355 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregorf4b793c2011-02-19 19:14:36 +00004356 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004357 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00004358 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004359 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4360 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4361 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004362
David Majnemer7121bdb2013-10-18 00:33:31 +00004363 if (Record->isAbstract()) {
4364 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
4365 Diag(Record->getLocation(), diag::warn_abstract_final_class)
4366 << FA->isSpelledAsSealed();
4367 DiagnoseAbstractType(Record);
4368 }
David Blaikieb6b5b972012-09-21 03:21:07 +00004369 }
4370
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004371 if (!Record->isDependentType()) {
4372 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4373 MEnd = Record->method_end();
4374 M != MEnd; ++M) {
Richard Smith1d28caf2012-12-11 01:14:52 +00004375 // See if a method overloads virtual methods in a base
4376 // class without overriding any.
David Blaikie262bc182012-04-30 02:36:29 +00004377 if (!M->isStatic())
Eli Friedmandae92712013-09-05 23:51:03 +00004378 DiagnoseHiddenVirtualMethods(*M);
Richard Smith1d28caf2012-12-11 01:14:52 +00004379
4380 // Check whether the explicitly-defaulted special members are valid.
4381 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
4382 CheckExplicitlyDefaultedSpecialMember(*M);
4383
4384 // For an explicitly defaulted or deleted special member, we defer
4385 // determining triviality until the class is complete. That time is now!
4386 if (!M->isImplicit() && !M->isUserProvided()) {
4387 CXXSpecialMember CSM = getSpecialMember(*M);
4388 if (CSM != CXXInvalid) {
4389 M->setTrivial(SpecialMemberIsTrivial(*M, CSM));
4390
4391 // Inform the class that we've finished declaring this member.
4392 Record->finishedDefaultedOrDeletedMember(*M);
4393 }
4394 }
4395 }
4396 }
4397
4398 // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member
4399 // function that is not a constructor declares that member function to be
4400 // const. [...] The class of which that function is a member shall be
4401 // a literal type.
4402 //
4403 // If the class has virtual bases, any constexpr members will already have
4404 // been diagnosed by the checks performed on the member declaration, so
4405 // suppress this (less useful) diagnostic.
4406 //
4407 // We delay this until we know whether an explicitly-defaulted (or deleted)
4408 // destructor for the class is trivial.
Richard Smith80ad52f2013-01-02 11:42:31 +00004409 if (LangOpts.CPlusPlus11 && !Record->isDependentType() &&
Richard Smith1d28caf2012-12-11 01:14:52 +00004410 !Record->isLiteral() && !Record->getNumVBases()) {
4411 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4412 MEnd = Record->method_end();
4413 M != MEnd; ++M) {
4414 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) {
4415 switch (Record->getTemplateSpecializationKind()) {
4416 case TSK_ImplicitInstantiation:
4417 case TSK_ExplicitInstantiationDeclaration:
4418 case TSK_ExplicitInstantiationDefinition:
4419 // If a template instantiates to a non-literal type, but its members
4420 // instantiate to constexpr functions, the template is technically
4421 // ill-formed, but we allow it for sanity.
4422 continue;
4423
4424 case TSK_Undeclared:
4425 case TSK_ExplicitSpecialization:
4426 RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
4427 diag::err_constexpr_method_non_literal);
4428 break;
4429 }
4430
4431 // Only produce one error per class.
4432 break;
4433 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004434 }
4435 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00004436
Warren Huntb2969b12013-10-11 20:19:00 +00004437 // Check to see if we're trying to lay out a struct using the ms_struct
4438 // attribute that is dynamic.
4439 if (Record->isMsStruct(Context) && Record->isDynamicClass()) {
4440 Diag(Record->getLocation(), diag::warn_pragma_ms_struct_failed);
4441 Record->dropAttr<MsStructAttr>();
4442 }
4443
Richard Smith07b0fdc2013-03-18 21:12:30 +00004444 // Declare inheriting constructors. We do this eagerly here because:
4445 // - The standard requires an eager diagnostic for conflicting inheriting
Sebastian Redlf677ea32011-02-05 19:23:19 +00004446 // constructors from different classes.
4447 // - The lazy declaration of the other implicit constructors is so as to not
4448 // waste space and performance on classes that are not meant to be
4449 // instantiated (e.g. meta-functions). This doesn't apply to classes that
Richard Smith07b0fdc2013-03-18 21:12:30 +00004450 // have inheriting constructors.
4451 DeclareInheritingConstructors(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00004452}
4453
Richard Smith7756afa2012-06-10 05:43:50 +00004454/// Is the special member function which would be selected to perform the
4455/// specified operation on the specified class type a constexpr constructor?
4456static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4457 Sema::CXXSpecialMember CSM,
4458 bool ConstArg) {
4459 Sema::SpecialMemberOverloadResult *SMOR =
4460 S.LookupSpecialMember(ClassDecl, CSM, ConstArg,
4461 false, false, false, false);
4462 if (!SMOR || !SMOR->getMethod())
4463 // A constructor we wouldn't select can't be "involved in initializing"
4464 // anything.
4465 return true;
4466 return SMOR->getMethod()->isConstexpr();
4467}
4468
4469/// Determine whether the specified special member function would be constexpr
4470/// if it were implicitly defined.
4471static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4472 Sema::CXXSpecialMember CSM,
4473 bool ConstArg) {
Richard Smith80ad52f2013-01-02 11:42:31 +00004474 if (!S.getLangOpts().CPlusPlus11)
Richard Smith7756afa2012-06-10 05:43:50 +00004475 return false;
4476
4477 // C++11 [dcl.constexpr]p4:
4478 // In the definition of a constexpr constructor [...]
Richard Smitha8942d72013-05-07 03:19:20 +00004479 bool Ctor = true;
Richard Smith7756afa2012-06-10 05:43:50 +00004480 switch (CSM) {
4481 case Sema::CXXDefaultConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00004482 // Since default constructor lookup is essentially trivial (and cannot
4483 // involve, for instance, template instantiation), we compute whether a
4484 // defaulted default constructor is constexpr directly within CXXRecordDecl.
4485 //
4486 // This is important for performance; we need to know whether the default
4487 // constructor is constexpr to determine whether the type is a literal type.
4488 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4489
Richard Smith7756afa2012-06-10 05:43:50 +00004490 case Sema::CXXCopyConstructor:
4491 case Sema::CXXMoveConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00004492 // For copy or move constructors, we need to perform overload resolution.
Richard Smith7756afa2012-06-10 05:43:50 +00004493 break;
4494
4495 case Sema::CXXCopyAssignment:
4496 case Sema::CXXMoveAssignment:
Richard Smitha8942d72013-05-07 03:19:20 +00004497 if (!S.getLangOpts().CPlusPlus1y)
4498 return false;
4499 // In C++1y, we need to perform overload resolution.
4500 Ctor = false;
4501 break;
4502
Richard Smith7756afa2012-06-10 05:43:50 +00004503 case Sema::CXXDestructor:
4504 case Sema::CXXInvalid:
4505 return false;
4506 }
4507
4508 // -- if the class is a non-empty union, or for each non-empty anonymous
4509 // union member of a non-union class, exactly one non-static data member
4510 // shall be initialized; [DR1359]
Richard Smithd3861ce2012-06-10 07:07:24 +00004511 //
4512 // If we squint, this is guaranteed, since exactly one non-static data member
4513 // will be initialized (if the constructor isn't deleted), we just don't know
4514 // which one.
Richard Smitha8942d72013-05-07 03:19:20 +00004515 if (Ctor && ClassDecl->isUnion())
Richard Smithd3861ce2012-06-10 07:07:24 +00004516 return true;
Richard Smith7756afa2012-06-10 05:43:50 +00004517
4518 // -- the class shall not have any virtual base classes;
Richard Smitha8942d72013-05-07 03:19:20 +00004519 if (Ctor && ClassDecl->getNumVBases())
4520 return false;
4521
4522 // C++1y [class.copy]p26:
4523 // -- [the class] is a literal type, and
4524 if (!Ctor && !ClassDecl->isLiteral())
Richard Smith7756afa2012-06-10 05:43:50 +00004525 return false;
4526
4527 // -- every constructor involved in initializing [...] base class
4528 // sub-objects shall be a constexpr constructor;
Richard Smitha8942d72013-05-07 03:19:20 +00004529 // -- the assignment operator selected to copy/move each direct base
4530 // class is a constexpr function, and
Richard Smith7756afa2012-06-10 05:43:50 +00004531 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4532 BEnd = ClassDecl->bases_end();
4533 B != BEnd; ++B) {
4534 const RecordType *BaseType = B->getType()->getAs<RecordType>();
4535 if (!BaseType) continue;
4536
4537 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4538 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, ConstArg))
4539 return false;
4540 }
4541
4542 // -- every constructor involved in initializing non-static data members
4543 // [...] shall be a constexpr constructor;
4544 // -- every non-static data member and base class sub-object shall be
4545 // initialized
Richard Smitha8942d72013-05-07 03:19:20 +00004546 // -- for each non-stastic data member of X that is of class type (or array
4547 // thereof), the assignment operator selected to copy/move that member is
4548 // a constexpr function
Richard Smith7756afa2012-06-10 05:43:50 +00004549 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4550 FEnd = ClassDecl->field_end();
4551 F != FEnd; ++F) {
4552 if (F->isInvalidDecl())
4553 continue;
Richard Smithd3861ce2012-06-10 07:07:24 +00004554 if (const RecordType *RecordTy =
4555 S.Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Richard Smith7756afa2012-06-10 05:43:50 +00004556 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4557 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, ConstArg))
4558 return false;
Richard Smith7756afa2012-06-10 05:43:50 +00004559 }
4560 }
4561
4562 // All OK, it's constexpr!
4563 return true;
4564}
4565
Richard Smithb9d0b762012-07-27 04:22:15 +00004566static Sema::ImplicitExceptionSpecification
4567computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
4568 switch (S.getSpecialMember(MD)) {
4569 case Sema::CXXDefaultConstructor:
4570 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
4571 case Sema::CXXCopyConstructor:
4572 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
4573 case Sema::CXXCopyAssignment:
4574 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4575 case Sema::CXXMoveConstructor:
4576 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
4577 case Sema::CXXMoveAssignment:
4578 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
4579 case Sema::CXXDestructor:
4580 return S.ComputeDefaultedDtorExceptionSpec(MD);
4581 case Sema::CXXInvalid:
4582 break;
4583 }
Richard Smith07b0fdc2013-03-18 21:12:30 +00004584 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
4585 "only special members have implicit exception specs");
4586 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
Richard Smithb9d0b762012-07-27 04:22:15 +00004587}
4588
Richard Smithdd25e802012-07-30 23:48:14 +00004589static void
4590updateExceptionSpec(Sema &S, FunctionDecl *FD, const FunctionProtoType *FPT,
4591 const Sema::ImplicitExceptionSpecification &ExceptSpec) {
4592 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
4593 ExceptSpec.getEPI(EPI);
Richard Smith4841ca52013-04-10 05:48:59 +00004594 FD->setType(S.Context.getFunctionType(FPT->getResultType(),
4595 FPT->getArgTypes(), EPI));
Richard Smithdd25e802012-07-30 23:48:14 +00004596}
4597
Reid Kleckneref072032013-08-27 23:08:25 +00004598static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
4599 CXXMethodDecl *MD) {
4600 FunctionProtoType::ExtProtoInfo EPI;
4601
4602 // Build an exception specification pointing back at this member.
4603 EPI.ExceptionSpecType = EST_Unevaluated;
4604 EPI.ExceptionSpecDecl = MD;
4605
4606 // Set the calling convention to the default for C++ instance methods.
4607 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
4608 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
4609 /*IsCXXMethod=*/true));
4610 return EPI;
4611}
4612
Richard Smithb9d0b762012-07-27 04:22:15 +00004613void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4614 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4615 if (FPT->getExceptionSpecType() != EST_Unevaluated)
4616 return;
4617
Richard Smithdd25e802012-07-30 23:48:14 +00004618 // Evaluate the exception specification.
4619 ImplicitExceptionSpecification ExceptSpec =
4620 computeImplicitExceptionSpec(*this, Loc, MD);
4621
4622 // Update the type of the special member to use it.
4623 updateExceptionSpec(*this, MD, FPT, ExceptSpec);
4624
4625 // A user-provided destructor can be defined outside the class. When that
4626 // happens, be sure to update the exception specification on both
4627 // declarations.
4628 const FunctionProtoType *CanonicalFPT =
4629 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4630 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
4631 updateExceptionSpec(*this, MD->getCanonicalDecl(),
4632 CanonicalFPT, ExceptSpec);
Richard Smithb9d0b762012-07-27 04:22:15 +00004633}
4634
Richard Smith3003e1d2012-05-15 04:39:51 +00004635void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4636 CXXRecordDecl *RD = MD->getParent();
4637 CXXSpecialMember CSM = getSpecialMember(MD);
Sean Hunt001cad92011-05-10 00:49:42 +00004638
Richard Smith3003e1d2012-05-15 04:39:51 +00004639 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4640 "not an explicitly-defaulted special member");
Sean Hunt49634cf2011-05-13 06:10:58 +00004641
4642 // Whether this was the first-declared instance of the constructor.
Richard Smith3003e1d2012-05-15 04:39:51 +00004643 // This affects whether we implicitly add an exception spec and constexpr.
Sean Hunt2b188082011-05-14 05:23:28 +00004644 bool First = MD == MD->getCanonicalDecl();
4645
4646 bool HadError = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004647
4648 // C++11 [dcl.fct.def.default]p1:
4649 // A function that is explicitly defaulted shall
4650 // -- be a special member function (checked elsewhere),
4651 // -- have the same type (except for ref-qualifiers, and except that a
4652 // copy operation can take a non-const reference) as an implicit
4653 // declaration, and
4654 // -- not have default arguments.
4655 unsigned ExpectedParams = 1;
4656 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4657 ExpectedParams = 0;
4658 if (MD->getNumParams() != ExpectedParams) {
4659 // This also checks for default arguments: a copy or move constructor with a
4660 // default argument is classified as a default constructor, and assignment
4661 // operations and destructors can't have default arguments.
4662 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4663 << CSM << MD->getSourceRange();
Sean Hunt2b188082011-05-14 05:23:28 +00004664 HadError = true;
Richard Smith50464392012-12-07 02:10:28 +00004665 } else if (MD->isVariadic()) {
4666 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
4667 << CSM << MD->getSourceRange();
4668 HadError = true;
Sean Hunt2b188082011-05-14 05:23:28 +00004669 }
4670
Richard Smith3003e1d2012-05-15 04:39:51 +00004671 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
Sean Hunt2b188082011-05-14 05:23:28 +00004672
Richard Smith7756afa2012-06-10 05:43:50 +00004673 bool CanHaveConstParam = false;
Richard Smithac713512012-12-08 02:53:02 +00004674 if (CSM == CXXCopyConstructor)
Richard Smithacf796b2012-11-28 06:23:12 +00004675 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
Richard Smithac713512012-12-08 02:53:02 +00004676 else if (CSM == CXXCopyAssignment)
Richard Smithacf796b2012-11-28 06:23:12 +00004677 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
Sean Hunt2b188082011-05-14 05:23:28 +00004678
Richard Smith3003e1d2012-05-15 04:39:51 +00004679 QualType ReturnType = Context.VoidTy;
4680 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4681 // Check for return type matching.
4682 ReturnType = Type->getResultType();
4683 QualType ExpectedReturnType =
4684 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4685 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4686 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4687 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4688 HadError = true;
4689 }
4690
4691 // A defaulted special member cannot have cv-qualifiers.
4692 if (Type->getTypeQuals()) {
4693 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
Richard Smitha8942d72013-05-07 03:19:20 +00004694 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus1y;
Richard Smith3003e1d2012-05-15 04:39:51 +00004695 HadError = true;
4696 }
4697 }
4698
4699 // Check for parameter type matching.
4700 QualType ArgType = ExpectedParams ? Type->getArgType(0) : QualType();
Richard Smith7756afa2012-06-10 05:43:50 +00004701 bool HasConstParam = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004702 if (ExpectedParams && ArgType->isReferenceType()) {
4703 // Argument must be reference to possibly-const T.
4704 QualType ReferentType = ArgType->getPointeeType();
Richard Smith7756afa2012-06-10 05:43:50 +00004705 HasConstParam = ReferentType.isConstQualified();
Richard Smith3003e1d2012-05-15 04:39:51 +00004706
4707 if (ReferentType.isVolatileQualified()) {
4708 Diag(MD->getLocation(),
4709 diag::err_defaulted_special_member_volatile_param) << CSM;
4710 HadError = true;
4711 }
4712
Richard Smith7756afa2012-06-10 05:43:50 +00004713 if (HasConstParam && !CanHaveConstParam) {
Richard Smith3003e1d2012-05-15 04:39:51 +00004714 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4715 Diag(MD->getLocation(),
4716 diag::err_defaulted_special_member_copy_const_param)
4717 << (CSM == CXXCopyAssignment);
4718 // FIXME: Explain why this special member can't be const.
4719 } else {
4720 Diag(MD->getLocation(),
4721 diag::err_defaulted_special_member_move_const_param)
4722 << (CSM == CXXMoveAssignment);
4723 }
4724 HadError = true;
4725 }
Richard Smith3003e1d2012-05-15 04:39:51 +00004726 } else if (ExpectedParams) {
4727 // A copy assignment operator can take its argument by value, but a
4728 // defaulted one cannot.
4729 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Sean Huntbe631222011-05-17 20:44:43 +00004730 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Sean Hunt2b188082011-05-14 05:23:28 +00004731 HadError = true;
4732 }
Sean Huntbe631222011-05-17 20:44:43 +00004733
Richard Smith61802452011-12-22 02:22:31 +00004734 // C++11 [dcl.fct.def.default]p2:
4735 // An explicitly-defaulted function may be declared constexpr only if it
4736 // would have been implicitly declared as constexpr,
Richard Smith3003e1d2012-05-15 04:39:51 +00004737 // Do not apply this rule to members of class templates, since core issue 1358
4738 // makes such functions always instantiate to constexpr functions. For
Richard Smitha8942d72013-05-07 03:19:20 +00004739 // functions which cannot be constexpr (for non-constructors in C++11 and for
4740 // destructors in C++1y), this is checked elsewhere.
Richard Smith7756afa2012-06-10 05:43:50 +00004741 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4742 HasConstParam);
Richard Smitha8942d72013-05-07 03:19:20 +00004743 if ((getLangOpts().CPlusPlus1y ? !isa<CXXDestructorDecl>(MD)
4744 : isa<CXXConstructorDecl>(MD)) &&
4745 MD->isConstexpr() && !Constexpr &&
Richard Smith3003e1d2012-05-15 04:39:51 +00004746 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4747 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
Richard Smitha8942d72013-05-07 03:19:20 +00004748 // FIXME: Explain why the special member can't be constexpr.
Richard Smith3003e1d2012-05-15 04:39:51 +00004749 HadError = true;
Richard Smith61802452011-12-22 02:22:31 +00004750 }
Richard Smith1d28caf2012-12-11 01:14:52 +00004751
Richard Smith61802452011-12-22 02:22:31 +00004752 // and may have an explicit exception-specification only if it is compatible
4753 // with the exception-specification on the implicit declaration.
Richard Smith1d28caf2012-12-11 01:14:52 +00004754 if (Type->hasExceptionSpec()) {
4755 // Delay the check if this is the first declaration of the special member,
4756 // since we may not have parsed some necessary in-class initializers yet.
Richard Smith12fef492013-03-27 00:22:47 +00004757 if (First) {
4758 // If the exception specification needs to be instantiated, do so now,
4759 // before we clobber it with an EST_Unevaluated specification below.
4760 if (Type->getExceptionSpecType() == EST_Uninstantiated) {
4761 InstantiateExceptionSpec(MD->getLocStart(), MD);
4762 Type = MD->getType()->getAs<FunctionProtoType>();
4763 }
Richard Smith1d28caf2012-12-11 01:14:52 +00004764 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
Richard Smith12fef492013-03-27 00:22:47 +00004765 } else
Richard Smith1d28caf2012-12-11 01:14:52 +00004766 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
4767 }
Richard Smith61802452011-12-22 02:22:31 +00004768
4769 // If a function is explicitly defaulted on its first declaration,
4770 if (First) {
4771 // -- it is implicitly considered to be constexpr if the implicit
4772 // definition would be,
Richard Smith3003e1d2012-05-15 04:39:51 +00004773 MD->setConstexpr(Constexpr);
Richard Smith61802452011-12-22 02:22:31 +00004774
Richard Smith3003e1d2012-05-15 04:39:51 +00004775 // -- it is implicitly considered to have the same exception-specification
4776 // as if it had been implicitly declared,
Richard Smith1d28caf2012-12-11 01:14:52 +00004777 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
4778 EPI.ExceptionSpecType = EST_Unevaluated;
4779 EPI.ExceptionSpecDecl = MD;
Jordan Rosebea522f2013-03-08 21:51:21 +00004780 MD->setType(Context.getFunctionType(ReturnType,
4781 ArrayRef<QualType>(&ArgType,
4782 ExpectedParams),
4783 EPI));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004784 }
4785
Richard Smith3003e1d2012-05-15 04:39:51 +00004786 if (ShouldDeleteSpecialMember(MD, CSM)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004787 if (First) {
Richard Smith0ab5b4c2013-04-02 19:38:47 +00004788 SetDeclDeleted(MD, MD->getLocation());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004789 } else {
Richard Smith3003e1d2012-05-15 04:39:51 +00004790 // C++11 [dcl.fct.def.default]p4:
4791 // [For a] user-provided explicitly-defaulted function [...] if such a
4792 // function is implicitly defined as deleted, the program is ill-formed.
4793 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
4794 HadError = true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004795 }
4796 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004797
Richard Smith3003e1d2012-05-15 04:39:51 +00004798 if (HadError)
4799 MD->setInvalidDecl();
Sean Huntcb45a0f2011-05-12 22:46:25 +00004800}
4801
Richard Smith1d28caf2012-12-11 01:14:52 +00004802/// Check whether the exception specification provided for an
4803/// explicitly-defaulted special member matches the exception specification
4804/// that would have been generated for an implicit special member, per
4805/// C++11 [dcl.fct.def.default]p2.
4806void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
4807 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
4808 // Compute the implicit exception specification.
Reid Kleckneref072032013-08-27 23:08:25 +00004809 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
4810 /*IsCXXMethod=*/true);
4811 FunctionProtoType::ExtProtoInfo EPI(CC);
Richard Smith1d28caf2012-12-11 01:14:52 +00004812 computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI);
4813 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
Dmitri Gribenko55431692013-05-05 00:41:58 +00004814 Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smith1d28caf2012-12-11 01:14:52 +00004815
4816 // Ensure that it matches.
4817 CheckEquivalentExceptionSpec(
4818 PDiag(diag::err_incorrect_defaulted_exception_spec)
4819 << getSpecialMember(MD), PDiag(),
4820 ImplicitType, SourceLocation(),
4821 SpecifiedType, MD->getLocation());
4822}
4823
Alp Toker08235662013-10-18 05:54:19 +00004824void Sema::CheckDelayedMemberExceptionSpecs() {
4825 SmallVector<std::pair<const CXXDestructorDecl *, const CXXDestructorDecl *>,
4826 2> Checks;
4827 SmallVector<std::pair<CXXMethodDecl *, const FunctionProtoType *>, 2> Specs;
Richard Smith1d28caf2012-12-11 01:14:52 +00004828
Alp Toker08235662013-10-18 05:54:19 +00004829 std::swap(Checks, DelayedDestructorExceptionSpecChecks);
4830 std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
4831
4832 // Perform any deferred checking of exception specifications for virtual
4833 // destructors.
4834 for (unsigned i = 0, e = Checks.size(); i != e; ++i) {
4835 const CXXDestructorDecl *Dtor = Checks[i].first;
4836 assert(!Dtor->getParent()->isDependentType() &&
4837 "Should not ever add destructors of templates into the list.");
4838 CheckOverridingFunctionExceptionSpec(Dtor, Checks[i].second);
4839 }
4840
4841 // Check that any explicitly-defaulted methods have exception specifications
4842 // compatible with their implicit exception specifications.
4843 for (unsigned I = 0, N = Specs.size(); I != N; ++I)
4844 CheckExplicitlyDefaultedMemberExceptionSpec(Specs[I].first,
4845 Specs[I].second);
Richard Smith1d28caf2012-12-11 01:14:52 +00004846}
4847
Richard Smith7d5088a2012-02-18 02:02:13 +00004848namespace {
4849struct SpecialMemberDeletionInfo {
4850 Sema &S;
4851 CXXMethodDecl *MD;
4852 Sema::CXXSpecialMember CSM;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004853 bool Diagnose;
Richard Smith7d5088a2012-02-18 02:02:13 +00004854
4855 // Properties of the special member, computed for convenience.
4856 bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg;
4857 SourceLocation Loc;
4858
4859 bool AllFieldsAreConst;
4860
4861 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith6c4c36c2012-03-30 20:53:28 +00004862 Sema::CXXSpecialMember CSM, bool Diagnose)
4863 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
Richard Smith7d5088a2012-02-18 02:02:13 +00004864 IsConstructor(false), IsAssignment(false), IsMove(false),
4865 ConstArg(false), VolatileArg(false), Loc(MD->getLocation()),
4866 AllFieldsAreConst(true) {
4867 switch (CSM) {
4868 case Sema::CXXDefaultConstructor:
4869 case Sema::CXXCopyConstructor:
4870 IsConstructor = true;
4871 break;
4872 case Sema::CXXMoveConstructor:
4873 IsConstructor = true;
4874 IsMove = true;
4875 break;
4876 case Sema::CXXCopyAssignment:
4877 IsAssignment = true;
4878 break;
4879 case Sema::CXXMoveAssignment:
4880 IsAssignment = true;
4881 IsMove = true;
4882 break;
4883 case Sema::CXXDestructor:
4884 break;
4885 case Sema::CXXInvalid:
4886 llvm_unreachable("invalid special member kind");
4887 }
4888
4889 if (MD->getNumParams()) {
4890 ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4891 VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified();
4892 }
4893 }
4894
4895 bool inUnion() const { return MD->getParent()->isUnion(); }
4896
4897 /// Look up the corresponding special member in the given class.
Richard Smith517bb842012-07-18 03:51:16 +00004898 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
4899 unsigned Quals) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004900 unsigned TQ = MD->getTypeQualifiers();
Richard Smith517bb842012-07-18 03:51:16 +00004901 // cv-qualifiers on class members don't affect default ctor / dtor calls.
4902 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4903 Quals = 0;
4904 return S.LookupSpecialMember(Class, CSM,
4905 ConstArg || (Quals & Qualifiers::Const),
4906 VolatileArg || (Quals & Qualifiers::Volatile),
Richard Smith7d5088a2012-02-18 02:02:13 +00004907 MD->getRefQualifier() == RQ_RValue,
4908 TQ & Qualifiers::Const,
4909 TQ & Qualifiers::Volatile);
4910 }
4911
Richard Smith6c4c36c2012-03-30 20:53:28 +00004912 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
Richard Smith9a561d52012-02-26 09:11:52 +00004913
Richard Smith6c4c36c2012-03-30 20:53:28 +00004914 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smith7d5088a2012-02-18 02:02:13 +00004915 bool shouldDeleteForField(FieldDecl *FD);
4916 bool shouldDeleteForAllConstMembers();
Richard Smith6c4c36c2012-03-30 20:53:28 +00004917
Richard Smith517bb842012-07-18 03:51:16 +00004918 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
4919 unsigned Quals);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004920 bool shouldDeleteForSubobjectCall(Subobject Subobj,
4921 Sema::SpecialMemberOverloadResult *SMOR,
4922 bool IsDtorCallInCtor);
John McCall12d8d802012-04-09 20:53:23 +00004923
4924 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smith7d5088a2012-02-18 02:02:13 +00004925};
4926}
4927
John McCall12d8d802012-04-09 20:53:23 +00004928/// Is the given special member inaccessible when used on the given
4929/// sub-object.
4930bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
4931 CXXMethodDecl *target) {
4932 /// If we're operating on a base class, the object type is the
4933 /// type of this special member.
4934 QualType objectTy;
Dmitri Gribenko1ad23d62012-09-10 21:20:09 +00004935 AccessSpecifier access = target->getAccess();
John McCall12d8d802012-04-09 20:53:23 +00004936 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
4937 objectTy = S.Context.getTypeDeclType(MD->getParent());
4938 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
4939
4940 // If we're operating on a field, the object type is the type of the field.
4941 } else {
4942 objectTy = S.Context.getTypeDeclType(target->getParent());
4943 }
4944
4945 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
4946}
4947
Richard Smith6c4c36c2012-03-30 20:53:28 +00004948/// Check whether we should delete a special member due to the implicit
4949/// definition containing a call to a special member of a subobject.
4950bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
4951 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
4952 bool IsDtorCallInCtor) {
4953 CXXMethodDecl *Decl = SMOR->getMethod();
4954 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
4955
4956 int DiagKind = -1;
4957
4958 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
4959 DiagKind = !Decl ? 0 : 1;
4960 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
4961 DiagKind = 2;
John McCall12d8d802012-04-09 20:53:23 +00004962 else if (!isAccessible(Subobj, Decl))
Richard Smith6c4c36c2012-03-30 20:53:28 +00004963 DiagKind = 3;
4964 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
4965 !Decl->isTrivial()) {
4966 // A member of a union must have a trivial corresponding special member.
4967 // As a weird special case, a destructor call from a union's constructor
4968 // must be accessible and non-deleted, but need not be trivial. Such a
4969 // destructor is never actually called, but is semantically checked as
4970 // if it were.
4971 DiagKind = 4;
4972 }
4973
4974 if (DiagKind == -1)
4975 return false;
4976
4977 if (Diagnose) {
4978 if (Field) {
4979 S.Diag(Field->getLocation(),
4980 diag::note_deleted_special_member_class_subobject)
4981 << CSM << MD->getParent() << /*IsField*/true
4982 << Field << DiagKind << IsDtorCallInCtor;
4983 } else {
4984 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
4985 S.Diag(Base->getLocStart(),
4986 diag::note_deleted_special_member_class_subobject)
4987 << CSM << MD->getParent() << /*IsField*/false
4988 << Base->getType() << DiagKind << IsDtorCallInCtor;
4989 }
4990
4991 if (DiagKind == 1)
4992 S.NoteDeletedFunction(Decl);
4993 // FIXME: Explain inaccessibility if DiagKind == 3.
4994 }
4995
4996 return true;
4997}
4998
Richard Smith9a561d52012-02-26 09:11:52 +00004999/// Check whether we should delete a special member function due to having a
Richard Smith517bb842012-07-18 03:51:16 +00005000/// direct or virtual base class or non-static data member of class type M.
Richard Smith9a561d52012-02-26 09:11:52 +00005001bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smith517bb842012-07-18 03:51:16 +00005002 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
Richard Smith6c4c36c2012-03-30 20:53:28 +00005003 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Richard Smith7d5088a2012-02-18 02:02:13 +00005004
5005 // C++11 [class.ctor]p5:
Richard Smithdf8dc862012-03-29 19:00:10 +00005006 // -- any direct or virtual base class, or non-static data member with no
5007 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smith7d5088a2012-02-18 02:02:13 +00005008 // either M has no default constructor or overload resolution as applied
5009 // to M's default constructor results in an ambiguity or in a function
5010 // that is deleted or inaccessible
5011 // C++11 [class.copy]p11, C++11 [class.copy]p23:
5012 // -- a direct or virtual base class B that cannot be copied/moved because
5013 // overload resolution, as applied to B's corresponding special member,
5014 // results in an ambiguity or a function that is deleted or inaccessible
5015 // from the defaulted special member
Richard Smith6c4c36c2012-03-30 20:53:28 +00005016 // C++11 [class.dtor]p5:
5017 // -- any direct or virtual base class [...] has a type with a destructor
5018 // that is deleted or inaccessible
5019 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smith1c931be2012-04-02 18:40:40 +00005020 Field && Field->hasInClassInitializer()) &&
Richard Smith517bb842012-07-18 03:51:16 +00005021 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals), false))
Richard Smith1c931be2012-04-02 18:40:40 +00005022 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00005023
Richard Smith6c4c36c2012-03-30 20:53:28 +00005024 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
5025 // -- any direct or virtual base class or non-static data member has a
5026 // type with a destructor that is deleted or inaccessible
5027 if (IsConstructor) {
5028 Sema::SpecialMemberOverloadResult *SMOR =
5029 S.LookupSpecialMember(Class, Sema::CXXDestructor,
5030 false, false, false, false, false);
5031 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
5032 return true;
5033 }
5034
Richard Smith9a561d52012-02-26 09:11:52 +00005035 return false;
5036}
5037
5038/// Check whether we should delete a special member function due to the class
5039/// having a particular direct or virtual base class.
Richard Smith6c4c36c2012-03-30 20:53:28 +00005040bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smith1c931be2012-04-02 18:40:40 +00005041 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
Richard Smith517bb842012-07-18 03:51:16 +00005042 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
Richard Smith7d5088a2012-02-18 02:02:13 +00005043}
5044
5045/// Check whether we should delete a special member function due to the class
5046/// having a particular non-static data member.
5047bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
5048 QualType FieldType = S.Context.getBaseElementType(FD->getType());
5049 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
5050
5051 if (CSM == Sema::CXXDefaultConstructor) {
5052 // For a default constructor, all references must be initialized in-class
5053 // and, if a union, it must have a non-const member.
Richard Smith6c4c36c2012-03-30 20:53:28 +00005054 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
5055 if (Diagnose)
5056 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
5057 << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00005058 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005059 }
Richard Smith79363f52012-02-27 06:07:25 +00005060 // C++11 [class.ctor]p5: any non-variant non-static data member of
5061 // const-qualified type (or array thereof) with no
5062 // brace-or-equal-initializer does not have a user-provided default
5063 // constructor.
5064 if (!inUnion() && FieldType.isConstQualified() &&
5065 !FD->hasInClassInitializer() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00005066 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
5067 if (Diagnose)
5068 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00005069 << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith79363f52012-02-27 06:07:25 +00005070 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005071 }
5072
5073 if (inUnion() && !FieldType.isConstQualified())
5074 AllFieldsAreConst = false;
Richard Smith7d5088a2012-02-18 02:02:13 +00005075 } else if (CSM == Sema::CXXCopyConstructor) {
5076 // For a copy constructor, data members must not be of rvalue reference
5077 // type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00005078 if (FieldType->isRValueReferenceType()) {
5079 if (Diagnose)
5080 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
5081 << MD->getParent() << FD << FieldType;
Richard Smith7d5088a2012-02-18 02:02:13 +00005082 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005083 }
Richard Smith7d5088a2012-02-18 02:02:13 +00005084 } else if (IsAssignment) {
5085 // For an assignment operator, data members must not be of reference type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00005086 if (FieldType->isReferenceType()) {
5087 if (Diagnose)
5088 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
5089 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00005090 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005091 }
5092 if (!FieldRecord && FieldType.isConstQualified()) {
5093 // C++11 [class.copy]p23:
5094 // -- a non-static data member of const non-class type (or array thereof)
5095 if (Diagnose)
5096 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00005097 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005098 return true;
5099 }
Richard Smith7d5088a2012-02-18 02:02:13 +00005100 }
5101
5102 if (FieldRecord) {
Richard Smith7d5088a2012-02-18 02:02:13 +00005103 // Some additional restrictions exist on the variant members.
5104 if (!inUnion() && FieldRecord->isUnion() &&
5105 FieldRecord->isAnonymousStructOrUnion()) {
5106 bool AllVariantFieldsAreConst = true;
5107
Richard Smithdf8dc862012-03-29 19:00:10 +00005108 // FIXME: Handle anonymous unions declared within anonymous unions.
Richard Smith7d5088a2012-02-18 02:02:13 +00005109 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
5110 UE = FieldRecord->field_end();
5111 UI != UE; ++UI) {
5112 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smith7d5088a2012-02-18 02:02:13 +00005113
5114 if (!UnionFieldType.isConstQualified())
5115 AllVariantFieldsAreConst = false;
5116
Richard Smith9a561d52012-02-26 09:11:52 +00005117 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
5118 if (UnionFieldRecord &&
Richard Smith517bb842012-07-18 03:51:16 +00005119 shouldDeleteForClassSubobject(UnionFieldRecord, *UI,
5120 UnionFieldType.getCVRQualifiers()))
Richard Smith9a561d52012-02-26 09:11:52 +00005121 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00005122 }
5123
5124 // At least one member in each anonymous union must be non-const
Douglas Gregor221c27f2012-02-24 21:25:53 +00005125 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00005126 FieldRecord->field_begin() != FieldRecord->field_end()) {
5127 if (Diagnose)
5128 S.Diag(FieldRecord->getLocation(),
5129 diag::note_deleted_default_ctor_all_const)
5130 << MD->getParent() << /*anonymous union*/1;
Richard Smith7d5088a2012-02-18 02:02:13 +00005131 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005132 }
Richard Smith7d5088a2012-02-18 02:02:13 +00005133
Richard Smithdf8dc862012-03-29 19:00:10 +00005134 // Don't check the implicit member of the anonymous union type.
Richard Smith7d5088a2012-02-18 02:02:13 +00005135 // This is technically non-conformant, but sanity demands it.
5136 return false;
5137 }
5138
Richard Smith517bb842012-07-18 03:51:16 +00005139 if (shouldDeleteForClassSubobject(FieldRecord, FD,
5140 FieldType.getCVRQualifiers()))
Richard Smithdf8dc862012-03-29 19:00:10 +00005141 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00005142 }
5143
5144 return false;
5145}
5146
5147/// C++11 [class.ctor] p5:
5148/// A defaulted default constructor for a class X is defined as deleted if
5149/// X is a union and all of its variant members are of const-qualified type.
5150bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor221c27f2012-02-24 21:25:53 +00005151 // This is a silly definition, because it gives an empty union a deleted
5152 // default constructor. Don't do that.
Richard Smith6c4c36c2012-03-30 20:53:28 +00005153 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
5154 (MD->getParent()->field_begin() != MD->getParent()->field_end())) {
5155 if (Diagnose)
5156 S.Diag(MD->getParent()->getLocation(),
5157 diag::note_deleted_default_ctor_all_const)
5158 << MD->getParent() << /*not anonymous union*/0;
5159 return true;
5160 }
5161 return false;
Richard Smith7d5088a2012-02-18 02:02:13 +00005162}
5163
5164/// Determine whether a defaulted special member function should be defined as
5165/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
5166/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith6c4c36c2012-03-30 20:53:28 +00005167bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
5168 bool Diagnose) {
Richard Smitheef00292012-08-06 02:25:10 +00005169 if (MD->isInvalidDecl())
5170 return false;
Sean Hunte16da072011-10-10 06:18:57 +00005171 CXXRecordDecl *RD = MD->getParent();
Sean Huntcdee3fe2011-05-11 22:34:38 +00005172 assert(!RD->isDependentType() && "do deletion after instantiation");
Richard Smith80ad52f2013-01-02 11:42:31 +00005173 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
Sean Huntcdee3fe2011-05-11 22:34:38 +00005174 return false;
5175
Richard Smith7d5088a2012-02-18 02:02:13 +00005176 // C++11 [expr.lambda.prim]p19:
5177 // The closure type associated with a lambda-expression has a
5178 // deleted (8.4.3) default constructor and a deleted copy
5179 // assignment operator.
5180 if (RD->isLambda() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00005181 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
5182 if (Diagnose)
5183 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smith7d5088a2012-02-18 02:02:13 +00005184 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005185 }
5186
Richard Smith5bdaac52012-04-02 20:59:25 +00005187 // For an anonymous struct or union, the copy and assignment special members
5188 // will never be used, so skip the check. For an anonymous union declared at
5189 // namespace scope, the constructor and destructor are used.
5190 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
5191 RD->isAnonymousStructOrUnion())
5192 return false;
5193
Richard Smith6c4c36c2012-03-30 20:53:28 +00005194 // C++11 [class.copy]p7, p18:
5195 // If the class definition declares a move constructor or move assignment
5196 // operator, an implicitly declared copy constructor or copy assignment
5197 // operator is defined as deleted.
5198 if (MD->isImplicit() &&
5199 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
5200 CXXMethodDecl *UserDeclaredMove = 0;
5201
5202 // In Microsoft mode, a user-declared move only causes the deletion of the
5203 // corresponding copy operation, not both copy operations.
5204 if (RD->hasUserDeclaredMoveConstructor() &&
5205 (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) {
5206 if (!Diagnose) return true;
Richard Smith55798652012-12-08 04:10:18 +00005207
5208 // Find any user-declared move constructor.
5209 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
5210 E = RD->ctor_end(); I != E; ++I) {
5211 if (I->isMoveConstructor()) {
5212 UserDeclaredMove = *I;
5213 break;
5214 }
5215 }
Richard Smith1c931be2012-04-02 18:40:40 +00005216 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00005217 } else if (RD->hasUserDeclaredMoveAssignment() &&
5218 (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) {
5219 if (!Diagnose) return true;
Richard Smith55798652012-12-08 04:10:18 +00005220
5221 // Find any user-declared move assignment operator.
5222 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
5223 E = RD->method_end(); I != E; ++I) {
5224 if (I->isMoveAssignmentOperator()) {
5225 UserDeclaredMove = *I;
5226 break;
5227 }
5228 }
Richard Smith1c931be2012-04-02 18:40:40 +00005229 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00005230 }
5231
5232 if (UserDeclaredMove) {
5233 Diag(UserDeclaredMove->getLocation(),
5234 diag::note_deleted_copy_user_declared_move)
Richard Smithe6af6602012-04-02 21:07:48 +00005235 << (CSM == CXXCopyAssignment) << RD
Richard Smith6c4c36c2012-03-30 20:53:28 +00005236 << UserDeclaredMove->isMoveAssignmentOperator();
5237 return true;
5238 }
5239 }
Sean Hunte16da072011-10-10 06:18:57 +00005240
Richard Smith5bdaac52012-04-02 20:59:25 +00005241 // Do access control from the special member function
5242 ContextRAII MethodContext(*this, MD);
5243
Richard Smith9a561d52012-02-26 09:11:52 +00005244 // C++11 [class.dtor]p5:
5245 // -- for a virtual destructor, lookup of the non-array deallocation function
5246 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith6c4c36c2012-03-30 20:53:28 +00005247 if (CSM == CXXDestructor && MD->isVirtual()) {
Richard Smith9a561d52012-02-26 09:11:52 +00005248 FunctionDecl *OperatorDelete = 0;
5249 DeclarationName Name =
5250 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5251 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smith6c4c36c2012-03-30 20:53:28 +00005252 OperatorDelete, false)) {
5253 if (Diagnose)
5254 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith9a561d52012-02-26 09:11:52 +00005255 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005256 }
Richard Smith9a561d52012-02-26 09:11:52 +00005257 }
5258
Richard Smith6c4c36c2012-03-30 20:53:28 +00005259 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
Sean Huntcdee3fe2011-05-11 22:34:38 +00005260
Sean Huntcdee3fe2011-05-11 22:34:38 +00005261 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00005262 BE = RD->bases_end(); BI != BE; ++BI)
5263 if (!BI->isVirtual() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00005264 SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00005265 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00005266
Richard Smithe0883602013-07-22 18:06:23 +00005267 // Per DR1611, do not consider virtual bases of constructors of abstract
5268 // classes, since we are not going to construct them.
Richard Smithcbc820a2013-07-22 02:56:56 +00005269 if (!RD->isAbstract() || !SMI.IsConstructor) {
5270 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
5271 BE = RD->vbases_end();
5272 BI != BE; ++BI)
5273 if (SMI.shouldDeleteForBase(BI))
5274 return true;
5275 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00005276
5277 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00005278 FE = RD->field_end(); FI != FE; ++FI)
5279 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
David Blaikie581deb32012-06-06 20:45:41 +00005280 SMI.shouldDeleteForField(*FI))
Sean Hunte3406822011-05-20 21:43:47 +00005281 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00005282
Richard Smith7d5088a2012-02-18 02:02:13 +00005283 if (SMI.shouldDeleteForAllConstMembers())
Sean Huntcdee3fe2011-05-11 22:34:38 +00005284 return true;
5285
5286 return false;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005287}
5288
Richard Smithac713512012-12-08 02:53:02 +00005289/// Perform lookup for a special member of the specified kind, and determine
5290/// whether it is trivial. If the triviality can be determined without the
5291/// lookup, skip it. This is intended for use when determining whether a
5292/// special member of a containing object is trivial, and thus does not ever
5293/// perform overload resolution for default constructors.
5294///
5295/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
5296/// member that was most likely to be intended to be trivial, if any.
5297static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
5298 Sema::CXXSpecialMember CSM, unsigned Quals,
5299 CXXMethodDecl **Selected) {
5300 if (Selected)
5301 *Selected = 0;
5302
5303 switch (CSM) {
5304 case Sema::CXXInvalid:
5305 llvm_unreachable("not a special member");
5306
5307 case Sema::CXXDefaultConstructor:
5308 // C++11 [class.ctor]p5:
5309 // A default constructor is trivial if:
5310 // - all the [direct subobjects] have trivial default constructors
5311 //
5312 // Note, no overload resolution is performed in this case.
5313 if (RD->hasTrivialDefaultConstructor())
5314 return true;
5315
5316 if (Selected) {
5317 // If there's a default constructor which could have been trivial, dig it
5318 // out. Otherwise, if there's any user-provided default constructor, point
5319 // to that as an example of why there's not a trivial one.
5320 CXXConstructorDecl *DefCtor = 0;
5321 if (RD->needsImplicitDefaultConstructor())
5322 S.DeclareImplicitDefaultConstructor(RD);
5323 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(),
5324 CE = RD->ctor_end(); CI != CE; ++CI) {
5325 if (!CI->isDefaultConstructor())
5326 continue;
5327 DefCtor = *CI;
5328 if (!DefCtor->isUserProvided())
5329 break;
5330 }
5331
5332 *Selected = DefCtor;
5333 }
5334
5335 return false;
5336
5337 case Sema::CXXDestructor:
5338 // C++11 [class.dtor]p5:
5339 // A destructor is trivial if:
5340 // - all the direct [subobjects] have trivial destructors
5341 if (RD->hasTrivialDestructor())
5342 return true;
5343
5344 if (Selected) {
5345 if (RD->needsImplicitDestructor())
5346 S.DeclareImplicitDestructor(RD);
5347 *Selected = RD->getDestructor();
5348 }
5349
5350 return false;
5351
5352 case Sema::CXXCopyConstructor:
5353 // C++11 [class.copy]p12:
5354 // A copy constructor is trivial if:
5355 // - the constructor selected to copy each direct [subobject] is trivial
5356 if (RD->hasTrivialCopyConstructor()) {
5357 if (Quals == Qualifiers::Const)
5358 // We must either select the trivial copy constructor or reach an
5359 // ambiguity; no need to actually perform overload resolution.
5360 return true;
5361 } else if (!Selected) {
5362 return false;
5363 }
5364 // In C++98, we are not supposed to perform overload resolution here, but we
5365 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
5366 // cases like B as having a non-trivial copy constructor:
5367 // struct A { template<typename T> A(T&); };
5368 // struct B { mutable A a; };
5369 goto NeedOverloadResolution;
5370
5371 case Sema::CXXCopyAssignment:
5372 // C++11 [class.copy]p25:
5373 // A copy assignment operator is trivial if:
5374 // - the assignment operator selected to copy each direct [subobject] is
5375 // trivial
5376 if (RD->hasTrivialCopyAssignment()) {
5377 if (Quals == Qualifiers::Const)
5378 return true;
5379 } else if (!Selected) {
5380 return false;
5381 }
5382 // In C++98, we are not supposed to perform overload resolution here, but we
5383 // treat that as a language defect.
5384 goto NeedOverloadResolution;
5385
5386 case Sema::CXXMoveConstructor:
5387 case Sema::CXXMoveAssignment:
5388 NeedOverloadResolution:
5389 Sema::SpecialMemberOverloadResult *SMOR =
5390 S.LookupSpecialMember(RD, CSM,
5391 Quals & Qualifiers::Const,
5392 Quals & Qualifiers::Volatile,
5393 /*RValueThis*/false, /*ConstThis*/false,
5394 /*VolatileThis*/false);
5395
5396 // The standard doesn't describe how to behave if the lookup is ambiguous.
5397 // We treat it as not making the member non-trivial, just like the standard
5398 // mandates for the default constructor. This should rarely matter, because
5399 // the member will also be deleted.
5400 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5401 return true;
5402
5403 if (!SMOR->getMethod()) {
5404 assert(SMOR->getKind() ==
5405 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5406 return false;
5407 }
5408
5409 // We deliberately don't check if we found a deleted special member. We're
5410 // not supposed to!
5411 if (Selected)
5412 *Selected = SMOR->getMethod();
5413 return SMOR->getMethod()->isTrivial();
5414 }
5415
5416 llvm_unreachable("unknown special method kind");
5417}
5418
Benjamin Kramera574c892013-02-15 12:30:38 +00005419static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
Richard Smithac713512012-12-08 02:53:02 +00005420 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(), CE = RD->ctor_end();
5421 CI != CE; ++CI)
5422 if (!CI->isImplicit())
5423 return *CI;
5424
5425 // Look for constructor templates.
5426 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
5427 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
5428 if (CXXConstructorDecl *CD =
5429 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
5430 return CD;
5431 }
5432
5433 return 0;
5434}
5435
5436/// The kind of subobject we are checking for triviality. The values of this
5437/// enumeration are used in diagnostics.
5438enum TrivialSubobjectKind {
5439 /// The subobject is a base class.
5440 TSK_BaseClass,
5441 /// The subobject is a non-static data member.
5442 TSK_Field,
5443 /// The object is actually the complete object.
5444 TSK_CompleteObject
5445};
5446
5447/// Check whether the special member selected for a given type would be trivial.
5448static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
5449 QualType SubType,
5450 Sema::CXXSpecialMember CSM,
5451 TrivialSubobjectKind Kind,
5452 bool Diagnose) {
5453 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
5454 if (!SubRD)
5455 return true;
5456
5457 CXXMethodDecl *Selected;
5458 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
5459 Diagnose ? &Selected : 0))
5460 return true;
5461
5462 if (Diagnose) {
5463 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
5464 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
5465 << Kind << SubType.getUnqualifiedType();
5466 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
5467 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
5468 } else if (!Selected)
5469 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
5470 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
5471 else if (Selected->isUserProvided()) {
5472 if (Kind == TSK_CompleteObject)
5473 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
5474 << Kind << SubType.getUnqualifiedType() << CSM;
5475 else {
5476 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
5477 << Kind << SubType.getUnqualifiedType() << CSM;
5478 S.Diag(Selected->getLocation(), diag::note_declared_at);
5479 }
5480 } else {
5481 if (Kind != TSK_CompleteObject)
5482 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
5483 << Kind << SubType.getUnqualifiedType() << CSM;
5484
5485 // Explain why the defaulted or deleted special member isn't trivial.
5486 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
5487 }
5488 }
5489
5490 return false;
5491}
5492
5493/// Check whether the members of a class type allow a special member to be
5494/// trivial.
5495static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
5496 Sema::CXXSpecialMember CSM,
5497 bool ConstArg, bool Diagnose) {
5498 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
5499 FE = RD->field_end(); FI != FE; ++FI) {
5500 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
5501 continue;
5502
5503 QualType FieldType = S.Context.getBaseElementType(FI->getType());
5504
5505 // Pretend anonymous struct or union members are members of this class.
5506 if (FI->isAnonymousStructOrUnion()) {
5507 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
5508 CSM, ConstArg, Diagnose))
5509 return false;
5510 continue;
5511 }
5512
5513 // C++11 [class.ctor]p5:
5514 // A default constructor is trivial if [...]
5515 // -- no non-static data member of its class has a
5516 // brace-or-equal-initializer
5517 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
5518 if (Diagnose)
5519 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << *FI;
5520 return false;
5521 }
5522
5523 // Objective C ARC 4.3.5:
5524 // [...] nontrivally ownership-qualified types are [...] not trivially
5525 // default constructible, copy constructible, move constructible, copy
5526 // assignable, move assignable, or destructible [...]
5527 if (S.getLangOpts().ObjCAutoRefCount &&
5528 FieldType.hasNonTrivialObjCLifetime()) {
5529 if (Diagnose)
5530 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
5531 << RD << FieldType.getObjCLifetime();
5532 return false;
5533 }
5534
5535 if (ConstArg && !FI->isMutable())
5536 FieldType.addConst();
5537 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, CSM,
5538 TSK_Field, Diagnose))
5539 return false;
5540 }
5541
5542 return true;
5543}
5544
5545/// Diagnose why the specified class does not have a trivial special member of
5546/// the given kind.
5547void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
5548 QualType Ty = Context.getRecordType(RD);
5549 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)
5550 Ty.addConst();
5551
5552 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, CSM,
5553 TSK_CompleteObject, /*Diagnose*/true);
5554}
5555
5556/// Determine whether a defaulted or deleted special member function is trivial,
5557/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
5558/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
5559bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
5560 bool Diagnose) {
Richard Smithac713512012-12-08 02:53:02 +00005561 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
5562
5563 CXXRecordDecl *RD = MD->getParent();
5564
5565 bool ConstArg = false;
Richard Smithac713512012-12-08 02:53:02 +00005566
5567 // C++11 [class.copy]p12, p25:
5568 // A [special member] is trivial if its declared parameter type is the same
5569 // as if it had been implicitly declared [...]
5570 switch (CSM) {
5571 case CXXDefaultConstructor:
5572 case CXXDestructor:
5573 // Trivial default constructors and destructors cannot have parameters.
5574 break;
5575
5576 case CXXCopyConstructor:
5577 case CXXCopyAssignment: {
5578 // Trivial copy operations always have const, non-volatile parameter types.
5579 ConstArg = true;
Jordan Rose41f3f3a2013-03-05 01:27:54 +00005580 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smithac713512012-12-08 02:53:02 +00005581 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
5582 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
5583 if (Diagnose)
5584 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5585 << Param0->getSourceRange() << Param0->getType()
5586 << Context.getLValueReferenceType(
5587 Context.getRecordType(RD).withConst());
5588 return false;
5589 }
5590 break;
5591 }
5592
5593 case CXXMoveConstructor:
5594 case CXXMoveAssignment: {
5595 // Trivial move operations always have non-cv-qualified parameters.
Jordan Rose41f3f3a2013-03-05 01:27:54 +00005596 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smithac713512012-12-08 02:53:02 +00005597 const RValueReferenceType *RT =
5598 Param0->getType()->getAs<RValueReferenceType>();
5599 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
5600 if (Diagnose)
5601 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5602 << Param0->getSourceRange() << Param0->getType()
5603 << Context.getRValueReferenceType(Context.getRecordType(RD));
5604 return false;
5605 }
5606 break;
5607 }
5608
5609 case CXXInvalid:
5610 llvm_unreachable("not a special member");
5611 }
5612
5613 // FIXME: We require that the parameter-declaration-clause is equivalent to
5614 // that of an implicit declaration, not just that the declared parameter type
5615 // matches, in order to prevent absuridities like a function simultaneously
5616 // being a trivial copy constructor and a non-trivial default constructor.
5617 // This issue has not yet been assigned a core issue number.
5618 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
5619 if (Diagnose)
5620 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
5621 diag::note_nontrivial_default_arg)
5622 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
5623 return false;
5624 }
5625 if (MD->isVariadic()) {
5626 if (Diagnose)
5627 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
5628 return false;
5629 }
5630
5631 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5632 // A copy/move [constructor or assignment operator] is trivial if
5633 // -- the [member] selected to copy/move each direct base class subobject
5634 // is trivial
5635 //
5636 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5637 // A [default constructor or destructor] is trivial if
5638 // -- all the direct base classes have trivial [default constructors or
5639 // destructors]
5640 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
5641 BE = RD->bases_end(); BI != BE; ++BI)
5642 if (!checkTrivialSubobjectCall(*this, BI->getLocStart(),
5643 ConstArg ? BI->getType().withConst()
5644 : BI->getType(),
5645 CSM, TSK_BaseClass, Diagnose))
5646 return false;
5647
5648 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5649 // A copy/move [constructor or assignment operator] for a class X is
5650 // trivial if
5651 // -- for each non-static data member of X that is of class type (or array
5652 // thereof), the constructor selected to copy/move that member is
5653 // trivial
5654 //
5655 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5656 // A [default constructor or destructor] is trivial if
5657 // -- for all of the non-static data members of its class that are of class
5658 // type (or array thereof), each such class has a trivial [default
5659 // constructor or destructor]
5660 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
5661 return false;
5662
5663 // C++11 [class.dtor]p5:
5664 // A destructor is trivial if [...]
5665 // -- the destructor is not virtual
5666 if (CSM == CXXDestructor && MD->isVirtual()) {
5667 if (Diagnose)
5668 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
5669 return false;
5670 }
5671
5672 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
5673 // A [special member] for class X is trivial if [...]
5674 // -- class X has no virtual functions and no virtual base classes
5675 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
5676 if (!Diagnose)
5677 return false;
5678
5679 if (RD->getNumVBases()) {
5680 // Check for virtual bases. We already know that the corresponding
5681 // member in all bases is trivial, so vbases must all be direct.
5682 CXXBaseSpecifier &BS = *RD->vbases_begin();
5683 assert(BS.isVirtual());
5684 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
5685 return false;
5686 }
5687
5688 // Must have a virtual method.
5689 for (CXXRecordDecl::method_iterator MI = RD->method_begin(),
5690 ME = RD->method_end(); MI != ME; ++MI) {
5691 if (MI->isVirtual()) {
5692 SourceLocation MLoc = MI->getLocStart();
5693 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
5694 return false;
5695 }
5696 }
5697
5698 llvm_unreachable("dynamic class with no vbases and no virtual functions");
5699 }
5700
5701 // Looks like it's trivial!
5702 return true;
5703}
5704
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005705/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramerc54061a2011-03-04 13:12:48 +00005706namespace {
5707 struct FindHiddenVirtualMethodData {
5708 Sema *S;
5709 CXXMethodDecl *Method;
5710 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005711 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramerc54061a2011-03-04 13:12:48 +00005712 };
5713}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005714
David Blaikie5f750682012-10-19 00:53:08 +00005715/// \brief Check whether any most overriden method from MD in Methods
5716static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
5717 const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5718 if (MD->size_overridden_methods() == 0)
5719 return Methods.count(MD->getCanonicalDecl());
5720 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5721 E = MD->end_overridden_methods();
5722 I != E; ++I)
5723 if (CheckMostOverridenMethods(*I, Methods))
5724 return true;
5725 return false;
5726}
5727
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005728/// \brief Member lookup function that determines whether a given C++
5729/// method overloads virtual methods in a base class without overriding any,
5730/// to be used with CXXRecordDecl::lookupInBases().
5731static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
5732 CXXBasePath &Path,
5733 void *UserData) {
5734 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5735
5736 FindHiddenVirtualMethodData &Data
5737 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
5738
5739 DeclarationName Name = Data.Method->getDeclName();
5740 assert(Name.getNameKind() == DeclarationName::Identifier);
5741
5742 bool foundSameNameMethod = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005743 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005744 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikie3bc93e32012-12-19 00:45:41 +00005745 !Path.Decls.empty();
5746 Path.Decls = Path.Decls.slice(1)) {
5747 NamedDecl *D = Path.Decls.front();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005748 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00005749 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005750 foundSameNameMethod = true;
5751 // Interested only in hidden virtual methods.
5752 if (!MD->isVirtual())
5753 continue;
5754 // If the method we are checking overrides a method from its base
5755 // don't warn about the other overloaded methods.
5756 if (!Data.S->IsOverload(Data.Method, MD, false))
5757 return true;
5758 // Collect the overload only if its hidden.
David Blaikie5f750682012-10-19 00:53:08 +00005759 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005760 overloadedMethods.push_back(MD);
5761 }
5762 }
5763
5764 if (foundSameNameMethod)
5765 Data.OverloadedMethods.append(overloadedMethods.begin(),
5766 overloadedMethods.end());
5767 return foundSameNameMethod;
5768}
5769
David Blaikie5f750682012-10-19 00:53:08 +00005770/// \brief Add the most overriden methods from MD to Methods
5771static void AddMostOverridenMethods(const CXXMethodDecl *MD,
5772 llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5773 if (MD->size_overridden_methods() == 0)
5774 Methods.insert(MD->getCanonicalDecl());
5775 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5776 E = MD->end_overridden_methods();
5777 I != E; ++I)
5778 AddMostOverridenMethods(*I, Methods);
5779}
5780
Eli Friedmandae92712013-09-05 23:51:03 +00005781/// \brief Check if a method overloads virtual methods in a base class without
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005782/// overriding any.
Eli Friedmandae92712013-09-05 23:51:03 +00005783void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
5784 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
Benjamin Kramerc4704422012-05-19 16:03:58 +00005785 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005786 return;
5787
5788 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
5789 /*bool RecordPaths=*/false,
5790 /*bool DetectVirtual=*/false);
5791 FindHiddenVirtualMethodData Data;
5792 Data.Method = MD;
5793 Data.S = this;
5794
5795 // Keep the base methods that were overriden or introduced in the subclass
5796 // by 'using' in a set. A base method not in this set is hidden.
Eli Friedmandae92712013-09-05 23:51:03 +00005797 CXXRecordDecl *DC = MD->getParent();
David Blaikie3bc93e32012-12-19 00:45:41 +00005798 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
5799 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
5800 NamedDecl *ND = *I;
5801 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
David Blaikie5f750682012-10-19 00:53:08 +00005802 ND = shad->getTargetDecl();
5803 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5804 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005805 }
5806
Eli Friedmandae92712013-09-05 23:51:03 +00005807 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths))
5808 OverloadedMethods = Data.OverloadedMethods;
5809}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005810
Eli Friedmandae92712013-09-05 23:51:03 +00005811void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
5812 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
5813 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
5814 CXXMethodDecl *overloadedMD = OverloadedMethods[i];
5815 PartialDiagnostic PD = PDiag(
5816 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
5817 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
5818 Diag(overloadedMD->getLocation(), PD);
5819 }
5820}
5821
5822/// \brief Diagnose methods which overload virtual methods in a base class
5823/// without overriding any.
5824void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
5825 if (MD->isInvalidDecl())
5826 return;
5827
5828 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
5829 MD->getLocation()) == DiagnosticsEngine::Ignored)
5830 return;
5831
5832 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
5833 FindHiddenVirtualMethods(MD, OverloadedMethods);
5834 if (!OverloadedMethods.empty()) {
5835 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
5836 << MD << (OverloadedMethods.size() > 1);
5837
5838 NoteHiddenVirtualMethods(MD, OverloadedMethods);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005839 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005840}
5841
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005842void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00005843 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005844 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00005845 SourceLocation RBrac,
5846 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005847 if (!TagDecl)
5848 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005849
Douglas Gregor42af25f2009-05-11 19:58:34 +00005850 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005851
Rafael Espindolaf729ce02012-07-12 04:32:30 +00005852 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
5853 if (l->getKind() != AttributeList::AT_Visibility)
5854 continue;
5855 l->setInvalid();
5856 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
5857 l->getName();
5858 }
5859
David Blaikie77b6de02011-09-22 02:58:26 +00005860 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCalld226f652010-08-21 09:40:31 +00005861 // strict aliasing violation!
5862 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie77b6de02011-09-22 02:58:26 +00005863 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00005864
Douglas Gregor23c94db2010-07-02 17:43:08 +00005865 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00005866 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005867}
5868
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005869/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5870/// special functions, such as the default constructor, copy
5871/// constructor, or destructor, to the given C++ class (C++
5872/// [special]p1). This routine can only be executed just before the
5873/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00005874void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00005875 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00005876 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005877
Richard Smithbc2a35d2012-12-08 08:32:28 +00005878 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
Douglas Gregor22584312010-07-02 23:41:54 +00005879 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005880
Richard Smithbc2a35d2012-12-08 08:32:28 +00005881 // If the properties or semantics of the copy constructor couldn't be
5882 // determined while the class was being declared, force a declaration
5883 // of it now.
5884 if (ClassDecl->needsOverloadResolutionForCopyConstructor())
5885 DeclareImplicitCopyConstructor(ClassDecl);
5886 }
5887
Richard Smith80ad52f2013-01-02 11:42:31 +00005888 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00005889 ++ASTContext::NumImplicitMoveConstructors;
5890
Richard Smithbc2a35d2012-12-08 08:32:28 +00005891 if (ClassDecl->needsOverloadResolutionForMoveConstructor())
5892 DeclareImplicitMoveConstructor(ClassDecl);
5893 }
5894
Douglas Gregora376d102010-07-02 21:50:04 +00005895 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
5896 ++ASTContext::NumImplicitCopyAssignmentOperators;
Richard Smithbc2a35d2012-12-08 08:32:28 +00005897
5898 // If we have a dynamic class, then the copy assignment operator may be
Douglas Gregora376d102010-07-02 21:50:04 +00005899 // virtual, so we have to declare it immediately. This ensures that, e.g.,
Richard Smithbc2a35d2012-12-08 08:32:28 +00005900 // it shows up in the right place in the vtable and that we diagnose
5901 // problems with the implicit exception specification.
5902 if (ClassDecl->isDynamicClass() ||
5903 ClassDecl->needsOverloadResolutionForCopyAssignment())
Douglas Gregora376d102010-07-02 21:50:04 +00005904 DeclareImplicitCopyAssignment(ClassDecl);
5905 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00005906
Richard Smith80ad52f2013-01-02 11:42:31 +00005907 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00005908 ++ASTContext::NumImplicitMoveAssignmentOperators;
5909
5910 // Likewise for the move assignment operator.
Richard Smithbc2a35d2012-12-08 08:32:28 +00005911 if (ClassDecl->isDynamicClass() ||
5912 ClassDecl->needsOverloadResolutionForMoveAssignment())
Richard Smithb701d3d2011-12-24 21:56:24 +00005913 DeclareImplicitMoveAssignment(ClassDecl);
5914 }
5915
Douglas Gregor4923aa22010-07-02 20:37:36 +00005916 if (!ClassDecl->hasUserDeclaredDestructor()) {
5917 ++ASTContext::NumImplicitDestructors;
Richard Smithbc2a35d2012-12-08 08:32:28 +00005918
5919 // If we have a dynamic class, then the destructor may be virtual, so we
Douglas Gregor4923aa22010-07-02 20:37:36 +00005920 // have to declare the destructor immediately. This ensures that, e.g., it
5921 // shows up in the right place in the vtable and that we diagnose problems
5922 // with the implicit exception specification.
Richard Smithbc2a35d2012-12-08 08:32:28 +00005923 if (ClassDecl->isDynamicClass() ||
5924 ClassDecl->needsOverloadResolutionForDestructor())
Douglas Gregor4923aa22010-07-02 20:37:36 +00005925 DeclareImplicitDestructor(ClassDecl);
5926 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005927}
5928
Francois Pichet8387e2a2011-04-22 22:18:13 +00005929void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
5930 if (!D)
5931 return;
5932
5933 int NumParamList = D->getNumTemplateParameterLists();
5934 for (int i = 0; i < NumParamList; i++) {
5935 TemplateParameterList* Params = D->getTemplateParameterList(i);
5936 for (TemplateParameterList::iterator Param = Params->begin(),
5937 ParamEnd = Params->end();
5938 Param != ParamEnd; ++Param) {
5939 NamedDecl *Named = cast<NamedDecl>(*Param);
5940 if (Named->getDeclName()) {
5941 S->AddDecl(Named);
5942 IdResolver.AddDecl(Named);
5943 }
5944 }
5945 }
5946}
5947
John McCalld226f652010-08-21 09:40:31 +00005948void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00005949 if (!D)
5950 return;
5951
5952 TemplateParameterList *Params = 0;
5953 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
5954 Params = Template->getTemplateParameters();
5955 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
5956 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
5957 Params = PartialSpec->getTemplateParameters();
5958 else
Douglas Gregor6569d682009-05-27 23:11:45 +00005959 return;
5960
Douglas Gregor6569d682009-05-27 23:11:45 +00005961 for (TemplateParameterList::iterator Param = Params->begin(),
5962 ParamEnd = Params->end();
5963 Param != ParamEnd; ++Param) {
5964 NamedDecl *Named = cast<NamedDecl>(*Param);
5965 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00005966 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00005967 IdResolver.AddDecl(Named);
5968 }
5969 }
5970}
5971
John McCalld226f652010-08-21 09:40:31 +00005972void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005973 if (!RecordD) return;
5974 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00005975 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00005976 PushDeclContext(S, Record);
5977}
5978
John McCalld226f652010-08-21 09:40:31 +00005979void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005980 if (!RecordD) return;
5981 PopDeclContext();
5982}
5983
Douglas Gregor72b505b2008-12-16 21:30:33 +00005984/// ActOnStartDelayedCXXMethodDeclaration - We have completed
5985/// parsing a top-level (non-nested) C++ class, and we are now
5986/// parsing those parts of the given Method declaration that could
5987/// not be parsed earlier (C++ [class.mem]p2), such as default
5988/// arguments. This action should enter the scope of the given
5989/// Method declaration as if we had just parsed the qualified method
5990/// name. However, it should not bring the parameters into scope;
5991/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00005992void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005993}
5994
5995/// ActOnDelayedCXXMethodParameter - We've already started a delayed
5996/// C++ method declaration. We're (re-)introducing the given
5997/// function parameter into scope for use in parsing later parts of
5998/// the method declaration. For example, we could see an
5999/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00006000void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00006001 if (!ParamD)
6002 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006003
John McCalld226f652010-08-21 09:40:31 +00006004 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00006005
6006 // If this parameter has an unparsed default argument, clear it out
6007 // to make way for the parsed default argument.
6008 if (Param->hasUnparsedDefaultArg())
6009 Param->setDefaultArg(0);
6010
John McCalld226f652010-08-21 09:40:31 +00006011 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00006012 if (Param->getDeclName())
6013 IdResolver.AddDecl(Param);
6014}
6015
6016/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
6017/// processing the delayed method declaration for Method. The method
6018/// declaration is now considered finished. There may be a separate
6019/// ActOnStartOfFunctionDef action later (not necessarily
6020/// immediately!) for this method, if it was also defined inside the
6021/// class body.
John McCalld226f652010-08-21 09:40:31 +00006022void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00006023 if (!MethodD)
6024 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006025
Douglas Gregorefd5bda2009-08-24 11:57:43 +00006026 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00006027
John McCalld226f652010-08-21 09:40:31 +00006028 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00006029
6030 // Now that we have our default arguments, check the constructor
6031 // again. It could produce additional diagnostics or affect whether
6032 // the class has implicitly-declared destructors, among other
6033 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00006034 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
6035 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00006036
6037 // Check the default arguments, which we may have added.
6038 if (!Method->isInvalidDecl())
6039 CheckCXXDefaultArguments(Method);
6040}
6041
Douglas Gregor42a552f2008-11-05 20:51:48 +00006042/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00006043/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00006044/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00006045/// emit diagnostics and set the invalid bit to true. In any case, the type
6046/// will be updated to reflect a well-formed type for the constructor and
6047/// returned.
6048QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00006049 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00006050 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00006051
6052 // C++ [class.ctor]p3:
6053 // A constructor shall not be virtual (10.3) or static (9.4). A
6054 // constructor can be invoked for a const, volatile or const
6055 // volatile object. A constructor shall not be declared const,
6056 // volatile, or const volatile (9.3.2).
6057 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00006058 if (!D.isInvalidType())
6059 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6060 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
6061 << SourceRange(D.getIdentifierLoc());
6062 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00006063 }
John McCalld931b082010-08-26 03:08:43 +00006064 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00006065 if (!D.isInvalidType())
6066 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6067 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6068 << SourceRange(D.getIdentifierLoc());
6069 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00006070 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00006071 }
Mike Stump1eb44332009-09-09 15:08:12 +00006072
Abramo Bagnara075f8f12010-12-10 16:29:40 +00006073 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00006074 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00006075 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006076 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6077 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00006078 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006079 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6080 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00006081 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006082 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6083 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00006084 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00006085 }
Mike Stump1eb44332009-09-09 15:08:12 +00006086
Douglas Gregorc938c162011-01-26 05:01:58 +00006087 // C++0x [class.ctor]p4:
6088 // A constructor shall not be declared with a ref-qualifier.
6089 if (FTI.hasRefQualifier()) {
6090 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
6091 << FTI.RefQualifierIsLValueRef
6092 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6093 D.setInvalidType();
6094 }
6095
Douglas Gregor42a552f2008-11-05 20:51:48 +00006096 // Rebuild the function type "R" without any type qualifiers (in
6097 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00006098 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00006099 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00006100 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
6101 return R;
6102
6103 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6104 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00006105 EPI.RefQualifier = RQ_None;
6106
Richard Smith07b0fdc2013-03-18 21:12:30 +00006107 return Context.getFunctionType(Context.VoidTy, Proto->getArgTypes(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00006108}
6109
Douglas Gregor72b505b2008-12-16 21:30:33 +00006110/// CheckConstructor - Checks a fully-formed constructor for
6111/// well-formedness, issuing any diagnostics required. Returns true if
6112/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00006113void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00006114 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00006115 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
6116 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00006117 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00006118
6119 // C++ [class.copy]p3:
6120 // A declaration of a constructor for a class X is ill-formed if
6121 // its first parameter is of type (optionally cv-qualified) X and
6122 // either there are no other parameters or else all other
6123 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00006124 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00006125 ((Constructor->getNumParams() == 1) ||
6126 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00006127 Constructor->getParamDecl(1)->hasDefaultArg())) &&
6128 Constructor->getTemplateSpecializationKind()
6129 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00006130 QualType ParamType = Constructor->getParamDecl(0)->getType();
6131 QualType ClassTy = Context.getTagDeclType(ClassDecl);
6132 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00006133 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00006134 const char *ConstRef
6135 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
6136 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00006137 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00006138 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00006139
6140 // FIXME: Rather that making the constructor invalid, we should endeavor
6141 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00006142 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00006143 }
6144 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00006145}
6146
John McCall15442822010-08-04 01:04:25 +00006147/// CheckDestructor - Checks a fully-formed destructor definition for
6148/// well-formedness, issuing any diagnostics required. Returns true
6149/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00006150bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00006151 CXXRecordDecl *RD = Destructor->getParent();
6152
Peter Collingbournef51cfb82013-05-20 14:12:25 +00006153 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
Anders Carlsson6d701392009-11-15 22:49:34 +00006154 SourceLocation Loc;
6155
6156 if (!Destructor->isImplicit())
6157 Loc = Destructor->getLocation();
6158 else
6159 Loc = RD->getLocation();
6160
6161 // If we have a virtual destructor, look up the deallocation function
6162 FunctionDecl *OperatorDelete = 0;
6163 DeclarationName Name =
6164 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00006165 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00006166 return true;
John McCall5efd91a2010-07-03 18:33:00 +00006167
Eli Friedman5f2987c2012-02-02 03:46:19 +00006168 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00006169
6170 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00006171 }
Anders Carlsson37909802009-11-30 21:24:50 +00006172
6173 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00006174}
6175
Mike Stump1eb44332009-09-09 15:08:12 +00006176static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00006177FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
6178 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
6179 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00006180 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00006181}
6182
Douglas Gregor42a552f2008-11-05 20:51:48 +00006183/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
6184/// the well-formednes of the destructor declarator @p D with type @p
6185/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00006186/// emit diagnostics and set the declarator to invalid. Even if this happens,
6187/// will be updated to reflect a well-formed type for the destructor and
6188/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00006189QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00006190 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00006191 // C++ [class.dtor]p1:
6192 // [...] A typedef-name that names a class is a class-name
6193 // (7.1.3); however, a typedef-name that names a class shall not
6194 // be used as the identifier in the declarator for a destructor
6195 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00006196 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smith162e1c12011-04-15 14:24:37 +00006197 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner65401802009-04-25 08:28:21 +00006198 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smith162e1c12011-04-15 14:24:37 +00006199 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00006200 else if (const TemplateSpecializationType *TST =
6201 DeclaratorType->getAs<TemplateSpecializationType>())
6202 if (TST->isTypeAlias())
6203 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6204 << DeclaratorType << 1;
Douglas Gregor42a552f2008-11-05 20:51:48 +00006205
6206 // C++ [class.dtor]p2:
6207 // A destructor is used to destroy objects of its class type. A
6208 // destructor takes no parameters, and no return type can be
6209 // specified for it (not even void). The address of a destructor
6210 // shall not be taken. A destructor shall not be static. A
6211 // destructor can be invoked for a const, volatile or const
6212 // volatile object. A destructor shall not be declared const,
6213 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00006214 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00006215 if (!D.isInvalidType())
6216 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
6217 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00006218 << SourceRange(D.getIdentifierLoc())
6219 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6220
John McCalld931b082010-08-26 03:08:43 +00006221 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00006222 }
Chris Lattner65401802009-04-25 08:28:21 +00006223 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00006224 // Destructors don't have return types, but the parser will
6225 // happily parse something like:
6226 //
6227 // class X {
6228 // float ~X();
6229 // };
6230 //
6231 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006232 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
6233 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6234 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00006235 }
Mike Stump1eb44332009-09-09 15:08:12 +00006236
Abramo Bagnara075f8f12010-12-10 16:29:40 +00006237 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00006238 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00006239 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006240 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6241 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00006242 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006243 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6244 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00006245 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006246 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6247 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00006248 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00006249 }
6250
Douglas Gregorc938c162011-01-26 05:01:58 +00006251 // C++0x [class.dtor]p2:
6252 // A destructor shall not be declared with a ref-qualifier.
6253 if (FTI.hasRefQualifier()) {
6254 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
6255 << FTI.RefQualifierIsLValueRef
6256 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6257 D.setInvalidType();
6258 }
6259
Douglas Gregor42a552f2008-11-05 20:51:48 +00006260 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00006261 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00006262 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
6263
6264 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00006265 FTI.freeArgs();
6266 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00006267 }
6268
Mike Stump1eb44332009-09-09 15:08:12 +00006269 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00006270 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00006271 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00006272 D.setInvalidType();
6273 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00006274
6275 // Rebuild the function type "R" without any type qualifiers or
6276 // parameters (in case any of the errors above fired) and with
6277 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00006278 // types.
John McCalle23cf432010-12-14 08:05:40 +00006279 if (!D.isInvalidType())
6280 return R;
6281
Douglas Gregord92ec472010-07-01 05:10:53 +00006282 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00006283 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6284 EPI.Variadic = false;
6285 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00006286 EPI.RefQualifier = RQ_None;
Dmitri Gribenko55431692013-05-05 00:41:58 +00006287 return Context.getFunctionType(Context.VoidTy, None, EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00006288}
6289
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006290/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6291/// well-formednes of the conversion function declarator @p D with
6292/// type @p R. If there are any errors in the declarator, this routine
6293/// will emit diagnostics and return true. Otherwise, it will return
6294/// false. Either way, the type @p R will be updated to reflect a
6295/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00006296void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00006297 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006298 // C++ [class.conv.fct]p1:
6299 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00006300 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00006301 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00006302 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00006303 if (!D.isInvalidType())
6304 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
Eli Friedman4cde94a2013-06-20 20:58:02 +00006305 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6306 << D.getName().getSourceRange();
Chris Lattner6e475012009-04-25 08:35:12 +00006307 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00006308 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006309 }
John McCalla3f81372010-04-13 00:04:31 +00006310
6311 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
6312
Chris Lattner6e475012009-04-25 08:35:12 +00006313 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006314 // Conversion functions don't have return types, but the parser will
6315 // happily parse something like:
6316 //
6317 // class X {
6318 // float operator bool();
6319 // };
6320 //
6321 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006322 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
6323 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6324 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00006325 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006326 }
6327
John McCalla3f81372010-04-13 00:04:31 +00006328 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6329
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006330 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00006331 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006332 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
6333
6334 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00006335 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00006336 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00006337 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006338 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00006339 D.setInvalidType();
6340 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006341
John McCalla3f81372010-04-13 00:04:31 +00006342 // Diagnose "&operator bool()" and other such nonsense. This
6343 // is actually a gcc extension which we don't support.
6344 if (Proto->getResultType() != ConvType) {
6345 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
6346 << Proto->getResultType();
6347 D.setInvalidType();
6348 ConvType = Proto->getResultType();
6349 }
6350
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006351 // C++ [class.conv.fct]p4:
6352 // The conversion-type-id shall not represent a function type nor
6353 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006354 if (ConvType->isArrayType()) {
6355 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
6356 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00006357 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006358 } else if (ConvType->isFunctionType()) {
6359 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
6360 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00006361 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006362 }
6363
6364 // Rebuild the function type "R" without any parameters (in case any
6365 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00006366 // return type.
John McCalle23cf432010-12-14 08:05:40 +00006367 if (D.isInvalidType())
Dmitri Gribenko55431692013-05-05 00:41:58 +00006368 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006369
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006370 // C++0x explicit conversion operators.
Richard Smithebaf0e62011-10-18 20:49:44 +00006371 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump1eb44332009-09-09 15:08:12 +00006372 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006373 getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +00006374 diag::warn_cxx98_compat_explicit_conversion_functions :
6375 diag::ext_explicit_conversion_functions)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006376 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006377}
6378
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006379/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
6380/// the declaration of the given C++ conversion function. This routine
6381/// is responsible for recording the conversion function in the C++
6382/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00006383Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006384 assert(Conversion && "Expected to receive a conversion function declaration");
6385
Douglas Gregor9d350972008-12-12 08:25:50 +00006386 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006387
6388 // Make sure we aren't redeclaring the conversion function.
6389 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006390
6391 // C++ [class.conv.fct]p1:
6392 // [...] A conversion function is never used to convert a
6393 // (possibly cv-qualified) object to the (possibly cv-qualified)
6394 // same object type (or a reference to it), to a (possibly
6395 // cv-qualified) base class of that type (or a reference to it),
6396 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00006397 // FIXME: Suppress this warning if the conversion function ends up being a
6398 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00006399 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006400 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00006401 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006402 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00006403 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
6404 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00006405 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00006406 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006407 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
6408 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00006409 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006410 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006411 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00006412 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006413 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006414 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00006415 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006416 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006417 }
6418
Douglas Gregore80622f2010-09-29 04:25:11 +00006419 if (FunctionTemplateDecl *ConversionTemplate
6420 = Conversion->getDescribedFunctionTemplate())
6421 return ConversionTemplate;
6422
John McCalld226f652010-08-21 09:40:31 +00006423 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006424}
6425
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006426//===----------------------------------------------------------------------===//
6427// Namespace Handling
6428//===----------------------------------------------------------------------===//
6429
Richard Smithd1a55a62012-10-04 22:13:39 +00006430/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
6431/// reopened.
6432static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
6433 SourceLocation Loc,
6434 IdentifierInfo *II, bool *IsInline,
6435 NamespaceDecl *PrevNS) {
6436 assert(*IsInline != PrevNS->isInline());
John McCallea318642010-08-26 09:15:37 +00006437
Richard Smithc969e6a2012-10-05 01:46:25 +00006438 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
6439 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
6440 // inline namespaces, with the intention of bringing names into namespace std.
6441 //
6442 // We support this just well enough to get that case working; this is not
6443 // sufficient to support reopening namespaces as inline in general.
Richard Smithd1a55a62012-10-04 22:13:39 +00006444 if (*IsInline && II && II->getName().startswith("__atomic") &&
6445 S.getSourceManager().isInSystemHeader(Loc)) {
Richard Smithc969e6a2012-10-05 01:46:25 +00006446 // Mark all prior declarations of the namespace as inline.
Richard Smithd1a55a62012-10-04 22:13:39 +00006447 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
6448 NS = NS->getPreviousDecl())
6449 NS->setInline(*IsInline);
6450 // Patch up the lookup table for the containing namespace. This isn't really
6451 // correct, but it's good enough for this particular case.
6452 for (DeclContext::decl_iterator I = PrevNS->decls_begin(),
6453 E = PrevNS->decls_end(); I != E; ++I)
6454 if (NamedDecl *ND = dyn_cast<NamedDecl>(*I))
6455 PrevNS->getParent()->makeDeclVisibleInContext(ND);
6456 return;
6457 }
6458
6459 if (PrevNS->isInline())
6460 // The user probably just forgot the 'inline', so suggest that it
6461 // be added back.
6462 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
6463 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
6464 else
6465 S.Diag(Loc, diag::err_inline_namespace_mismatch)
6466 << IsInline;
6467
6468 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
6469 *IsInline = PrevNS->isInline();
6470}
John McCallea318642010-08-26 09:15:37 +00006471
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006472/// ActOnStartNamespaceDef - This is called at the start of a namespace
6473/// definition.
John McCalld226f652010-08-21 09:40:31 +00006474Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00006475 SourceLocation InlineLoc,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006476 SourceLocation NamespaceLoc,
John McCallea318642010-08-26 09:15:37 +00006477 SourceLocation IdentLoc,
6478 IdentifierInfo *II,
6479 SourceLocation LBrace,
6480 AttributeList *AttrList) {
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006481 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
6482 // For anonymous namespace, take the location of the left brace.
6483 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006484 bool IsInline = InlineLoc.isValid();
Douglas Gregor67310742012-01-10 22:14:10 +00006485 bool IsInvalid = false;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006486 bool IsStd = false;
6487 bool AddToKnown = false;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006488 Scope *DeclRegionScope = NamespcScope->getParent();
6489
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006490 NamespaceDecl *PrevNS = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006491 if (II) {
6492 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00006493 // The identifier in an original-namespace-definition shall not
6494 // have been previously defined in the declarative region in
6495 // which the original-namespace-definition appears. The
6496 // identifier in an original-namespace-definition is the name of
6497 // the namespace. Subsequently in that declarative region, it is
6498 // treated as an original-namespace-name.
6499 //
6500 // Since namespace names are unique in their scope, and we don't
Douglas Gregor010157f2011-05-06 23:28:47 +00006501 // look through using directives, just look for any ordinary names.
6502
6503 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006504 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
6505 Decl::IDNS_Namespace;
Douglas Gregor010157f2011-05-06 23:28:47 +00006506 NamedDecl *PrevDecl = 0;
David Blaikie3bc93e32012-12-19 00:45:41 +00006507 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
6508 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6509 ++I) {
6510 if ((*I)->getIdentifierNamespace() & IDNS) {
6511 PrevDecl = *I;
Douglas Gregor010157f2011-05-06 23:28:47 +00006512 break;
6513 }
6514 }
6515
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006516 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
6517
6518 if (PrevNS) {
Douglas Gregor44b43212008-12-11 16:49:14 +00006519 // This is an extended namespace definition.
Richard Smithd1a55a62012-10-04 22:13:39 +00006520 if (IsInline != PrevNS->isInline())
6521 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
6522 &IsInline, PrevNS);
Douglas Gregor44b43212008-12-11 16:49:14 +00006523 } else if (PrevDecl) {
6524 // This is an invalid name redefinition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006525 Diag(Loc, diag::err_redefinition_different_kind)
6526 << II;
Douglas Gregor44b43212008-12-11 16:49:14 +00006527 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00006528 IsInvalid = true;
Douglas Gregor44b43212008-12-11 16:49:14 +00006529 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006530 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00006531 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00006532 // This is the first "real" definition of the namespace "std", so update
6533 // our cache of the "std" namespace to point at this definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006534 PrevNS = getStdNamespace();
6535 IsStd = true;
6536 AddToKnown = !IsInline;
6537 } else {
6538 // We've seen this namespace for the first time.
6539 AddToKnown = !IsInline;
Mike Stump1eb44332009-09-09 15:08:12 +00006540 }
Douglas Gregor44b43212008-12-11 16:49:14 +00006541 } else {
John McCall9aeed322009-10-01 00:25:31 +00006542 // Anonymous namespaces.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006543
6544 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl7a126a42010-08-31 00:36:30 +00006545 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00006546 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006547 PrevNS = TU->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00006548 } else {
6549 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006550 PrevNS = ND->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00006551 }
6552
Richard Smithd1a55a62012-10-04 22:13:39 +00006553 if (PrevNS && IsInline != PrevNS->isInline())
6554 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
6555 &IsInline, PrevNS);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006556 }
6557
6558 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
6559 StartLoc, Loc, II, PrevNS);
Douglas Gregor67310742012-01-10 22:14:10 +00006560 if (IsInvalid)
6561 Namespc->setInvalidDecl();
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006562
6563 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00006564
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006565 // FIXME: Should we be merging attributes?
6566 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00006567 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006568
6569 if (IsStd)
6570 StdNamespace = Namespc;
6571 if (AddToKnown)
6572 KnownNamespaces[Namespc] = false;
6573
6574 if (II) {
6575 PushOnScopeChains(Namespc, DeclRegionScope);
6576 } else {
6577 // Link the anonymous namespace into its parent.
6578 DeclContext *Parent = CurContext->getRedeclContext();
6579 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6580 TU->setAnonymousNamespace(Namespc);
6581 } else {
6582 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall5fdd7642009-12-16 02:06:49 +00006583 }
John McCall9aeed322009-10-01 00:25:31 +00006584
Douglas Gregora4181472010-03-24 00:46:35 +00006585 CurContext->addDecl(Namespc);
6586
John McCall9aeed322009-10-01 00:25:31 +00006587 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
6588 // behaves as if it were replaced by
6589 // namespace unique { /* empty body */ }
6590 // using namespace unique;
6591 // namespace unique { namespace-body }
6592 // where all occurrences of 'unique' in a translation unit are
6593 // replaced by the same identifier and this identifier differs
6594 // from all other identifiers in the entire program.
6595
6596 // We just create the namespace with an empty name and then add an
6597 // implicit using declaration, just like the standard suggests.
6598 //
6599 // CodeGen enforces the "universally unique" aspect by giving all
6600 // declarations semantically contained within an anonymous
6601 // namespace internal linkage.
6602
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006603 if (!PrevNS) {
John McCall5fdd7642009-12-16 02:06:49 +00006604 UsingDirectiveDecl* UD
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006605 = UsingDirectiveDecl::Create(Context, Parent,
John McCall5fdd7642009-12-16 02:06:49 +00006606 /* 'using' */ LBrace,
6607 /* 'namespace' */ SourceLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00006608 /* qualifier */ NestedNameSpecifierLoc(),
John McCall5fdd7642009-12-16 02:06:49 +00006609 /* identifier */ SourceLocation(),
6610 Namespc,
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006611 /* Ancestor */ Parent);
John McCall5fdd7642009-12-16 02:06:49 +00006612 UD->setImplicit();
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006613 Parent->addDecl(UD);
John McCall5fdd7642009-12-16 02:06:49 +00006614 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006615 }
6616
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00006617 ActOnDocumentableDecl(Namespc);
6618
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006619 // Although we could have an invalid decl (i.e. the namespace name is a
6620 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00006621 // FIXME: We should be able to push Namespc here, so that the each DeclContext
6622 // for the namespace has the declarations that showed up in that particular
6623 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00006624 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00006625 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006626}
6627
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006628/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
6629/// is a namespace alias, returns the namespace it points to.
6630static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
6631 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
6632 return AD->getNamespace();
6633 return dyn_cast_or_null<NamespaceDecl>(D);
6634}
6635
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006636/// ActOnFinishNamespaceDef - This callback is called after a namespace is
6637/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00006638void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006639 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
6640 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006641 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006642 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00006643 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00006644 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006645}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006646
John McCall384aff82010-08-25 07:42:41 +00006647CXXRecordDecl *Sema::getStdBadAlloc() const {
6648 return cast_or_null<CXXRecordDecl>(
6649 StdBadAlloc.get(Context.getExternalSource()));
6650}
6651
6652NamespaceDecl *Sema::getStdNamespace() const {
6653 return cast_or_null<NamespaceDecl>(
6654 StdNamespace.get(Context.getExternalSource()));
6655}
6656
Douglas Gregor66992202010-06-29 17:53:46 +00006657/// \brief Retrieve the special "std" namespace, which may require us to
6658/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006659NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00006660 if (!StdNamespace) {
6661 // The "std" namespace has not yet been defined, so build one implicitly.
6662 StdNamespace = NamespaceDecl::Create(Context,
6663 Context.getTranslationUnitDecl(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006664 /*Inline=*/false,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006665 SourceLocation(), SourceLocation(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006666 &PP.getIdentifierTable().get("std"),
6667 /*PrevDecl=*/0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006668 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00006669 }
6670
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006671 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00006672}
6673
Sebastian Redl395e04d2012-01-17 22:49:33 +00006674bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006675 assert(getLangOpts().CPlusPlus &&
Sebastian Redl395e04d2012-01-17 22:49:33 +00006676 "Looking for std::initializer_list outside of C++.");
6677
6678 // We're looking for implicit instantiations of
6679 // template <typename E> class std::initializer_list.
6680
6681 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
6682 return false;
6683
Sebastian Redl84760e32012-01-17 22:49:58 +00006684 ClassTemplateDecl *Template = 0;
6685 const TemplateArgument *Arguments = 0;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006686
Sebastian Redl84760e32012-01-17 22:49:58 +00006687 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl395e04d2012-01-17 22:49:33 +00006688
Sebastian Redl84760e32012-01-17 22:49:58 +00006689 ClassTemplateSpecializationDecl *Specialization =
6690 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
6691 if (!Specialization)
6692 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006693
Sebastian Redl84760e32012-01-17 22:49:58 +00006694 Template = Specialization->getSpecializedTemplate();
6695 Arguments = Specialization->getTemplateArgs().data();
6696 } else if (const TemplateSpecializationType *TST =
6697 Ty->getAs<TemplateSpecializationType>()) {
6698 Template = dyn_cast_or_null<ClassTemplateDecl>(
6699 TST->getTemplateName().getAsTemplateDecl());
6700 Arguments = TST->getArgs();
6701 }
6702 if (!Template)
6703 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006704
6705 if (!StdInitializerList) {
6706 // Haven't recognized std::initializer_list yet, maybe this is it.
6707 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
6708 if (TemplateClass->getIdentifier() !=
6709 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006710 !getStdNamespace()->InEnclosingNamespaceSetOf(
6711 TemplateClass->getDeclContext()))
Sebastian Redl395e04d2012-01-17 22:49:33 +00006712 return false;
6713 // This is a template called std::initializer_list, but is it the right
6714 // template?
6715 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006716 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl395e04d2012-01-17 22:49:33 +00006717 return false;
6718 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
6719 return false;
6720
6721 // It's the right template.
6722 StdInitializerList = Template;
6723 }
6724
6725 if (Template != StdInitializerList)
6726 return false;
6727
6728 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl84760e32012-01-17 22:49:58 +00006729 if (Element)
6730 *Element = Arguments[0].getAsType();
Sebastian Redl395e04d2012-01-17 22:49:33 +00006731 return true;
6732}
6733
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006734static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
6735 NamespaceDecl *Std = S.getStdNamespace();
6736 if (!Std) {
6737 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6738 return 0;
6739 }
6740
6741 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
6742 Loc, Sema::LookupOrdinaryName);
6743 if (!S.LookupQualifiedName(Result, Std)) {
6744 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6745 return 0;
6746 }
6747 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
6748 if (!Template) {
6749 Result.suppressDiagnostics();
6750 // We found something weird. Complain about the first thing we found.
6751 NamedDecl *Found = *Result.begin();
6752 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
6753 return 0;
6754 }
6755
6756 // We found some template called std::initializer_list. Now verify that it's
6757 // correct.
6758 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006759 if (Params->getMinRequiredArguments() != 1 ||
6760 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006761 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
6762 return 0;
6763 }
6764
6765 return Template;
6766}
6767
6768QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
6769 if (!StdInitializerList) {
6770 StdInitializerList = LookupStdInitializerList(*this, Loc);
6771 if (!StdInitializerList)
6772 return QualType();
6773 }
6774
6775 TemplateArgumentListInfo Args(Loc, Loc);
6776 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
6777 Context.getTrivialTypeSourceInfo(Element,
6778 Loc)));
6779 return Context.getCanonicalType(
6780 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
6781}
6782
Sebastian Redl98d36062012-01-17 22:50:14 +00006783bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
6784 // C++ [dcl.init.list]p2:
6785 // A constructor is an initializer-list constructor if its first parameter
6786 // is of type std::initializer_list<E> or reference to possibly cv-qualified
6787 // std::initializer_list<E> for some type E, and either there are no other
6788 // parameters or else all other parameters have default arguments.
6789 if (Ctor->getNumParams() < 1 ||
6790 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
6791 return false;
6792
6793 QualType ArgType = Ctor->getParamDecl(0)->getType();
6794 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
6795 ArgType = RT->getPointeeType().getUnqualifiedType();
6796
6797 return isStdInitializerList(ArgType, 0);
6798}
6799
Douglas Gregor9172aa62011-03-26 22:25:30 +00006800/// \brief Determine whether a using statement is in a context where it will be
6801/// apply in all contexts.
6802static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
6803 switch (CurContext->getDeclKind()) {
6804 case Decl::TranslationUnit:
6805 return true;
6806 case Decl::LinkageSpec:
6807 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
6808 default:
6809 return false;
6810 }
6811}
6812
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006813namespace {
6814
6815// Callback to only accept typo corrections that are namespaces.
6816class NamespaceValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00006817public:
6818 bool ValidateCandidate(const TypoCorrection &candidate) LLVM_OVERRIDE {
6819 if (NamedDecl *ND = candidate.getCorrectionDecl())
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006820 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006821 return false;
6822 }
6823};
6824
6825}
6826
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006827static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
6828 CXXScopeSpec &SS,
6829 SourceLocation IdentLoc,
6830 IdentifierInfo *Ident) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006831 NamespaceValidatorCCC Validator;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006832 R.clear();
6833 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006834 R.getLookupKind(), Sc, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00006835 Validator)) {
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +00006836 if (DeclContext *DC = S.computeDeclContext(SS, false)) {
Richard Smith2d670972013-08-17 00:46:16 +00006837 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
6838 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +00006839 Ident->getName().equals(CorrectedStr);
Richard Smith2d670972013-08-17 00:46:16 +00006840 S.diagnoseTypo(Corrected,
6841 S.PDiag(diag::err_using_directive_member_suggest)
6842 << Ident << DC << DroppedSpecifier << SS.getRange(),
6843 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +00006844 } else {
Richard Smith2d670972013-08-17 00:46:16 +00006845 S.diagnoseTypo(Corrected,
6846 S.PDiag(diag::err_using_directive_suggest) << Ident,
6847 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +00006848 }
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006849 R.addDecl(Corrected.getCorrectionDecl());
6850 return true;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006851 }
6852 return false;
6853}
6854
John McCalld226f652010-08-21 09:40:31 +00006855Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006856 SourceLocation UsingLoc,
6857 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006858 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006859 SourceLocation IdentLoc,
6860 IdentifierInfo *NamespcName,
6861 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00006862 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6863 assert(NamespcName && "Invalid NamespcName.");
6864 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00006865
6866 // This can only happen along a recovery path.
6867 while (S->getFlags() & Scope::TemplateParamScope)
6868 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006869 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00006870
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006871 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00006872 NestedNameSpecifier *Qualifier = 0;
6873 if (SS.isSet())
6874 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
6875
Douglas Gregoreb11cd02009-01-14 22:20:51 +00006876 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00006877 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
6878 LookupParsedName(R, S, &SS);
6879 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00006880 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00006881
Douglas Gregor66992202010-06-29 17:53:46 +00006882 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006883 R.clear();
Douglas Gregor66992202010-06-29 17:53:46 +00006884 // Allow "using namespace std;" or "using namespace ::std;" even if
6885 // "std" hasn't been defined yet, for GCC compatibility.
6886 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
6887 NamespcName->isStr("std")) {
6888 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006889 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00006890 R.resolveKind();
6891 }
6892 // Otherwise, attempt typo correction.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006893 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00006894 }
6895
John McCallf36e02d2009-10-09 21:13:30 +00006896 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006897 NamedDecl *Named = R.getFoundDecl();
6898 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
6899 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006900 // C++ [namespace.udir]p1:
6901 // A using-directive specifies that the names in the nominated
6902 // namespace can be used in the scope in which the
6903 // using-directive appears after the using-directive. During
6904 // unqualified name lookup (3.4.1), the names appear as if they
6905 // were declared in the nearest enclosing namespace which
6906 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00006907 // namespace. [Note: in this context, "contains" means "contains
6908 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006909
6910 // Find enclosing context containing both using-directive and
6911 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006912 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006913 DeclContext *CommonAncestor = cast<DeclContext>(NS);
6914 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
6915 CommonAncestor = CommonAncestor->getParent();
6916
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006917 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregordb992412011-02-25 16:33:46 +00006918 SS.getWithLocInContext(Context),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006919 IdentLoc, Named, CommonAncestor);
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006920
Douglas Gregor9172aa62011-03-26 22:25:30 +00006921 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Eli Friedman24146972013-08-22 00:27:10 +00006922 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006923 Diag(IdentLoc, diag::warn_using_directive_in_header);
6924 }
6925
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006926 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006927 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00006928 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00006929 }
6930
Richard Smith6b3d3e52013-02-20 19:22:51 +00006931 if (UDir)
6932 ProcessDeclAttributeList(S, UDir, AttrList);
6933
John McCalld226f652010-08-21 09:40:31 +00006934 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006935}
6936
6937void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith1b7f9cb2012-03-13 03:12:56 +00006938 // If the scope has an associated entity and the using directive is at
6939 // namespace or translation unit scope, add the UsingDirectiveDecl into
6940 // its lookup structure so qualified name lookup can find it.
Ted Kremenekf0d58612013-10-08 17:08:03 +00006941 DeclContext *Ctx = S->getEntity();
Richard Smith1b7f9cb2012-03-13 03:12:56 +00006942 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006943 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006944 else
Richard Smith1b7f9cb2012-03-13 03:12:56 +00006945 // Otherwise, it is at block sope. The using-directives will affect lookup
6946 // only to the end of the scope.
John McCalld226f652010-08-21 09:40:31 +00006947 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006948}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006949
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006950
John McCalld226f652010-08-21 09:40:31 +00006951Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00006952 AccessSpecifier AS,
6953 bool HasUsingKeyword,
6954 SourceLocation UsingLoc,
6955 CXXScopeSpec &SS,
6956 UnqualifiedId &Name,
6957 AttributeList *AttrList,
Enea Zaffanella8d030c72013-07-22 10:54:09 +00006958 bool HasTypenameKeyword,
John McCall78b81052010-11-10 02:40:36 +00006959 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006960 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00006961
Douglas Gregor12c118a2009-11-04 16:30:06 +00006962 switch (Name.getKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00006963 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006964 case UnqualifiedId::IK_Identifier:
6965 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00006966 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006967 case UnqualifiedId::IK_ConversionFunctionId:
6968 break;
6969
6970 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00006971 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smitha1366cb2012-04-27 19:33:05 +00006972 // C++11 inheriting constructors.
Daniel Dunbar96a00142012-03-09 18:35:03 +00006973 Diag(Name.getLocStart(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006974 getLangOpts().CPlusPlus11 ?
Richard Smith07b0fdc2013-03-18 21:12:30 +00006975 diag::warn_cxx98_compat_using_decl_constructor :
Richard Smithebaf0e62011-10-18 20:49:44 +00006976 diag::err_using_decl_constructor)
6977 << SS.getRange();
6978
Richard Smith80ad52f2013-01-02 11:42:31 +00006979 if (getLangOpts().CPlusPlus11) break;
John McCall604e7f12009-12-08 07:46:18 +00006980
John McCalld226f652010-08-21 09:40:31 +00006981 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006982
6983 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar96a00142012-03-09 18:35:03 +00006984 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor12c118a2009-11-04 16:30:06 +00006985 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00006986 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006987
6988 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar96a00142012-03-09 18:35:03 +00006989 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor12c118a2009-11-04 16:30:06 +00006990 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00006991 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006992 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006993
6994 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
6995 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00006996 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00006997 return 0;
John McCall604e7f12009-12-08 07:46:18 +00006998
Richard Smith07b0fdc2013-03-18 21:12:30 +00006999 // Warn about access declarations.
John McCall60fa3cf2009-12-11 02:10:03 +00007000 if (!HasUsingKeyword) {
Enea Zaffanellad4de59d2013-07-17 17:28:56 +00007001 Diag(Name.getLocStart(),
Richard Smith1b2209f2013-06-13 02:12:17 +00007002 getLangOpts().CPlusPlus11 ? diag::err_access_decl
7003 : diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00007004 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00007005 }
7006
Douglas Gregor56c04582010-12-16 00:46:58 +00007007 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
7008 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
7009 return 0;
7010
John McCall9488ea12009-11-17 05:59:44 +00007011 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007012 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00007013 /* IsInstantiation */ false,
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007014 HasTypenameKeyword, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00007015 if (UD)
7016 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00007017
John McCalld226f652010-08-21 09:40:31 +00007018 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00007019}
7020
Douglas Gregor09acc982010-07-07 23:08:52 +00007021/// \brief Determine whether a using declaration considers the given
7022/// declarations as "equivalent", e.g., if they are redeclarations of
7023/// the same entity or are both typedefs of the same type.
Richard Smithf06a28932013-10-23 02:17:46 +00007024static bool
7025IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
7026 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
Douglas Gregor09acc982010-07-07 23:08:52 +00007027 return true;
Douglas Gregor09acc982010-07-07 23:08:52 +00007028
Richard Smith162e1c12011-04-15 14:24:37 +00007029 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
Richard Smithf06a28932013-10-23 02:17:46 +00007030 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
Douglas Gregor09acc982010-07-07 23:08:52 +00007031 return Context.hasSameType(TD1->getUnderlyingType(),
7032 TD2->getUnderlyingType());
Douglas Gregor09acc982010-07-07 23:08:52 +00007033
7034 return false;
7035}
7036
7037
John McCall9f54ad42009-12-10 09:41:52 +00007038/// Determines whether to create a using shadow decl for a particular
7039/// decl, given the set of decls existing prior to this using lookup.
7040bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
Richard Smithf06a28932013-10-23 02:17:46 +00007041 const LookupResult &Previous,
7042 UsingShadowDecl *&PrevShadow) {
John McCall9f54ad42009-12-10 09:41:52 +00007043 // Diagnose finding a decl which is not from a base class of the
7044 // current class. We do this now because there are cases where this
7045 // function will silently decide not to build a shadow decl, which
7046 // will pre-empt further diagnostics.
7047 //
7048 // We don't need to do this in C++0x because we do the check once on
7049 // the qualifier.
7050 //
7051 // FIXME: diagnose the following if we care enough:
7052 // struct A { int foo; };
7053 // struct B : A { using A::foo; };
7054 // template <class T> struct C : A {};
7055 // template <class T> struct D : C<T> { using B::foo; } // <---
7056 // This is invalid (during instantiation) in C++03 because B::foo
7057 // resolves to the using decl in B, which is not a base class of D<T>.
7058 // We can't diagnose it immediately because C<T> is an unknown
7059 // specialization. The UsingShadowDecl in D<T> then points directly
7060 // to A::foo, which will look well-formed when we instantiate.
7061 // The right solution is to not collapse the shadow-decl chain.
Richard Smith80ad52f2013-01-02 11:42:31 +00007062 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
John McCall9f54ad42009-12-10 09:41:52 +00007063 DeclContext *OrigDC = Orig->getDeclContext();
7064
7065 // Handle enums and anonymous structs.
7066 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
7067 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
7068 while (OrigRec->isAnonymousStructOrUnion())
7069 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
7070
7071 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
7072 if (OrigDC == CurContext) {
7073 Diag(Using->getLocation(),
7074 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregordc355712011-02-25 00:36:19 +00007075 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00007076 Diag(Orig->getLocation(), diag::note_using_decl_target);
7077 return true;
7078 }
7079
Douglas Gregordc355712011-02-25 00:36:19 +00007080 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall9f54ad42009-12-10 09:41:52 +00007081 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregordc355712011-02-25 00:36:19 +00007082 << Using->getQualifier()
John McCall9f54ad42009-12-10 09:41:52 +00007083 << cast<CXXRecordDecl>(CurContext)
Douglas Gregordc355712011-02-25 00:36:19 +00007084 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00007085 Diag(Orig->getLocation(), diag::note_using_decl_target);
7086 return true;
7087 }
7088 }
7089
7090 if (Previous.empty()) return false;
7091
7092 NamedDecl *Target = Orig;
7093 if (isa<UsingShadowDecl>(Target))
7094 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7095
John McCalld7533ec2009-12-11 02:33:26 +00007096 // If the target happens to be one of the previous declarations, we
7097 // don't have a conflict.
7098 //
7099 // FIXME: but we might be increasing its access, in which case we
7100 // should redeclare it.
7101 NamedDecl *NonTag = 0, *Tag = 0;
Richard Smithf06a28932013-10-23 02:17:46 +00007102 bool FoundEquivalentDecl = false;
John McCalld7533ec2009-12-11 02:33:26 +00007103 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7104 I != E; ++I) {
7105 NamedDecl *D = (*I)->getUnderlyingDecl();
Richard Smithf06a28932013-10-23 02:17:46 +00007106 if (IsEquivalentForUsingDecl(Context, D, Target)) {
7107 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
7108 PrevShadow = Shadow;
7109 FoundEquivalentDecl = true;
7110 }
John McCalld7533ec2009-12-11 02:33:26 +00007111
7112 (isa<TagDecl>(D) ? Tag : NonTag) = D;
7113 }
7114
Richard Smithf06a28932013-10-23 02:17:46 +00007115 if (FoundEquivalentDecl)
7116 return false;
7117
John McCall9f54ad42009-12-10 09:41:52 +00007118 if (Target->isFunctionOrFunctionTemplate()) {
7119 FunctionDecl *FD;
7120 if (isa<FunctionTemplateDecl>(Target))
7121 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
7122 else
7123 FD = cast<FunctionDecl>(Target);
7124
7125 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00007126 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00007127 case Ovl_Overload:
7128 return false;
7129
7130 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00007131 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00007132 break;
7133
7134 // We found a decl with the exact signature.
7135 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00007136 // If we're in a record, we want to hide the target, so we
7137 // return true (without a diagnostic) to tell the caller not to
7138 // build a shadow decl.
7139 if (CurContext->isRecord())
7140 return true;
7141
7142 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00007143 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00007144 break;
7145 }
7146
7147 Diag(Target->getLocation(), diag::note_using_decl_target);
7148 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
7149 return true;
7150 }
7151
7152 // Target is not a function.
7153
John McCall9f54ad42009-12-10 09:41:52 +00007154 if (isa<TagDecl>(Target)) {
7155 // No conflict between a tag and a non-tag.
7156 if (!Tag) return false;
7157
John McCall41ce66f2009-12-10 19:51:03 +00007158 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00007159 Diag(Target->getLocation(), diag::note_using_decl_target);
7160 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
7161 return true;
7162 }
7163
7164 // No conflict between a tag and a non-tag.
7165 if (!NonTag) return false;
7166
John McCall41ce66f2009-12-10 19:51:03 +00007167 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00007168 Diag(Target->getLocation(), diag::note_using_decl_target);
7169 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
7170 return true;
7171}
7172
John McCall9488ea12009-11-17 05:59:44 +00007173/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00007174UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00007175 UsingDecl *UD,
Richard Smithf06a28932013-10-23 02:17:46 +00007176 NamedDecl *Orig,
7177 UsingShadowDecl *PrevDecl) {
John McCall9488ea12009-11-17 05:59:44 +00007178
7179 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00007180 NamedDecl *Target = Orig;
7181 if (isa<UsingShadowDecl>(Target)) {
7182 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7183 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00007184 }
Richard Smithf06a28932013-10-23 02:17:46 +00007185
John McCall9488ea12009-11-17 05:59:44 +00007186 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00007187 = UsingShadowDecl::Create(Context, CurContext,
7188 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00007189 UD->addShadowDecl(Shadow);
Richard Smithf06a28932013-10-23 02:17:46 +00007190
Douglas Gregore80622f2010-09-29 04:25:11 +00007191 Shadow->setAccess(UD->getAccess());
7192 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
7193 Shadow->setInvalidDecl();
Richard Smithf06a28932013-10-23 02:17:46 +00007194
7195 Shadow->setPreviousDecl(PrevDecl);
7196
John McCall9488ea12009-11-17 05:59:44 +00007197 if (S)
John McCall604e7f12009-12-08 07:46:18 +00007198 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00007199 else
John McCall604e7f12009-12-08 07:46:18 +00007200 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00007201
John McCall604e7f12009-12-08 07:46:18 +00007202
John McCall9f54ad42009-12-10 09:41:52 +00007203 return Shadow;
7204}
John McCall604e7f12009-12-08 07:46:18 +00007205
John McCall9f54ad42009-12-10 09:41:52 +00007206/// Hides a using shadow declaration. This is required by the current
7207/// using-decl implementation when a resolvable using declaration in a
7208/// class is followed by a declaration which would hide or override
7209/// one or more of the using decl's targets; for example:
7210///
7211/// struct Base { void foo(int); };
7212/// struct Derived : Base {
7213/// using Base::foo;
7214/// void foo(int);
7215/// };
7216///
7217/// The governing language is C++03 [namespace.udecl]p12:
7218///
7219/// When a using-declaration brings names from a base class into a
7220/// derived class scope, member functions in the derived class
7221/// override and/or hide member functions with the same name and
7222/// parameter types in a base class (rather than conflicting).
7223///
7224/// There are two ways to implement this:
7225/// (1) optimistically create shadow decls when they're not hidden
7226/// by existing declarations, or
7227/// (2) don't create any shadow decls (or at least don't make them
7228/// visible) until we've fully parsed/instantiated the class.
7229/// The problem with (1) is that we might have to retroactively remove
7230/// a shadow decl, which requires several O(n) operations because the
7231/// decl structures are (very reasonably) not designed for removal.
7232/// (2) avoids this but is very fiddly and phase-dependent.
7233void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00007234 if (Shadow->getDeclName().getNameKind() ==
7235 DeclarationName::CXXConversionFunctionName)
7236 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
7237
John McCall9f54ad42009-12-10 09:41:52 +00007238 // Remove it from the DeclContext...
7239 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00007240
John McCall9f54ad42009-12-10 09:41:52 +00007241 // ...and the scope, if applicable...
7242 if (S) {
John McCalld226f652010-08-21 09:40:31 +00007243 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00007244 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00007245 }
7246
John McCall9f54ad42009-12-10 09:41:52 +00007247 // ...and the using decl.
7248 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
7249
7250 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00007251 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00007252}
7253
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00007254namespace {
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007255class UsingValidatorCCC : public CorrectionCandidateCallback {
7256public:
Kaelyn Uhrainb5c77682013-10-19 00:05:00 +00007257 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
7258 bool RequireMember)
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007259 : HasTypenameKeyword(HasTypenameKeyword),
Kaelyn Uhrainb5c77682013-10-19 00:05:00 +00007260 IsInstantiation(IsInstantiation), RequireMember(RequireMember) {}
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007261
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00007262 bool ValidateCandidate(const TypoCorrection &Candidate) LLVM_OVERRIDE {
7263 NamedDecl *ND = Candidate.getCorrectionDecl();
7264
7265 // Keywords are not valid here.
7266 if (!ND || isa<NamespaceDecl>(ND))
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007267 return false;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00007268
Kaelyn Uhrainb5c77682013-10-19 00:05:00 +00007269 if (RequireMember && !isa<FieldDecl>(ND) && !isa<CXXMethodDecl>(ND) &&
7270 !isa<TypeDecl>(ND))
7271 return false;
7272
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00007273 // Completely unqualified names are invalid for a 'using' declaration.
7274 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
7275 return false;
7276
7277 if (isa<TypeDecl>(ND))
7278 return HasTypenameKeyword || !IsInstantiation;
7279
7280 return !HasTypenameKeyword;
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007281 }
7282
7283private:
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007284 bool HasTypenameKeyword;
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007285 bool IsInstantiation;
Kaelyn Uhrainb5c77682013-10-19 00:05:00 +00007286 bool RequireMember;
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007287};
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00007288} // end anonymous namespace
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007289
John McCall7ba107a2009-11-18 02:36:19 +00007290/// Builds a using declaration.
7291///
7292/// \param IsInstantiation - Whether this call arises from an
7293/// instantiation of an unresolved using declaration. We treat
7294/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00007295NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
7296 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00007297 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007298 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00007299 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00007300 bool IsInstantiation,
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007301 bool HasTypenameKeyword,
John McCall7ba107a2009-11-18 02:36:19 +00007302 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00007303 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007304 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00007305 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00007306
Anders Carlsson550b14b2009-08-28 05:49:21 +00007307 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00007308
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007309 if (SS.isEmpty()) {
7310 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00007311 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007312 }
Mike Stump1eb44332009-09-09 15:08:12 +00007313
John McCall9f54ad42009-12-10 09:41:52 +00007314 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007315 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00007316 ForRedeclaration);
7317 Previous.setHideTags(false);
7318 if (S) {
7319 LookupName(Previous, S);
7320
7321 // It is really dumb that we have to do this.
7322 LookupResult::Filter F = Previous.makeFilter();
7323 while (F.hasNext()) {
7324 NamedDecl *D = F.next();
7325 if (!isDeclInScope(D, CurContext, S))
7326 F.erase();
7327 }
7328 F.done();
7329 } else {
7330 assert(IsInstantiation && "no scope in non-instantiation");
7331 assert(CurContext->isRecord() && "scope not record in instantiation");
7332 LookupQualifiedName(Previous, CurContext);
7333 }
7334
John McCall9f54ad42009-12-10 09:41:52 +00007335 // Check for invalid redeclarations.
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007336 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
7337 SS, IdentLoc, Previous))
John McCall9f54ad42009-12-10 09:41:52 +00007338 return 0;
7339
7340 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00007341 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
7342 return 0;
7343
John McCallaf8e6ed2009-11-12 03:15:40 +00007344 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00007345 NamedDecl *D;
Douglas Gregordc355712011-02-25 00:36:19 +00007346 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallaf8e6ed2009-11-12 03:15:40 +00007347 if (!LookupContext) {
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007348 if (HasTypenameKeyword) {
John McCalled976492009-12-04 22:46:56 +00007349 // FIXME: not all declaration name kinds are legal here
7350 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
7351 UsingLoc, TypenameLoc,
Douglas Gregordc355712011-02-25 00:36:19 +00007352 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007353 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00007354 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00007355 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
7356 QualifierLoc, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00007357 }
John McCalled976492009-12-04 22:46:56 +00007358 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00007359 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007360 NameInfo, HasTypenameKeyword);
Anders Carlsson550b14b2009-08-28 05:49:21 +00007361 }
John McCalled976492009-12-04 22:46:56 +00007362 D->setAccess(AS);
7363 CurContext->addDecl(D);
7364
7365 if (!LookupContext) return D;
7366 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00007367
John McCall77bb1aa2010-05-01 00:40:08 +00007368 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00007369 UD->setInvalidDecl();
7370 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007371 }
7372
Richard Smithc5a89a12012-04-02 01:30:27 +00007373 // The normal rules do not apply to inheriting constructor declarations.
Sebastian Redlf677ea32011-02-05 19:23:19 +00007374 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Richard Smithc5a89a12012-04-02 01:30:27 +00007375 if (CheckInheritingConstructorUsingDecl(UD))
Sebastian Redlcaa35e42011-03-12 13:44:32 +00007376 UD->setInvalidDecl();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007377 return UD;
7378 }
7379
7380 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00007381
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007382 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00007383
John McCall604e7f12009-12-08 07:46:18 +00007384 // Unlike most lookups, we don't always want to hide tag
7385 // declarations: tag names are visible through the using declaration
7386 // even if hidden by ordinary names, *except* in a dependent context
7387 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00007388 if (!IsInstantiation)
7389 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00007390
John McCallb9abd8722012-04-07 03:04:20 +00007391 // For the purposes of this lookup, we have a base object type
7392 // equal to that of the current context.
7393 if (CurContext->isRecord()) {
7394 R.setBaseObjectType(
7395 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
7396 }
7397
John McCalla24dc2e2009-11-17 02:14:36 +00007398 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00007399
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007400 // Try to correct typos if possible.
John McCallf36e02d2009-10-09 21:13:30 +00007401 if (R.empty()) {
Kaelyn Uhrainb5c77682013-10-19 00:05:00 +00007402 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation,
7403 CurContext->isRecord());
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007404 if (TypoCorrection Corrected = CorrectTypo(R.getLookupNameInfo(),
7405 R.getLookupKind(), S, &SS, CCC)){
7406 // We reject any correction for which ND would be NULL.
7407 NamedDecl *ND = Corrected.getCorrectionDecl();
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007408 R.setLookupName(Corrected.getCorrection());
7409 R.addDecl(ND);
Richard Smith2d670972013-08-17 00:46:16 +00007410 // We reject candidates where DroppedSpecifier == true, hence the
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007411 // literal '0' below.
Richard Smith2d670972013-08-17 00:46:16 +00007412 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
7413 << NameInfo.getName() << LookupContext << 0
7414 << SS.getRange());
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007415 } else {
Richard Smith2d670972013-08-17 00:46:16 +00007416 Diag(IdentLoc, diag::err_no_member)
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007417 << NameInfo.getName() << LookupContext << SS.getRange();
7418 UD->setInvalidDecl();
7419 return UD;
7420 }
Douglas Gregor9cfbe482009-06-20 00:51:54 +00007421 }
7422
John McCalled976492009-12-04 22:46:56 +00007423 if (R.isAmbiguous()) {
7424 UD->setInvalidDecl();
7425 return UD;
7426 }
Mike Stump1eb44332009-09-09 15:08:12 +00007427
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007428 if (HasTypenameKeyword) {
John McCall7ba107a2009-11-18 02:36:19 +00007429 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00007430 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00007431 Diag(IdentLoc, diag::err_using_typename_non_type);
7432 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
7433 Diag((*I)->getUnderlyingDecl()->getLocation(),
7434 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00007435 UD->setInvalidDecl();
7436 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00007437 }
7438 } else {
7439 // If we asked for a non-typename and we got a type, error out,
7440 // but only if this is an instantiation of an unresolved using
7441 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00007442 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00007443 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
7444 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00007445 UD->setInvalidDecl();
7446 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00007447 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007448 }
7449
Anders Carlsson73b39cf2009-08-28 03:35:18 +00007450 // C++0x N2914 [namespace.udecl]p6:
7451 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00007452 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00007453 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
7454 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00007455 UD->setInvalidDecl();
7456 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00007457 }
Mike Stump1eb44332009-09-09 15:08:12 +00007458
John McCall9f54ad42009-12-10 09:41:52 +00007459 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
Richard Smithf06a28932013-10-23 02:17:46 +00007460 UsingShadowDecl *PrevDecl = 0;
7461 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
7462 BuildUsingShadowDecl(S, UD, *I, PrevDecl);
John McCall9f54ad42009-12-10 09:41:52 +00007463 }
John McCall9488ea12009-11-17 05:59:44 +00007464
7465 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00007466}
7467
Sebastian Redlf677ea32011-02-05 19:23:19 +00007468/// Additional checks for a using declaration referring to a constructor name.
Richard Smithc5a89a12012-04-02 01:30:27 +00007469bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007470 assert(!UD->hasTypename() && "expecting a constructor name");
Sebastian Redlf677ea32011-02-05 19:23:19 +00007471
Douglas Gregordc355712011-02-25 00:36:19 +00007472 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007473 assert(SourceType &&
7474 "Using decl naming constructor doesn't have type in scope spec.");
7475 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
7476
7477 // Check whether the named type is a direct base class.
7478 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
7479 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
7480 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
7481 BaseIt != BaseE; ++BaseIt) {
7482 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
7483 if (CanonicalSourceType == BaseType)
7484 break;
Richard Smithc5a89a12012-04-02 01:30:27 +00007485 if (BaseIt->getType()->isDependentType())
7486 break;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007487 }
7488
7489 if (BaseIt == BaseE) {
7490 // Did not find SourceType in the bases.
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007491 Diag(UD->getUsingLoc(),
Sebastian Redlf677ea32011-02-05 19:23:19 +00007492 diag::err_using_decl_constructor_not_in_direct_base)
7493 << UD->getNameInfo().getSourceRange()
7494 << QualType(SourceType, 0) << TargetClass;
7495 return true;
7496 }
7497
Richard Smithc5a89a12012-04-02 01:30:27 +00007498 if (!CurContext->isDependentContext())
7499 BaseIt->setInheritConstructors();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007500
7501 return false;
7502}
7503
John McCall9f54ad42009-12-10 09:41:52 +00007504/// Checks that the given using declaration is not an invalid
7505/// redeclaration. Note that this is checking only for the using decl
7506/// itself, not for any ill-formedness among the UsingShadowDecls.
7507bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007508 bool HasTypenameKeyword,
John McCall9f54ad42009-12-10 09:41:52 +00007509 const CXXScopeSpec &SS,
7510 SourceLocation NameLoc,
7511 const LookupResult &Prev) {
7512 // C++03 [namespace.udecl]p8:
7513 // C++0x [namespace.udecl]p10:
7514 // A using-declaration is a declaration and can therefore be used
7515 // repeatedly where (and only where) multiple declarations are
7516 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00007517 //
John McCall8a726212010-11-29 18:01:58 +00007518 // That's in non-member contexts.
7519 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00007520 return false;
7521
7522 NestedNameSpecifier *Qual
7523 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
7524
7525 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
7526 NamedDecl *D = *I;
7527
7528 bool DTypename;
7529 NestedNameSpecifier *DQual;
7530 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007531 DTypename = UD->hasTypename();
Douglas Gregordc355712011-02-25 00:36:19 +00007532 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007533 } else if (UnresolvedUsingValueDecl *UD
7534 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
7535 DTypename = false;
Douglas Gregordc355712011-02-25 00:36:19 +00007536 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007537 } else if (UnresolvedUsingTypenameDecl *UD
7538 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
7539 DTypename = true;
Douglas Gregordc355712011-02-25 00:36:19 +00007540 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007541 } else continue;
7542
7543 // using decls differ if one says 'typename' and the other doesn't.
7544 // FIXME: non-dependent using decls?
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007545 if (HasTypenameKeyword != DTypename) continue;
John McCall9f54ad42009-12-10 09:41:52 +00007546
7547 // using decls differ if they name different scopes (but note that
7548 // template instantiation can cause this check to trigger when it
7549 // didn't before instantiation).
7550 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
7551 Context.getCanonicalNestedNameSpecifier(DQual))
7552 continue;
7553
7554 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00007555 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00007556 return true;
7557 }
7558
7559 return false;
7560}
7561
John McCall604e7f12009-12-08 07:46:18 +00007562
John McCalled976492009-12-04 22:46:56 +00007563/// Checks that the given nested-name qualifier used in a using decl
7564/// in the current context is appropriately related to the current
7565/// scope. If an error is found, diagnoses it and returns true.
7566bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
7567 const CXXScopeSpec &SS,
7568 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00007569 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00007570
John McCall604e7f12009-12-08 07:46:18 +00007571 if (!CurContext->isRecord()) {
7572 // C++03 [namespace.udecl]p3:
7573 // C++0x [namespace.udecl]p8:
7574 // A using-declaration for a class member shall be a member-declaration.
7575
7576 // If we weren't able to compute a valid scope, it must be a
7577 // dependent class scope.
7578 if (!NamedContext || NamedContext->isRecord()) {
7579 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
7580 << SS.getRange();
7581 return true;
7582 }
7583
7584 // Otherwise, everything is known to be fine.
7585 return false;
7586 }
7587
7588 // The current scope is a record.
7589
7590 // If the named context is dependent, we can't decide much.
7591 if (!NamedContext) {
7592 // FIXME: in C++0x, we can diagnose if we can prove that the
7593 // nested-name-specifier does not refer to a base class, which is
7594 // still possible in some cases.
7595
7596 // Otherwise we have to conservatively report that things might be
7597 // okay.
7598 return false;
7599 }
7600
7601 if (!NamedContext->isRecord()) {
7602 // Ideally this would point at the last name in the specifier,
7603 // but we don't have that level of source info.
7604 Diag(SS.getRange().getBegin(),
7605 diag::err_using_decl_nested_name_specifier_is_not_class)
7606 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
7607 return true;
7608 }
7609
Douglas Gregor6fb07292010-12-21 07:41:49 +00007610 if (!NamedContext->isDependentContext() &&
7611 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
7612 return true;
7613
Richard Smith80ad52f2013-01-02 11:42:31 +00007614 if (getLangOpts().CPlusPlus11) {
John McCall604e7f12009-12-08 07:46:18 +00007615 // C++0x [namespace.udecl]p3:
7616 // In a using-declaration used as a member-declaration, the
7617 // nested-name-specifier shall name a base class of the class
7618 // being defined.
7619
7620 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
7621 cast<CXXRecordDecl>(NamedContext))) {
7622 if (CurContext == NamedContext) {
7623 Diag(NameLoc,
7624 diag::err_using_decl_nested_name_specifier_is_current_class)
7625 << SS.getRange();
7626 return true;
7627 }
7628
7629 Diag(SS.getRange().getBegin(),
7630 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7631 << (NestedNameSpecifier*) SS.getScopeRep()
7632 << cast<CXXRecordDecl>(CurContext)
7633 << SS.getRange();
7634 return true;
7635 }
7636
7637 return false;
7638 }
7639
7640 // C++03 [namespace.udecl]p4:
7641 // A using-declaration used as a member-declaration shall refer
7642 // to a member of a base class of the class being defined [etc.].
7643
7644 // Salient point: SS doesn't have to name a base class as long as
7645 // lookup only finds members from base classes. Therefore we can
7646 // diagnose here only if we can prove that that can't happen,
7647 // i.e. if the class hierarchies provably don't intersect.
7648
7649 // TODO: it would be nice if "definitely valid" results were cached
7650 // in the UsingDecl and UsingShadowDecl so that these checks didn't
7651 // need to be repeated.
7652
7653 struct UserData {
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00007654 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
John McCall604e7f12009-12-08 07:46:18 +00007655
7656 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
7657 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7658 Data->Bases.insert(Base);
7659 return true;
7660 }
7661
7662 bool hasDependentBases(const CXXRecordDecl *Class) {
7663 return !Class->forallBases(collect, this);
7664 }
7665
7666 /// Returns true if the base is dependent or is one of the
7667 /// accumulated base classes.
7668 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
7669 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7670 return !Data->Bases.count(Base);
7671 }
7672
7673 bool mightShareBases(const CXXRecordDecl *Class) {
7674 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
7675 }
7676 };
7677
7678 UserData Data;
7679
7680 // Returns false if we find a dependent base.
7681 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
7682 return false;
7683
7684 // Returns false if the class has a dependent base or if it or one
7685 // of its bases is present in the base set of the current context.
7686 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
7687 return false;
7688
7689 Diag(SS.getRange().getBegin(),
7690 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7691 << (NestedNameSpecifier*) SS.getScopeRep()
7692 << cast<CXXRecordDecl>(CurContext)
7693 << SS.getRange();
7694
7695 return true;
John McCalled976492009-12-04 22:46:56 +00007696}
7697
Richard Smith162e1c12011-04-15 14:24:37 +00007698Decl *Sema::ActOnAliasDeclaration(Scope *S,
7699 AccessSpecifier AS,
Richard Smith3e4c6c42011-05-05 21:57:07 +00007700 MultiTemplateParamsArg TemplateParamLists,
Richard Smith162e1c12011-04-15 14:24:37 +00007701 SourceLocation UsingLoc,
7702 UnqualifiedId &Name,
Richard Smith6b3d3e52013-02-20 19:22:51 +00007703 AttributeList *AttrList,
Richard Smith162e1c12011-04-15 14:24:37 +00007704 TypeResult Type) {
Richard Smith3e4c6c42011-05-05 21:57:07 +00007705 // Skip up to the relevant declaration scope.
7706 while (S->getFlags() & Scope::TemplateParamScope)
7707 S = S->getParent();
Richard Smith162e1c12011-04-15 14:24:37 +00007708 assert((S->getFlags() & Scope::DeclScope) &&
7709 "got alias-declaration outside of declaration scope");
7710
7711 if (Type.isInvalid())
7712 return 0;
7713
7714 bool Invalid = false;
7715 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
7716 TypeSourceInfo *TInfo = 0;
Nick Lewyckyb79bf1d2011-05-02 01:07:19 +00007717 GetTypeFromParser(Type.get(), &TInfo);
Richard Smith162e1c12011-04-15 14:24:37 +00007718
7719 if (DiagnoseClassNameShadow(CurContext, NameInfo))
7720 return 0;
7721
7722 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3e4c6c42011-05-05 21:57:07 +00007723 UPPC_DeclarationType)) {
Richard Smith162e1c12011-04-15 14:24:37 +00007724 Invalid = true;
Richard Smith3e4c6c42011-05-05 21:57:07 +00007725 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
7726 TInfo->getTypeLoc().getBeginLoc());
7727 }
Richard Smith162e1c12011-04-15 14:24:37 +00007728
7729 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
7730 LookupName(Previous, S);
7731
7732 // Warn about shadowing the name of a template parameter.
7733 if (Previous.isSingleResult() &&
7734 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorcb8f9512011-10-20 17:58:49 +00007735 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smith162e1c12011-04-15 14:24:37 +00007736 Previous.clear();
7737 }
7738
7739 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
7740 "name in alias declaration must be an identifier");
7741 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
7742 Name.StartLocation,
7743 Name.Identifier, TInfo);
7744
7745 NewTD->setAccess(AS);
7746
7747 if (Invalid)
7748 NewTD->setInvalidDecl();
7749
Richard Smith6b3d3e52013-02-20 19:22:51 +00007750 ProcessDeclAttributeList(S, NewTD, AttrList);
7751
Richard Smith3e4c6c42011-05-05 21:57:07 +00007752 CheckTypedefForVariablyModifiedType(S, NewTD);
7753 Invalid |= NewTD->isInvalidDecl();
7754
Richard Smith162e1c12011-04-15 14:24:37 +00007755 bool Redeclaration = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00007756
7757 NamedDecl *NewND;
7758 if (TemplateParamLists.size()) {
7759 TypeAliasTemplateDecl *OldDecl = 0;
7760 TemplateParameterList *OldTemplateParams = 0;
7761
7762 if (TemplateParamLists.size() != 1) {
7763 Diag(UsingLoc, diag::err_alias_template_extra_headers)
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007764 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
7765 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
Richard Smith3e4c6c42011-05-05 21:57:07 +00007766 }
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007767 TemplateParameterList *TemplateParams = TemplateParamLists[0];
Richard Smith3e4c6c42011-05-05 21:57:07 +00007768
7769 // Only consider previous declarations in the same scope.
7770 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
7771 /*ExplicitInstantiationOrSpecialization*/false);
7772 if (!Previous.empty()) {
7773 Redeclaration = true;
7774
7775 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
7776 if (!OldDecl && !Invalid) {
7777 Diag(UsingLoc, diag::err_redefinition_different_kind)
7778 << Name.Identifier;
7779
7780 NamedDecl *OldD = Previous.getRepresentativeDecl();
7781 if (OldD->getLocation().isValid())
7782 Diag(OldD->getLocation(), diag::note_previous_definition);
7783
7784 Invalid = true;
7785 }
7786
7787 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
7788 if (TemplateParameterListsAreEqual(TemplateParams,
7789 OldDecl->getTemplateParameters(),
7790 /*Complain=*/true,
7791 TPL_TemplateMatch))
7792 OldTemplateParams = OldDecl->getTemplateParameters();
7793 else
7794 Invalid = true;
7795
7796 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
7797 if (!Invalid &&
7798 !Context.hasSameType(OldTD->getUnderlyingType(),
7799 NewTD->getUnderlyingType())) {
7800 // FIXME: The C++0x standard does not clearly say this is ill-formed,
7801 // but we can't reasonably accept it.
7802 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
7803 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
7804 if (OldTD->getLocation().isValid())
7805 Diag(OldTD->getLocation(), diag::note_previous_definition);
7806 Invalid = true;
7807 }
7808 }
7809 }
7810
7811 // Merge any previous default template arguments into our parameters,
7812 // and check the parameter list.
7813 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
7814 TPC_TypeAliasTemplate))
7815 return 0;
7816
7817 TypeAliasTemplateDecl *NewDecl =
7818 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
7819 Name.Identifier, TemplateParams,
7820 NewTD);
7821
7822 NewDecl->setAccess(AS);
7823
7824 if (Invalid)
7825 NewDecl->setInvalidDecl();
7826 else if (OldDecl)
Rafael Espindolabc650912013-10-17 15:37:26 +00007827 NewDecl->setPreviousDecl(OldDecl);
Richard Smith3e4c6c42011-05-05 21:57:07 +00007828
7829 NewND = NewDecl;
7830 } else {
7831 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
7832 NewND = NewTD;
7833 }
Richard Smith162e1c12011-04-15 14:24:37 +00007834
7835 if (!Redeclaration)
Richard Smith3e4c6c42011-05-05 21:57:07 +00007836 PushOnScopeChains(NewND, S);
Richard Smith162e1c12011-04-15 14:24:37 +00007837
Dmitri Gribenkoc27bc802012-08-02 20:49:51 +00007838 ActOnDocumentableDecl(NewND);
Richard Smith3e4c6c42011-05-05 21:57:07 +00007839 return NewND;
Richard Smith162e1c12011-04-15 14:24:37 +00007840}
7841
John McCalld226f652010-08-21 09:40:31 +00007842Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00007843 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00007844 SourceLocation AliasLoc,
7845 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00007846 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00007847 SourceLocation IdentLoc,
7848 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00007849
Anders Carlsson81c85c42009-03-28 23:53:49 +00007850 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00007851 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
7852 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00007853
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007854 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00007855 NamedDecl *PrevDecl
7856 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
7857 ForRedeclaration);
7858 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
7859 PrevDecl = 0;
7860
7861 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00007862 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00007863 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00007864 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00007865 // FIXME: At some point, we'll want to create the (redundant)
7866 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00007867 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00007868 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00007869 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00007870 }
Mike Stump1eb44332009-09-09 15:08:12 +00007871
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007872 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
7873 diag::err_redefinition_different_kind;
7874 Diag(AliasLoc, DiagID) << Alias;
7875 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00007876 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007877 }
7878
John McCalla24dc2e2009-11-17 02:14:36 +00007879 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00007880 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00007881
John McCallf36e02d2009-10-09 21:13:30 +00007882 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00007883 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smithbf9658c2012-04-05 23:13:23 +00007884 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00007885 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00007886 }
Anders Carlsson5721c682009-03-28 06:42:02 +00007887 }
Mike Stump1eb44332009-09-09 15:08:12 +00007888
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007889 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00007890 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00007891 Alias, SS.getWithLocInContext(Context),
John McCallf36e02d2009-10-09 21:13:30 +00007892 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00007893
John McCall3dbd3d52010-02-16 06:53:13 +00007894 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00007895 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00007896}
7897
Sean Hunt001cad92011-05-10 00:49:42 +00007898Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00007899Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
7900 CXXMethodDecl *MD) {
7901 CXXRecordDecl *ClassDecl = MD->getParent();
7902
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007903 // C++ [except.spec]p14:
7904 // An implicitly declared special member function (Clause 12) shall have an
7905 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00007906 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007907 if (ClassDecl->isInvalidDecl())
7908 return ExceptSpec;
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007909
Sebastian Redl60618fa2011-03-12 11:50:43 +00007910 // Direct base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007911 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7912 BEnd = ClassDecl->bases_end();
7913 B != BEnd; ++B) {
7914 if (B->isVirtual()) // Handled below.
7915 continue;
7916
Douglas Gregor18274032010-07-03 00:47:00 +00007917 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7918 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007919 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7920 // If this is a deleted function, add it anyway. This might be conformant
7921 // with the standard. This might not. I'm not sure. It might not matter.
7922 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007923 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007924 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007925 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007926
7927 // Virtual base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007928 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7929 BEnd = ClassDecl->vbases_end();
7930 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00007931 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7932 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007933 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7934 // If this is a deleted function, add it anyway. This might be conformant
7935 // with the standard. This might not. I'm not sure. It might not matter.
7936 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007937 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007938 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007939 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007940
7941 // Field constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007942 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7943 FEnd = ClassDecl->field_end();
7944 F != FEnd; ++F) {
Richard Smith7a614d82011-06-11 17:19:42 +00007945 if (F->hasInClassInitializer()) {
7946 if (Expr *E = F->getInClassInitializer())
7947 ExceptSpec.CalledExpr(E);
7948 else if (!F->isInvalidDecl())
Richard Smithb9d0b762012-07-27 04:22:15 +00007949 // DR1351:
7950 // If the brace-or-equal-initializer of a non-static data member
7951 // invokes a defaulted default constructor of its class or of an
7952 // enclosing class in a potentially evaluated subexpression, the
7953 // program is ill-formed.
7954 //
7955 // This resolution is unworkable: the exception specification of the
7956 // default constructor can be needed in an unevaluated context, in
7957 // particular, in the operand of a noexcept-expression, and we can be
7958 // unable to compute an exception specification for an enclosed class.
7959 //
7960 // We do not allow an in-class initializer to require the evaluation
7961 // of the exception specification for any in-class initializer whose
7962 // definition is not lexically complete.
7963 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
Richard Smith7a614d82011-06-11 17:19:42 +00007964 } else if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00007965 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Sean Huntb320e0c2011-06-10 03:50:41 +00007966 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7967 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7968 // If this is a deleted function, add it anyway. This might be conformant
7969 // with the standard. This might not. I'm not sure. It might not matter.
7970 // In particular, the problem is that this function never gets called. It
7971 // might just be ill-formed because this function attempts to refer to
7972 // a deleted function here.
7973 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007974 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007975 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007976 }
John McCalle23cf432010-12-14 08:05:40 +00007977
Sean Hunt001cad92011-05-10 00:49:42 +00007978 return ExceptSpec;
7979}
7980
Richard Smith07b0fdc2013-03-18 21:12:30 +00007981Sema::ImplicitExceptionSpecification
Richard Smith0b0ca472013-04-10 06:11:48 +00007982Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
7983 CXXRecordDecl *ClassDecl = CD->getParent();
7984
7985 // C++ [except.spec]p14:
7986 // An inheriting constructor [...] shall have an exception-specification. [...]
Richard Smith07b0fdc2013-03-18 21:12:30 +00007987 ImplicitExceptionSpecification ExceptSpec(*this);
Richard Smith0b0ca472013-04-10 06:11:48 +00007988 if (ClassDecl->isInvalidDecl())
7989 return ExceptSpec;
7990
7991 // Inherited constructor.
7992 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
7993 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
7994 // FIXME: Copying or moving the parameters could add extra exceptions to the
7995 // set, as could the default arguments for the inherited constructor. This
7996 // will be addressed when we implement the resolution of core issue 1351.
7997 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
7998
7999 // Direct base-class constructors.
8000 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8001 BEnd = ClassDecl->bases_end();
8002 B != BEnd; ++B) {
8003 if (B->isVirtual()) // Handled below.
8004 continue;
8005
8006 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8007 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8008 if (BaseClassDecl == InheritedDecl)
8009 continue;
8010 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8011 if (Constructor)
8012 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
8013 }
8014 }
8015
8016 // Virtual base-class constructors.
8017 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8018 BEnd = ClassDecl->vbases_end();
8019 B != BEnd; ++B) {
8020 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8021 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8022 if (BaseClassDecl == InheritedDecl)
8023 continue;
8024 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8025 if (Constructor)
8026 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
8027 }
8028 }
8029
8030 // Field constructors.
8031 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8032 FEnd = ClassDecl->field_end();
8033 F != FEnd; ++F) {
8034 if (F->hasInClassInitializer()) {
8035 if (Expr *E = F->getInClassInitializer())
8036 ExceptSpec.CalledExpr(E);
8037 else if (!F->isInvalidDecl())
8038 Diag(CD->getLocation(),
8039 diag::err_in_class_initializer_references_def_ctor) << CD;
8040 } else if (const RecordType *RecordTy
8041 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8042 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8043 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8044 if (Constructor)
8045 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
8046 }
8047 }
8048
Richard Smith07b0fdc2013-03-18 21:12:30 +00008049 return ExceptSpec;
8050}
8051
Richard Smithafb49182012-11-29 01:34:07 +00008052namespace {
8053/// RAII object to register a special member as being currently declared.
8054struct DeclaringSpecialMember {
8055 Sema &S;
8056 Sema::SpecialMemberDecl D;
8057 bool WasAlreadyBeingDeclared;
8058
8059 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
8060 : S(S), D(RD, CSM) {
8061 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D);
8062 if (WasAlreadyBeingDeclared)
8063 // This almost never happens, but if it does, ensure that our cache
8064 // doesn't contain a stale result.
8065 S.SpecialMemberCache.clear();
8066
8067 // FIXME: Register a note to be produced if we encounter an error while
8068 // declaring the special member.
8069 }
8070 ~DeclaringSpecialMember() {
8071 if (!WasAlreadyBeingDeclared)
8072 S.SpecialMembersBeingDeclared.erase(D);
8073 }
8074
8075 /// \brief Are we already trying to declare this special member?
8076 bool isAlreadyBeingDeclared() const {
8077 return WasAlreadyBeingDeclared;
8078 }
8079};
8080}
8081
Sean Hunt001cad92011-05-10 00:49:42 +00008082CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
8083 CXXRecordDecl *ClassDecl) {
8084 // C++ [class.ctor]p5:
8085 // A default constructor for a class X is a constructor of class X
8086 // that can be called without an argument. If there is no
8087 // user-declared constructor for class X, a default constructor is
8088 // implicitly declared. An implicitly-declared default constructor
8089 // is an inline public member of its class.
Richard Smithd0adeb62012-11-27 21:20:31 +00008090 assert(ClassDecl->needsImplicitDefaultConstructor() &&
Sean Hunt001cad92011-05-10 00:49:42 +00008091 "Should not build implicit default constructor!");
8092
Richard Smithafb49182012-11-29 01:34:07 +00008093 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
8094 if (DSM.isAlreadyBeingDeclared())
8095 return 0;
8096
Richard Smith7756afa2012-06-10 05:43:50 +00008097 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8098 CXXDefaultConstructor,
8099 false);
8100
Douglas Gregoreb8c6702010-07-01 22:31:05 +00008101 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00008102 CanQualType ClassType
8103 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008104 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor32df23e2010-07-01 22:02:46 +00008105 DeclarationName Name
8106 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008107 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith61802452011-12-22 02:22:31 +00008108 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00008109 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00008110 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00008111 Constexpr);
Douglas Gregor32df23e2010-07-01 22:02:46 +00008112 DefaultCon->setAccess(AS_public);
Sean Hunt1e238652011-05-12 03:51:51 +00008113 DefaultCon->setDefaulted();
Douglas Gregor32df23e2010-07-01 22:02:46 +00008114 DefaultCon->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00008115
8116 // Build an exception specification pointing back at this constructor.
Reid Kleckneref072032013-08-27 23:08:25 +00008117 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
Dmitri Gribenko55431692013-05-05 00:41:58 +00008118 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00008119
Richard Smithbc2a35d2012-12-08 08:32:28 +00008120 // We don't need to use SpecialMemberIsTrivial here; triviality for default
8121 // constructors is easy to compute.
8122 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
8123
8124 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00008125 SetDeclDeleted(DefaultCon, ClassLoc);
Richard Smithbc2a35d2012-12-08 08:32:28 +00008126
Douglas Gregor18274032010-07-03 00:47:00 +00008127 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00008128 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
Richard Smithbc2a35d2012-12-08 08:32:28 +00008129
Douglas Gregor23c94db2010-07-02 17:43:08 +00008130 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00008131 PushOnScopeChains(DefaultCon, S, false);
8132 ClassDecl->addDecl(DefaultCon);
Sean Hunt71a682f2011-05-18 03:41:58 +00008133
Douglas Gregor32df23e2010-07-01 22:02:46 +00008134 return DefaultCon;
8135}
8136
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00008137void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
8138 CXXConstructorDecl *Constructor) {
Sean Hunt1e238652011-05-12 03:51:51 +00008139 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00008140 !Constructor->doesThisDeclarationHaveABody() &&
8141 !Constructor->isDeleted()) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00008142 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00008143
Anders Carlssonf6513ed2010-04-23 16:04:08 +00008144 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00008145 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00008146
Eli Friedman9a14db32012-10-18 20:14:08 +00008147 SynthesizedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008148 DiagnosticErrorTrap Trap(Diags);
David Blaikie93c86172013-01-17 05:26:25 +00008149 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008150 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00008151 Diag(CurrentLocation, diag::note_member_synthesized_at)
Sean Huntf961ea52011-05-10 19:08:14 +00008152 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00008153 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00008154 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00008155 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00008156
8157 SourceLocation Loc = Constructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00008158 Constructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor4ada9d32010-09-20 16:48:21 +00008159
Eli Friedman86164e82013-09-05 00:02:25 +00008160 Constructor->markUsed(Context);
Douglas Gregor4ada9d32010-09-20 16:48:21 +00008161 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008162
8163 if (ASTMutationListener *L = getASTMutationListener()) {
8164 L->CompletedImplicitDefinition(Constructor);
8165 }
Richard Trieu858d2ba2013-10-25 00:56:00 +00008166
8167 DiagnoseUninitializedFields(*this, Constructor);
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00008168}
8169
Richard Smith7a614d82011-06-11 17:19:42 +00008170void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
Alp Toker08235662013-10-18 05:54:19 +00008171 // Perform any delayed checks on exception specifications.
8172 CheckDelayedMemberExceptionSpecs();
Richard Smith7a614d82011-06-11 17:19:42 +00008173}
8174
Richard Smith4841ca52013-04-10 05:48:59 +00008175namespace {
8176/// Information on inheriting constructors to declare.
8177class InheritingConstructorInfo {
8178public:
8179 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
8180 : SemaRef(SemaRef), Derived(Derived) {
8181 // Mark the constructors that we already have in the derived class.
8182 //
8183 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
8184 // unless there is a user-declared constructor with the same signature in
8185 // the class where the using-declaration appears.
8186 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
8187 }
8188
8189 void inheritAll(CXXRecordDecl *RD) {
8190 visitAll(RD, &InheritingConstructorInfo::inherit);
8191 }
8192
8193private:
8194 /// Information about an inheriting constructor.
8195 struct InheritingConstructor {
8196 InheritingConstructor()
8197 : DeclaredInDerived(false), BaseCtor(0), DerivedCtor(0) {}
8198
8199 /// If \c true, a constructor with this signature is already declared
8200 /// in the derived class.
8201 bool DeclaredInDerived;
8202
8203 /// The constructor which is inherited.
8204 const CXXConstructorDecl *BaseCtor;
8205
8206 /// The derived constructor we declared.
8207 CXXConstructorDecl *DerivedCtor;
8208 };
8209
8210 /// Inheriting constructors with a given canonical type. There can be at
8211 /// most one such non-template constructor, and any number of templated
8212 /// constructors.
8213 struct InheritingConstructorsForType {
8214 InheritingConstructor NonTemplate;
Robert Wilhelme7205c02013-08-10 12:33:24 +00008215 SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4>
8216 Templates;
Richard Smith4841ca52013-04-10 05:48:59 +00008217
8218 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
8219 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
8220 TemplateParameterList *ParamList = FTD->getTemplateParameters();
8221 for (unsigned I = 0, N = Templates.size(); I != N; ++I)
8222 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
8223 false, S.TPL_TemplateMatch))
8224 return Templates[I].second;
8225 Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
8226 return Templates.back().second;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008227 }
Richard Smith4841ca52013-04-10 05:48:59 +00008228
8229 return NonTemplate;
8230 }
8231 };
8232
8233 /// Get or create the inheriting constructor record for a constructor.
8234 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
8235 QualType CtorType) {
8236 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
8237 .getEntry(SemaRef, Ctor);
8238 }
8239
8240 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
8241
8242 /// Process all constructors for a class.
8243 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
8244 for (CXXRecordDecl::ctor_iterator CtorIt = RD->ctor_begin(),
8245 CtorE = RD->ctor_end();
8246 CtorIt != CtorE; ++CtorIt)
8247 (this->*Callback)(*CtorIt);
8248 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
8249 I(RD->decls_begin()), E(RD->decls_end());
8250 I != E; ++I) {
8251 const FunctionDecl *FD = (*I)->getTemplatedDecl();
8252 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
8253 (this->*Callback)(CD);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008254 }
8255 }
Richard Smith4841ca52013-04-10 05:48:59 +00008256
8257 /// Note that a constructor (or constructor template) was declared in Derived.
8258 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
8259 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
8260 }
8261
8262 /// Inherit a single constructor.
8263 void inherit(const CXXConstructorDecl *Ctor) {
8264 const FunctionProtoType *CtorType =
8265 Ctor->getType()->castAs<FunctionProtoType>();
8266 ArrayRef<QualType> ArgTypes(CtorType->getArgTypes());
8267 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
8268
8269 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
8270
8271 // Core issue (no number yet): the ellipsis is always discarded.
8272 if (EPI.Variadic) {
8273 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
8274 SemaRef.Diag(Ctor->getLocation(),
8275 diag::note_using_decl_constructor_ellipsis);
8276 EPI.Variadic = false;
8277 }
8278
8279 // Declare a constructor for each number of parameters.
8280 //
8281 // C++11 [class.inhctor]p1:
8282 // The candidate set of inherited constructors from the class X named in
8283 // the using-declaration consists of [... modulo defects ...] for each
8284 // constructor or constructor template of X, the set of constructors or
8285 // constructor templates that results from omitting any ellipsis parameter
8286 // specification and successively omitting parameters with a default
8287 // argument from the end of the parameter-type-list
Richard Smith987c0302013-04-17 19:00:52 +00008288 unsigned MinParams = minParamsToInherit(Ctor);
8289 unsigned Params = Ctor->getNumParams();
8290 if (Params >= MinParams) {
8291 do
8292 declareCtor(UsingLoc, Ctor,
8293 SemaRef.Context.getFunctionType(
8294 Ctor->getResultType(), ArgTypes.slice(0, Params), EPI));
8295 while (Params > MinParams &&
8296 Ctor->getParamDecl(--Params)->hasDefaultArg());
8297 }
Richard Smith4841ca52013-04-10 05:48:59 +00008298 }
8299
8300 /// Find the using-declaration which specified that we should inherit the
8301 /// constructors of \p Base.
8302 SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
8303 // No fancy lookup required; just look for the base constructor name
8304 // directly within the derived class.
8305 ASTContext &Context = SemaRef.Context;
8306 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8307 Context.getCanonicalType(Context.getRecordType(Base)));
8308 DeclContext::lookup_const_result Decls = Derived->lookup(Name);
8309 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
8310 }
8311
8312 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
8313 // C++11 [class.inhctor]p3:
8314 // [F]or each constructor template in the candidate set of inherited
8315 // constructors, a constructor template is implicitly declared
8316 if (Ctor->getDescribedFunctionTemplate())
8317 return 0;
8318
8319 // For each non-template constructor in the candidate set of inherited
8320 // constructors other than a constructor having no parameters or a
8321 // copy/move constructor having a single parameter, a constructor is
8322 // implicitly declared [...]
8323 if (Ctor->getNumParams() == 0)
8324 return 1;
8325 if (Ctor->isCopyOrMoveConstructor())
8326 return 2;
8327
8328 // Per discussion on core reflector, never inherit a constructor which
8329 // would become a default, copy, or move constructor of Derived either.
8330 const ParmVarDecl *PD = Ctor->getParamDecl(0);
8331 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
8332 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
8333 }
8334
8335 /// Declare a single inheriting constructor, inheriting the specified
8336 /// constructor, with the given type.
8337 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
8338 QualType DerivedType) {
8339 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
8340
8341 // C++11 [class.inhctor]p3:
8342 // ... a constructor is implicitly declared with the same constructor
8343 // characteristics unless there is a user-declared constructor with
8344 // the same signature in the class where the using-declaration appears
8345 if (Entry.DeclaredInDerived)
8346 return;
8347
8348 // C++11 [class.inhctor]p7:
8349 // If two using-declarations declare inheriting constructors with the
8350 // same signature, the program is ill-formed
8351 if (Entry.DerivedCtor) {
8352 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
8353 // Only diagnose this once per constructor.
8354 if (Entry.DerivedCtor->isInvalidDecl())
8355 return;
8356 Entry.DerivedCtor->setInvalidDecl();
8357
8358 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
8359 SemaRef.Diag(BaseCtor->getLocation(),
8360 diag::note_using_decl_constructor_conflict_current_ctor);
8361 SemaRef.Diag(Entry.BaseCtor->getLocation(),
8362 diag::note_using_decl_constructor_conflict_previous_ctor);
8363 SemaRef.Diag(Entry.DerivedCtor->getLocation(),
8364 diag::note_using_decl_constructor_conflict_previous_using);
8365 } else {
8366 // Core issue (no number): if the same inheriting constructor is
8367 // produced by multiple base class constructors from the same base
8368 // class, the inheriting constructor is defined as deleted.
8369 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
8370 }
8371
8372 return;
8373 }
8374
8375 ASTContext &Context = SemaRef.Context;
8376 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8377 Context.getCanonicalType(Context.getRecordType(Derived)));
8378 DeclarationNameInfo NameInfo(Name, UsingLoc);
8379
8380 TemplateParameterList *TemplateParams = 0;
8381 if (const FunctionTemplateDecl *FTD =
8382 BaseCtor->getDescribedFunctionTemplate()) {
8383 TemplateParams = FTD->getTemplateParameters();
8384 // We're reusing template parameters from a different DeclContext. This
8385 // is questionable at best, but works out because the template depth in
8386 // both places is guaranteed to be 0.
8387 // FIXME: Rebuild the template parameters in the new context, and
8388 // transform the function type to refer to them.
8389 }
8390
8391 // Build type source info pointing at the using-declaration. This is
8392 // required by template instantiation.
8393 TypeSourceInfo *TInfo =
8394 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
8395 FunctionProtoTypeLoc ProtoLoc =
8396 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
8397
8398 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
8399 Context, Derived, UsingLoc, NameInfo, DerivedType,
8400 TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
8401 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
8402
8403 // Build an unevaluated exception specification for this constructor.
8404 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
8405 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8406 EPI.ExceptionSpecType = EST_Unevaluated;
8407 EPI.ExceptionSpecDecl = DerivedCtor;
8408 DerivedCtor->setType(Context.getFunctionType(FPT->getResultType(),
8409 FPT->getArgTypes(), EPI));
8410
8411 // Build the parameter declarations.
8412 SmallVector<ParmVarDecl *, 16> ParamDecls;
8413 for (unsigned I = 0, N = FPT->getNumArgs(); I != N; ++I) {
8414 TypeSourceInfo *TInfo =
8415 Context.getTrivialTypeSourceInfo(FPT->getArgType(I), UsingLoc);
8416 ParmVarDecl *PD = ParmVarDecl::Create(
8417 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/0,
8418 FPT->getArgType(I), TInfo, SC_None, /*DefaultArg=*/0);
8419 PD->setScopeInfo(0, I);
8420 PD->setImplicit();
8421 ParamDecls.push_back(PD);
8422 ProtoLoc.setArg(I, PD);
8423 }
8424
8425 // Set up the new constructor.
8426 DerivedCtor->setAccess(BaseCtor->getAccess());
8427 DerivedCtor->setParams(ParamDecls);
8428 DerivedCtor->setInheritedConstructor(BaseCtor);
8429 if (BaseCtor->isDeleted())
8430 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
8431
8432 // If this is a constructor template, build the template declaration.
8433 if (TemplateParams) {
8434 FunctionTemplateDecl *DerivedTemplate =
8435 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
8436 TemplateParams, DerivedCtor);
8437 DerivedTemplate->setAccess(BaseCtor->getAccess());
8438 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
8439 Derived->addDecl(DerivedTemplate);
8440 } else {
8441 Derived->addDecl(DerivedCtor);
8442 }
8443
8444 Entry.BaseCtor = BaseCtor;
8445 Entry.DerivedCtor = DerivedCtor;
8446 }
8447
8448 Sema &SemaRef;
8449 CXXRecordDecl *Derived;
8450 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
8451 MapType Map;
8452};
8453}
8454
8455void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
8456 // Defer declaring the inheriting constructors until the class is
8457 // instantiated.
8458 if (ClassDecl->isDependentContext())
Sebastian Redlf677ea32011-02-05 19:23:19 +00008459 return;
8460
Richard Smith4841ca52013-04-10 05:48:59 +00008461 // Find base classes from which we might inherit constructors.
8462 SmallVector<CXXRecordDecl*, 4> InheritedBases;
8463 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
8464 BaseE = ClassDecl->bases_end();
8465 BaseIt != BaseE; ++BaseIt)
8466 if (BaseIt->getInheritConstructors())
8467 InheritedBases.push_back(BaseIt->getType()->getAsCXXRecordDecl());
Richard Smith07b0fdc2013-03-18 21:12:30 +00008468
Richard Smith4841ca52013-04-10 05:48:59 +00008469 // Go no further if we're not inheriting any constructors.
8470 if (InheritedBases.empty())
8471 return;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008472
Richard Smith4841ca52013-04-10 05:48:59 +00008473 // Declare the inherited constructors.
8474 InheritingConstructorInfo ICI(*this, ClassDecl);
8475 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
8476 ICI.inheritAll(InheritedBases[I]);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008477}
8478
Richard Smith07b0fdc2013-03-18 21:12:30 +00008479void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
8480 CXXConstructorDecl *Constructor) {
8481 CXXRecordDecl *ClassDecl = Constructor->getParent();
8482 assert(Constructor->getInheritedConstructor() &&
8483 !Constructor->doesThisDeclarationHaveABody() &&
8484 !Constructor->isDeleted());
8485
8486 SynthesizedFunctionScope Scope(*this, Constructor);
8487 DiagnosticErrorTrap Trap(Diags);
8488 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
8489 Trap.hasErrorOccurred()) {
8490 Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
8491 << Context.getTagDeclType(ClassDecl);
8492 Constructor->setInvalidDecl();
8493 return;
8494 }
8495
8496 SourceLocation Loc = Constructor->getLocation();
8497 Constructor->setBody(new (Context) CompoundStmt(Loc));
8498
Eli Friedman86164e82013-09-05 00:02:25 +00008499 Constructor->markUsed(Context);
Richard Smith07b0fdc2013-03-18 21:12:30 +00008500 MarkVTableUsed(CurrentLocation, ClassDecl);
8501
8502 if (ASTMutationListener *L = getASTMutationListener()) {
8503 L->CompletedImplicitDefinition(Constructor);
8504 }
8505}
8506
8507
Sean Huntcb45a0f2011-05-12 22:46:25 +00008508Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00008509Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
8510 CXXRecordDecl *ClassDecl = MD->getParent();
8511
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008512 // C++ [except.spec]p14:
8513 // An implicitly declared special member function (Clause 12) shall have
8514 // an exception-specification.
Richard Smithe6975e92012-04-17 00:58:00 +00008515 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008516 if (ClassDecl->isInvalidDecl())
8517 return ExceptSpec;
8518
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008519 // Direct base-class destructors.
8520 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8521 BEnd = ClassDecl->bases_end();
8522 B != BEnd; ++B) {
8523 if (B->isVirtual()) // Handled below.
8524 continue;
8525
8526 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00008527 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00008528 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008529 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00008530
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008531 // Virtual base-class destructors.
8532 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8533 BEnd = ClassDecl->vbases_end();
8534 B != BEnd; ++B) {
8535 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00008536 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00008537 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008538 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00008539
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008540 // Field destructors.
8541 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8542 FEnd = ClassDecl->field_end();
8543 F != FEnd; ++F) {
8544 if (const RecordType *RecordTy
8545 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00008546 ExceptSpec.CalledDecl(F->getLocation(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00008547 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008548 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008549
Sean Huntcb45a0f2011-05-12 22:46:25 +00008550 return ExceptSpec;
8551}
8552
8553CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
8554 // C++ [class.dtor]p2:
8555 // If a class has no user-declared destructor, a destructor is
8556 // declared implicitly. An implicitly-declared destructor is an
8557 // inline public member of its class.
Richard Smithe5411b72012-12-01 02:35:44 +00008558 assert(ClassDecl->needsImplicitDestructor());
Sean Huntcb45a0f2011-05-12 22:46:25 +00008559
Richard Smithafb49182012-11-29 01:34:07 +00008560 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
8561 if (DSM.isAlreadyBeingDeclared())
8562 return 0;
8563
Douglas Gregor4923aa22010-07-02 20:37:36 +00008564 // Create the actual destructor declaration.
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008565 CanQualType ClassType
8566 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008567 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008568 DeclarationName Name
8569 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008570 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008571 CXXDestructorDecl *Destructor
Richard Smithb9d0b762012-07-27 04:22:15 +00008572 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8573 QualType(), 0, /*isInline=*/true,
Sebastian Redl60618fa2011-03-12 11:50:43 +00008574 /*isImplicitlyDeclared=*/true);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008575 Destructor->setAccess(AS_public);
Sean Huntcb45a0f2011-05-12 22:46:25 +00008576 Destructor->setDefaulted();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008577 Destructor->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00008578
8579 // Build an exception specification pointing back at this destructor.
Reid Kleckneref072032013-08-27 23:08:25 +00008580 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
Dmitri Gribenko55431692013-05-05 00:41:58 +00008581 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00008582
Richard Smithbc2a35d2012-12-08 08:32:28 +00008583 AddOverriddenMethods(ClassDecl, Destructor);
8584
8585 // We don't need to use SpecialMemberIsTrivial here; triviality for
8586 // destructors is easy to compute.
8587 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
8588
8589 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00008590 SetDeclDeleted(Destructor, ClassLoc);
Richard Smithbc2a35d2012-12-08 08:32:28 +00008591
Douglas Gregor4923aa22010-07-02 20:37:36 +00008592 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00008593 ++ASTContext::NumImplicitDestructorsDeclared;
Richard Smithb9d0b762012-07-27 04:22:15 +00008594
Douglas Gregor4923aa22010-07-02 20:37:36 +00008595 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00008596 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00008597 PushOnScopeChains(Destructor, S, false);
8598 ClassDecl->addDecl(Destructor);
Sean Huntcb45a0f2011-05-12 22:46:25 +00008599
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008600 return Destructor;
8601}
8602
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008603void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00008604 CXXDestructorDecl *Destructor) {
Sean Huntcd10dec2011-05-23 23:14:04 +00008605 assert((Destructor->isDefaulted() &&
Richard Smith03f68782012-02-26 07:51:39 +00008606 !Destructor->doesThisDeclarationHaveABody() &&
8607 !Destructor->isDeleted()) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008608 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00008609 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008610 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008611
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008612 if (Destructor->isInvalidDecl())
8613 return;
8614
Eli Friedman9a14db32012-10-18 20:14:08 +00008615 SynthesizedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008616
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008617 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00008618 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
8619 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00008620
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008621 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00008622 Diag(CurrentLocation, diag::note_member_synthesized_at)
8623 << CXXDestructor << Context.getTagDeclType(ClassDecl);
8624
8625 Destructor->setInvalidDecl();
8626 return;
8627 }
8628
Douglas Gregor4ada9d32010-09-20 16:48:21 +00008629 SourceLocation Loc = Destructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00008630 Destructor->setBody(new (Context) CompoundStmt(Loc));
Eli Friedman86164e82013-09-05 00:02:25 +00008631 Destructor->markUsed(Context);
Douglas Gregor6fb745b2010-05-13 16:44:06 +00008632 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008633
8634 if (ASTMutationListener *L = getASTMutationListener()) {
8635 L->CompletedImplicitDefinition(Destructor);
8636 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008637}
8638
Richard Smitha4156b82012-04-21 18:42:51 +00008639/// \brief Perform any semantic analysis which needs to be delayed until all
8640/// pending class member declarations have been parsed.
8641void Sema::ActOnFinishCXXMemberDecls() {
Douglas Gregor10318842013-02-01 04:49:10 +00008642 // If the context is an invalid C++ class, just suppress these checks.
8643 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
8644 if (Record->isInvalidDecl()) {
Alp Toker08235662013-10-18 05:54:19 +00008645 DelayedDefaultedMemberExceptionSpecs.clear();
Douglas Gregor10318842013-02-01 04:49:10 +00008646 DelayedDestructorExceptionSpecChecks.clear();
8647 return;
8648 }
8649 }
Richard Smitha4156b82012-04-21 18:42:51 +00008650}
8651
Richard Smithb9d0b762012-07-27 04:22:15 +00008652void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
8653 CXXDestructorDecl *Destructor) {
Richard Smith80ad52f2013-01-02 11:42:31 +00008654 assert(getLangOpts().CPlusPlus11 &&
Richard Smithb9d0b762012-07-27 04:22:15 +00008655 "adjusting dtor exception specs was introduced in c++11");
8656
Sebastian Redl0ee33912011-05-19 05:13:44 +00008657 // C++11 [class.dtor]p3:
8658 // A declaration of a destructor that does not have an exception-
8659 // specification is implicitly considered to have the same exception-
8660 // specification as an implicit declaration.
Richard Smithb9d0b762012-07-27 04:22:15 +00008661 const FunctionProtoType *DtorType = Destructor->getType()->
Sebastian Redl0ee33912011-05-19 05:13:44 +00008662 getAs<FunctionProtoType>();
Richard Smithb9d0b762012-07-27 04:22:15 +00008663 if (DtorType->hasExceptionSpec())
Sebastian Redl0ee33912011-05-19 05:13:44 +00008664 return;
8665
Chandler Carruth3f224b22011-09-20 04:55:26 +00008666 // Replace the destructor's type, building off the existing one. Fortunately,
8667 // the only thing of interest in the destructor type is its extended info.
8668 // The return and arguments are fixed.
Richard Smithb9d0b762012-07-27 04:22:15 +00008669 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
8670 EPI.ExceptionSpecType = EST_Unevaluated;
8671 EPI.ExceptionSpecDecl = Destructor;
Dmitri Gribenko55431692013-05-05 00:41:58 +00008672 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smitha4156b82012-04-21 18:42:51 +00008673
Sebastian Redl0ee33912011-05-19 05:13:44 +00008674 // FIXME: If the destructor has a body that could throw, and the newly created
8675 // spec doesn't allow exceptions, we should emit a warning, because this
8676 // change in behavior can break conforming C++03 programs at runtime.
Richard Smithb9d0b762012-07-27 04:22:15 +00008677 // However, we don't have a body or an exception specification yet, so it
8678 // needs to be done somewhere else.
Sebastian Redl0ee33912011-05-19 05:13:44 +00008679}
8680
Pavel Labath66ea35d2013-08-30 08:52:28 +00008681namespace {
8682/// \brief An abstract base class for all helper classes used in building the
8683// copy/move operators. These classes serve as factory functions and help us
8684// avoid using the same Expr* in the AST twice.
8685class ExprBuilder {
8686 ExprBuilder(const ExprBuilder&) LLVM_DELETED_FUNCTION;
8687 ExprBuilder &operator=(const ExprBuilder&) LLVM_DELETED_FUNCTION;
8688
8689protected:
8690 static Expr *assertNotNull(Expr *E) {
8691 assert(E && "Expression construction must not fail.");
8692 return E;
8693 }
8694
8695public:
8696 ExprBuilder() {}
8697 virtual ~ExprBuilder() {}
8698
8699 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
8700};
8701
8702class RefBuilder: public ExprBuilder {
8703 VarDecl *Var;
8704 QualType VarType;
8705
8706public:
8707 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8708 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).take());
8709 }
8710
8711 RefBuilder(VarDecl *Var, QualType VarType)
8712 : Var(Var), VarType(VarType) {}
8713};
8714
8715class ThisBuilder: public ExprBuilder {
8716public:
8717 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8718 return assertNotNull(S.ActOnCXXThis(Loc).takeAs<Expr>());
8719 }
8720};
8721
8722class CastBuilder: public ExprBuilder {
8723 const ExprBuilder &Builder;
8724 QualType Type;
8725 ExprValueKind Kind;
8726 const CXXCastPath &Path;
8727
8728public:
8729 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8730 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
8731 CK_UncheckedDerivedToBase, Kind,
8732 &Path).take());
8733 }
8734
8735 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
8736 const CXXCastPath &Path)
8737 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
8738};
8739
8740class DerefBuilder: public ExprBuilder {
8741 const ExprBuilder &Builder;
8742
8743public:
8744 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8745 return assertNotNull(
8746 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).take());
8747 }
8748
8749 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
8750};
8751
8752class MemberBuilder: public ExprBuilder {
8753 const ExprBuilder &Builder;
8754 QualType Type;
8755 CXXScopeSpec SS;
8756 bool IsArrow;
8757 LookupResult &MemberLookup;
8758
8759public:
8760 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8761 return assertNotNull(S.BuildMemberReferenceExpr(
8762 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 0,
8763 MemberLookup, 0).take());
8764 }
8765
8766 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
8767 LookupResult &MemberLookup)
8768 : Builder(Builder), Type(Type), IsArrow(IsArrow),
8769 MemberLookup(MemberLookup) {}
8770};
8771
8772class MoveCastBuilder: public ExprBuilder {
8773 const ExprBuilder &Builder;
8774
8775public:
8776 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8777 return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
8778 }
8779
8780 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
8781};
8782
8783class LvalueConvBuilder: public ExprBuilder {
8784 const ExprBuilder &Builder;
8785
8786public:
8787 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8788 return assertNotNull(
8789 S.DefaultLvalueConversion(Builder.build(S, Loc)).take());
8790 }
8791
8792 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
8793};
8794
8795class SubscriptBuilder: public ExprBuilder {
8796 const ExprBuilder &Base;
8797 const ExprBuilder &Index;
8798
8799public:
8800 virtual Expr *build(Sema &S, SourceLocation Loc) const
8801 LLVM_OVERRIDE {
8802 return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
8803 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).take());
8804 }
8805
8806 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
8807 : Base(Base), Index(Index) {}
8808};
8809
8810} // end anonymous namespace
8811
Richard Smith8c889532012-11-14 00:50:40 +00008812/// When generating a defaulted copy or move assignment operator, if a field
8813/// should be copied with __builtin_memcpy rather than via explicit assignments,
8814/// do so. This optimization only applies for arrays of scalars, and for arrays
8815/// of class type where the selected copy/move-assignment operator is trivial.
8816static StmtResult
8817buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath66ea35d2013-08-30 08:52:28 +00008818 const ExprBuilder &ToB, const ExprBuilder &FromB) {
Richard Smith8c889532012-11-14 00:50:40 +00008819 // Compute the size of the memory buffer to be copied.
8820 QualType SizeType = S.Context.getSizeType();
8821 llvm::APInt Size(S.Context.getTypeSize(SizeType),
8822 S.Context.getTypeSizeInChars(T).getQuantity());
8823
8824 // Take the address of the field references for "from" and "to". We
8825 // directly construct UnaryOperators here because semantic analysis
8826 // does not permit us to take the address of an xvalue.
Pavel Labath66ea35d2013-08-30 08:52:28 +00008827 Expr *From = FromB.build(S, Loc);
Richard Smith8c889532012-11-14 00:50:40 +00008828 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
8829 S.Context.getPointerType(From->getType()),
8830 VK_RValue, OK_Ordinary, Loc);
Pavel Labath66ea35d2013-08-30 08:52:28 +00008831 Expr *To = ToB.build(S, Loc);
Richard Smith8c889532012-11-14 00:50:40 +00008832 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
8833 S.Context.getPointerType(To->getType()),
8834 VK_RValue, OK_Ordinary, Loc);
8835
8836 const Type *E = T->getBaseElementTypeUnsafe();
8837 bool NeedsCollectableMemCpy =
8838 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
8839
8840 // Create a reference to the __builtin_objc_memmove_collectable function
8841 StringRef MemCpyName = NeedsCollectableMemCpy ?
8842 "__builtin_objc_memmove_collectable" :
8843 "__builtin_memcpy";
8844 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
8845 Sema::LookupOrdinaryName);
8846 S.LookupName(R, S.TUScope, true);
8847
8848 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
8849 if (!MemCpy)
8850 // Something went horribly wrong earlier, and we will have complained
8851 // about it.
8852 return StmtError();
8853
8854 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
8855 VK_RValue, Loc, 0);
8856 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
8857
8858 Expr *CallArgs[] = {
8859 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
8860 };
8861 ExprResult Call = S.ActOnCallExpr(/*Scope=*/0, MemCpyRef.take(),
8862 Loc, CallArgs, Loc);
8863
8864 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8865 return S.Owned(Call.takeAs<Stmt>());
8866}
8867
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008868/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregor06a9f362010-05-01 20:49:11 +00008869/// \c To.
8870///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008871/// This routine is used to copy/move the members of a class with an
8872/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregor06a9f362010-05-01 20:49:11 +00008873/// copied are arrays, this routine builds for loops to copy them.
8874///
8875/// \param S The Sema object used for type-checking.
8876///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008877/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008878///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008879/// \param T The type of the expressions being copied/moved. Both expressions
8880/// must have this type.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008881///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008882/// \param To The expression we are copying/moving to.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008883///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008884/// \param From The expression we are copying/moving from.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008885///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008886/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008887/// Otherwise, it's a non-static member subobject.
8888///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008889/// \param Copying Whether we're copying or moving.
8890///
Douglas Gregor06a9f362010-05-01 20:49:11 +00008891/// \param Depth Internal parameter recording the depth of the recursion.
8892///
Richard Smith8c889532012-11-14 00:50:40 +00008893/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
8894/// if a memcpy should be used instead.
John McCall60d7b3a2010-08-24 06:29:42 +00008895static StmtResult
Richard Smith8c889532012-11-14 00:50:40 +00008896buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath66ea35d2013-08-30 08:52:28 +00008897 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith8c889532012-11-14 00:50:40 +00008898 bool CopyingBaseSubobject, bool Copying,
8899 unsigned Depth = 0) {
Richard Smith044c8aa2012-11-13 00:54:12 +00008900 // C++11 [class.copy]p28:
Douglas Gregor06a9f362010-05-01 20:49:11 +00008901 // Each subobject is assigned in the manner appropriate to its type:
8902 //
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008903 // - if the subobject is of class type, as if by a call to operator= with
8904 // the subobject as the object expression and the corresponding
8905 // subobject of x as a single function argument (as if by explicit
8906 // qualification; that is, ignoring any possible virtual overriding
8907 // functions in more derived classes);
Richard Smith044c8aa2012-11-13 00:54:12 +00008908 //
8909 // C++03 [class.copy]p13:
8910 // - if the subobject is of class type, the copy assignment operator for
8911 // the class is used (as if by explicit qualification; that is,
8912 // ignoring any possible virtual overriding functions in more derived
8913 // classes);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008914 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
8915 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith044c8aa2012-11-13 00:54:12 +00008916
Douglas Gregor06a9f362010-05-01 20:49:11 +00008917 // Look for operator=.
8918 DeclarationName Name
8919 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8920 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
8921 S.LookupQualifiedName(OpLookup, ClassDecl, false);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008922
Richard Smith044c8aa2012-11-13 00:54:12 +00008923 // Prior to C++11, filter out any result that isn't a copy/move-assignment
8924 // operator.
Richard Smith80ad52f2013-01-02 11:42:31 +00008925 if (!S.getLangOpts().CPlusPlus11) {
Richard Smith044c8aa2012-11-13 00:54:12 +00008926 LookupResult::Filter F = OpLookup.makeFilter();
8927 while (F.hasNext()) {
8928 NamedDecl *D = F.next();
8929 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
8930 if (Method->isCopyAssignmentOperator() ||
8931 (!Copying && Method->isMoveAssignmentOperator()))
8932 continue;
8933
8934 F.erase();
8935 }
8936 F.done();
John McCallb0207482010-03-16 06:11:48 +00008937 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008938
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008939 // Suppress the protected check (C++ [class.protected]) for each of the
Richard Smith044c8aa2012-11-13 00:54:12 +00008940 // assignment operators we found. This strange dance is required when
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008941 // we're assigning via a base classes's copy-assignment operator. To
Richard Smith044c8aa2012-11-13 00:54:12 +00008942 // ensure that we're getting the right base class subobject (without
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008943 // ambiguities), we need to cast "this" to that subobject type; to
8944 // ensure that we don't go through the virtual call mechanism, we need
8945 // to qualify the operator= name with the base class (see below). However,
8946 // this means that if the base class has a protected copy assignment
8947 // operator, the protected member access check will fail. So, we
8948 // rewrite "protected" access to "public" access in this case, since we
8949 // know by construction that we're calling from a derived class.
8950 if (CopyingBaseSubobject) {
8951 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
8952 L != LEnd; ++L) {
8953 if (L.getAccess() == AS_protected)
8954 L.setAccess(AS_public);
8955 }
8956 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008957
Douglas Gregor06a9f362010-05-01 20:49:11 +00008958 // Create the nested-name-specifier that will be used to qualify the
8959 // reference to operator=; this is required to suppress the virtual
8960 // call mechanism.
8961 CXXScopeSpec SS;
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00008962 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Richard Smith044c8aa2012-11-13 00:54:12 +00008963 SS.MakeTrivial(S.Context,
8964 NestedNameSpecifier::Create(S.Context, 0, false,
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00008965 CanonicalT),
Douglas Gregorc34348a2011-02-24 17:54:50 +00008966 Loc);
Richard Smith044c8aa2012-11-13 00:54:12 +00008967
Douglas Gregor06a9f362010-05-01 20:49:11 +00008968 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00008969 ExprResult OpEqualRef
Pavel Labath66ea35d2013-08-30 08:52:28 +00008970 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
8971 SS, /*TemplateKWLoc=*/SourceLocation(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008972 /*FirstQualifierInScope=*/0,
8973 OpLookup,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008974 /*TemplateArgs=*/0,
8975 /*SuppressQualifierCheck=*/true);
8976 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008977 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00008978
Douglas Gregor06a9f362010-05-01 20:49:11 +00008979 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00008980
Pavel Labath66ea35d2013-08-30 08:52:28 +00008981 Expr *FromInst = From.build(S, Loc);
Richard Smith044c8aa2012-11-13 00:54:12 +00008982 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00008983 OpEqualRef.takeAs<Expr>(),
Pavel Labath66ea35d2013-08-30 08:52:28 +00008984 Loc, FromInst, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008985 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008986 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00008987
Richard Smith8c889532012-11-14 00:50:40 +00008988 // If we built a call to a trivial 'operator=' while copying an array,
8989 // bail out. We'll replace the whole shebang with a memcpy.
8990 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
8991 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
8992 return StmtResult((Stmt*)0);
8993
Richard Smith044c8aa2012-11-13 00:54:12 +00008994 // Convert to an expression-statement, and clean up any produced
8995 // temporaries.
Richard Smith41956372013-01-14 22:39:08 +00008996 return S.ActOnExprStmt(Call);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008997 }
John McCallb0207482010-03-16 06:11:48 +00008998
Richard Smith044c8aa2012-11-13 00:54:12 +00008999 // - if the subobject is of scalar type, the built-in assignment
Douglas Gregor06a9f362010-05-01 20:49:11 +00009000 // operator is used.
Richard Smith044c8aa2012-11-13 00:54:12 +00009001 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009002 if (!ArrayTy) {
Pavel Labath66ea35d2013-08-30 08:52:28 +00009003 ExprResult Assignment = S.CreateBuiltinBinOp(
9004 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00009005 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00009006 return StmtError();
Richard Smith41956372013-01-14 22:39:08 +00009007 return S.ActOnExprStmt(Assignment);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009008 }
Richard Smith044c8aa2012-11-13 00:54:12 +00009009
9010 // - if the subobject is an array, each element is assigned, in the
Douglas Gregor06a9f362010-05-01 20:49:11 +00009011 // manner appropriate to the element type;
Richard Smith044c8aa2012-11-13 00:54:12 +00009012
Douglas Gregor06a9f362010-05-01 20:49:11 +00009013 // Construct a loop over the array bounds, e.g.,
9014 //
9015 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
9016 //
9017 // that will copy each of the array elements.
9018 QualType SizeType = S.Context.getSizeType();
Richard Smith8c889532012-11-14 00:50:40 +00009019
Douglas Gregor06a9f362010-05-01 20:49:11 +00009020 // Create the iteration variable.
9021 IdentifierInfo *IterationVarName = 0;
9022 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00009023 SmallString<8> Str;
Douglas Gregor06a9f362010-05-01 20:49:11 +00009024 llvm::raw_svector_ostream OS(Str);
9025 OS << "__i" << Depth;
9026 IterationVarName = &S.Context.Idents.get(OS.str());
9027 }
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009028 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00009029 IterationVarName, SizeType,
9030 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00009031 SC_None);
Richard Smith8c889532012-11-14 00:50:40 +00009032
Douglas Gregor06a9f362010-05-01 20:49:11 +00009033 // Initialize the iteration variable to zero.
9034 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00009035 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00009036
Pavel Labath66ea35d2013-08-30 08:52:28 +00009037 // Creates a reference to the iteration variable.
9038 RefBuilder IterationVarRef(IterationVar, SizeType);
9039 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
Eli Friedman8c382062012-01-23 02:35:22 +00009040
Douglas Gregor06a9f362010-05-01 20:49:11 +00009041 // Create the DeclStmt that holds the iteration variable.
9042 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
Richard Smith8c889532012-11-14 00:50:40 +00009043
Douglas Gregor06a9f362010-05-01 20:49:11 +00009044 // Subscript the "from" and "to" expressions with the iteration variable.
Pavel Labath66ea35d2013-08-30 08:52:28 +00009045 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
9046 MoveCastBuilder FromIndexMove(FromIndexCopy);
9047 const ExprBuilder *FromIndex;
9048 if (Copying)
9049 FromIndex = &FromIndexCopy;
9050 else
9051 FromIndex = &FromIndexMove;
9052
9053 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009054
9055 // Build the copy/move for an individual element of the array.
Richard Smith8c889532012-11-14 00:50:40 +00009056 StmtResult Copy =
9057 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
Pavel Labath66ea35d2013-08-30 08:52:28 +00009058 ToIndex, *FromIndex, CopyingBaseSubobject,
Richard Smith8c889532012-11-14 00:50:40 +00009059 Copying, Depth + 1);
9060 // Bail out if copying fails or if we determined that we should use memcpy.
9061 if (Copy.isInvalid() || !Copy.get())
9062 return Copy;
9063
9064 // Create the comparison against the array bound.
9065 llvm::APInt Upper
9066 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
9067 Expr *Comparison
Pavel Labath66ea35d2013-08-30 08:52:28 +00009068 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
Richard Smith8c889532012-11-14 00:50:40 +00009069 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
9070 BO_NE, S.Context.BoolTy,
9071 VK_RValue, OK_Ordinary, Loc, false);
9072
9073 // Create the pre-increment of the iteration variable.
9074 Expr *Increment
Pavel Labath66ea35d2013-08-30 08:52:28 +00009075 = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
9076 SizeType, VK_LValue, OK_Ordinary, Loc);
Richard Smith8c889532012-11-14 00:50:40 +00009077
Douglas Gregor06a9f362010-05-01 20:49:11 +00009078 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00009079 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00009080 S.MakeFullExpr(Comparison),
Richard Smith41956372013-01-14 22:39:08 +00009081 0, S.MakeFullDiscardedValueExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00009082 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009083}
9084
Richard Smith8c889532012-11-14 00:50:40 +00009085static StmtResult
9086buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath66ea35d2013-08-30 08:52:28 +00009087 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith8c889532012-11-14 00:50:40 +00009088 bool CopyingBaseSubobject, bool Copying) {
9089 // Maybe we should use a memcpy?
9090 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
9091 T.isTriviallyCopyableType(S.Context))
9092 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9093
9094 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
9095 CopyingBaseSubobject,
9096 Copying, 0));
9097
9098 // If we ended up picking a trivial assignment operator for an array of a
9099 // non-trivially-copyable class type, just emit a memcpy.
9100 if (!Result.isInvalid() && !Result.get())
9101 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9102
9103 return Result;
9104}
9105
Richard Smithb9d0b762012-07-27 04:22:15 +00009106Sema::ImplicitExceptionSpecification
9107Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
9108 CXXRecordDecl *ClassDecl = MD->getParent();
9109
9110 ImplicitExceptionSpecification ExceptSpec(*this);
9111 if (ClassDecl->isInvalidDecl())
9112 return ExceptSpec;
9113
9114 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
9115 assert(T->getNumArgs() == 1 && "not a copy assignment op");
9116 unsigned ArgQuals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
9117
Douglas Gregorb87786f2010-07-01 17:48:08 +00009118 // C++ [except.spec]p14:
Richard Smithb9d0b762012-07-27 04:22:15 +00009119 // An implicitly declared special member function (Clause 12) shall have an
Douglas Gregorb87786f2010-07-01 17:48:08 +00009120 // exception-specification. [...]
Sean Hunt661c67a2011-06-21 23:42:56 +00009121
9122 // It is unspecified whether or not an implicit copy assignment operator
9123 // attempts to deduplicate calls to assignment operators of virtual bases are
9124 // made. As such, this exception specification is effectively unspecified.
9125 // Based on a similar decision made for constness in C++0x, we're erring on
9126 // the side of assuming such calls to be made regardless of whether they
9127 // actually happen.
Douglas Gregorb87786f2010-07-01 17:48:08 +00009128 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9129 BaseEnd = ClassDecl->bases_end();
9130 Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00009131 if (Base->isVirtual())
9132 continue;
9133
Douglas Gregora376d102010-07-02 21:50:04 +00009134 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00009135 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00009136 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9137 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009138 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Douglas Gregorb87786f2010-07-01 17:48:08 +00009139 }
Sean Hunt661c67a2011-06-21 23:42:56 +00009140
9141 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9142 BaseEnd = ClassDecl->vbases_end();
9143 Base != BaseEnd; ++Base) {
9144 CXXRecordDecl *BaseClassDecl
9145 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9146 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9147 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009148 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Sean Hunt661c67a2011-06-21 23:42:56 +00009149 }
9150
Douglas Gregorb87786f2010-07-01 17:48:08 +00009151 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9152 FieldEnd = ClassDecl->field_end();
9153 Field != FieldEnd;
9154 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009155 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00009156 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9157 if (CXXMethodDecl *CopyAssign =
Richard Smith6a06e5f2012-07-18 03:36:00 +00009158 LookupCopyingAssignment(FieldClassDecl,
9159 ArgQuals | FieldType.getCVRQualifiers(),
9160 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009161 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00009162 }
Douglas Gregorb87786f2010-07-01 17:48:08 +00009163 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00009164
Richard Smithb9d0b762012-07-27 04:22:15 +00009165 return ExceptSpec;
Sean Hunt30de05c2011-05-14 05:23:20 +00009166}
9167
9168CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
9169 // Note: The following rules are largely analoguous to the copy
9170 // constructor rules. Note that virtual bases are not taken into account
9171 // for determining the argument type of the operator. Note also that
9172 // operators taking an object instead of a reference are allowed.
Richard Smithe5411b72012-12-01 02:35:44 +00009173 assert(ClassDecl->needsImplicitCopyAssignment());
Sean Hunt30de05c2011-05-14 05:23:20 +00009174
Richard Smithafb49182012-11-29 01:34:07 +00009175 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
9176 if (DSM.isAlreadyBeingDeclared())
9177 return 0;
9178
Sean Hunt30de05c2011-05-14 05:23:20 +00009179 QualType ArgType = Context.getTypeDeclType(ClassDecl);
9180 QualType RetType = Context.getLValueReferenceType(ArgType);
Richard Smitha8942d72013-05-07 03:19:20 +00009181 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
9182 if (Const)
Sean Hunt30de05c2011-05-14 05:23:20 +00009183 ArgType = ArgType.withConst();
9184 ArgType = Context.getLValueReferenceType(ArgType);
9185
Richard Smitha8942d72013-05-07 03:19:20 +00009186 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9187 CXXCopyAssignment,
9188 Const);
9189
Douglas Gregord3c35902010-07-01 16:36:15 +00009190 // An implicitly-declared copy assignment operator is an inline public
9191 // member of its class.
9192 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009193 SourceLocation ClassLoc = ClassDecl->getLocation();
9194 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smitha8942d72013-05-07 03:19:20 +00009195 CXXMethodDecl *CopyAssignment =
9196 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
9197 /*TInfo=*/ 0, /*StorageClass=*/ SC_None,
9198 /*isInline=*/ true, Constexpr, SourceLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00009199 CopyAssignment->setAccess(AS_public);
Sean Hunt7f410192011-05-14 05:23:24 +00009200 CopyAssignment->setDefaulted();
Douglas Gregord3c35902010-07-01 16:36:15 +00009201 CopyAssignment->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00009202
9203 // Build an exception specification pointing back at this member.
Reid Kleckneref072032013-08-27 23:08:25 +00009204 FunctionProtoType::ExtProtoInfo EPI =
9205 getImplicitMethodEPI(*this, CopyAssignment);
Jordan Rosebea522f2013-03-08 21:51:21 +00009206 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009207
Douglas Gregord3c35902010-07-01 16:36:15 +00009208 // Add the parameter to the operator.
9209 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009210 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregord3c35902010-07-01 16:36:15 +00009211 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00009212 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009213 CopyAssignment->setParams(FromParam);
Sean Hunt7f410192011-05-14 05:23:24 +00009214
Richard Smithbc2a35d2012-12-08 08:32:28 +00009215 AddOverriddenMethods(ClassDecl, CopyAssignment);
9216
9217 CopyAssignment->setTrivial(
9218 ClassDecl->needsOverloadResolutionForCopyAssignment()
9219 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
9220 : ClassDecl->hasTrivialCopyAssignment());
9221
Richard Smitha8942d72013-05-07 03:19:20 +00009222 // C++11 [class.copy]p19:
Nico Weberafcc96a2012-01-23 03:19:29 +00009223 // .... If the class definition does not explicitly declare a copy
9224 // assignment operator, there is no user-declared move constructor, and
9225 // there is no user-declared move assignment operator, a copy assignment
9226 // operator is implicitly declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00009227 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00009228 SetDeclDeleted(CopyAssignment, ClassLoc);
Richard Smith6c4c36c2012-03-30 20:53:28 +00009229
Richard Smithbc2a35d2012-12-08 08:32:28 +00009230 // Note that we have added this copy-assignment operator.
9231 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
9232
9233 if (Scope *S = getScopeForContext(ClassDecl))
9234 PushOnScopeChains(CopyAssignment, S, false);
9235 ClassDecl->addDecl(CopyAssignment);
9236
Douglas Gregord3c35902010-07-01 16:36:15 +00009237 return CopyAssignment;
9238}
9239
Richard Smith36155c12013-06-13 03:23:42 +00009240/// Diagnose an implicit copy operation for a class which is odr-used, but
9241/// which is deprecated because the class has a user-declared copy constructor,
9242/// copy assignment operator, or destructor.
9243static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
9244 SourceLocation UseLoc) {
9245 assert(CopyOp->isImplicit());
9246
9247 CXXRecordDecl *RD = CopyOp->getParent();
9248 CXXMethodDecl *UserDeclaredOperation = 0;
9249
9250 // In Microsoft mode, assignment operations don't affect constructors and
9251 // vice versa.
9252 if (RD->hasUserDeclaredDestructor()) {
9253 UserDeclaredOperation = RD->getDestructor();
9254 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
9255 RD->hasUserDeclaredCopyConstructor() &&
9256 !S.getLangOpts().MicrosoftMode) {
9257 // Find any user-declared copy constructor.
9258 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
9259 E = RD->ctor_end(); I != E; ++I) {
9260 if (I->isCopyConstructor()) {
9261 UserDeclaredOperation = *I;
9262 break;
9263 }
9264 }
9265 assert(UserDeclaredOperation);
9266 } else if (isa<CXXConstructorDecl>(CopyOp) &&
9267 RD->hasUserDeclaredCopyAssignment() &&
9268 !S.getLangOpts().MicrosoftMode) {
9269 // Find any user-declared move assignment operator.
9270 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
9271 E = RD->method_end(); I != E; ++I) {
9272 if (I->isCopyAssignmentOperator()) {
9273 UserDeclaredOperation = *I;
9274 break;
9275 }
9276 }
9277 assert(UserDeclaredOperation);
9278 }
9279
9280 if (UserDeclaredOperation) {
9281 S.Diag(UserDeclaredOperation->getLocation(),
9282 diag::warn_deprecated_copy_operation)
9283 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
9284 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
9285 S.Diag(UseLoc, diag::note_member_synthesized_at)
9286 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
9287 : Sema::CXXCopyAssignment)
9288 << RD;
9289 }
9290}
9291
Douglas Gregor06a9f362010-05-01 20:49:11 +00009292void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
9293 CXXMethodDecl *CopyAssignOperator) {
Sean Hunt7f410192011-05-14 05:23:24 +00009294 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00009295 CopyAssignOperator->isOverloadedOperator() &&
9296 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00009297 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
9298 !CopyAssignOperator->isDeleted()) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00009299 "DefineImplicitCopyAssignment called for wrong function");
9300
9301 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
9302
9303 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
9304 CopyAssignOperator->setInvalidDecl();
9305 return;
9306 }
Richard Smith36155c12013-06-13 03:23:42 +00009307
9308 // C++11 [class.copy]p18:
9309 // The [definition of an implicitly declared copy assignment operator] is
9310 // deprecated if the class has a user-declared copy constructor or a
9311 // user-declared destructor.
9312 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
9313 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
9314
Eli Friedman86164e82013-09-05 00:02:25 +00009315 CopyAssignOperator->markUsed(Context);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009316
Eli Friedman9a14db32012-10-18 20:14:08 +00009317 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00009318 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009319
9320 // C++0x [class.copy]p30:
9321 // The implicitly-defined or explicitly-defaulted copy assignment operator
9322 // for a non-union class X performs memberwise copy assignment of its
9323 // subobjects. The direct base classes of X are assigned first, in the
9324 // order of their declaration in the base-specifier-list, and then the
9325 // immediate non-static data members of X are assigned, in the order in
9326 // which they were declared in the class definition.
9327
9328 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00009329 SmallVector<Stmt*, 8> Statements;
Douglas Gregor06a9f362010-05-01 20:49:11 +00009330
9331 // The parameter for the "other" object, which we are copying from.
9332 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
9333 Qualifiers OtherQuals = Other->getType().getQualifiers();
9334 QualType OtherRefType = Other->getType();
9335 if (const LValueReferenceType *OtherRef
9336 = OtherRefType->getAs<LValueReferenceType>()) {
9337 OtherRefType = OtherRef->getPointeeType();
9338 OtherQuals = OtherRefType.getQualifiers();
9339 }
9340
9341 // Our location for everything implicitly-generated.
9342 SourceLocation Loc = CopyAssignOperator->getLocation();
9343
Pavel Labath66ea35d2013-08-30 08:52:28 +00009344 // Builds a DeclRefExpr for the "other" object.
9345 RefBuilder OtherRef(Other, OtherRefType);
9346
9347 // Builds the "this" pointer.
9348 ThisBuilder This;
Douglas Gregor06a9f362010-05-01 20:49:11 +00009349
9350 // Assign base classes.
9351 bool Invalid = false;
9352 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9353 E = ClassDecl->bases_end(); Base != E; ++Base) {
9354 // Form the assignment:
9355 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
9356 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00009357 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00009358 Invalid = true;
9359 continue;
9360 }
9361
John McCallf871d0c2010-08-07 06:22:56 +00009362 CXXCastPath BasePath;
9363 BasePath.push_back(Base);
9364
Douglas Gregor06a9f362010-05-01 20:49:11 +00009365 // Construct the "from" expression, which is an implicit cast to the
9366 // appropriately-qualified base type.
Pavel Labath66ea35d2013-08-30 08:52:28 +00009367 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
9368 VK_LValue, BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009369
9370 // Dereference "this".
Pavel Labath66ea35d2013-08-30 08:52:28 +00009371 DerefBuilder DerefThis(This);
9372 CastBuilder To(DerefThis,
9373 Context.getCVRQualifiedType(
9374 BaseType, CopyAssignOperator->getTypeQualifiers()),
9375 VK_LValue, BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009376
9377 // Build the copy.
Richard Smith8c889532012-11-14 00:50:40 +00009378 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath66ea35d2013-08-30 08:52:28 +00009379 To, From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009380 /*CopyingBaseSubobject=*/true,
9381 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009382 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00009383 Diag(CurrentLocation, diag::note_member_synthesized_at)
9384 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9385 CopyAssignOperator->setInvalidDecl();
9386 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00009387 }
9388
9389 // Success! Record the copy.
9390 Statements.push_back(Copy.takeAs<Expr>());
9391 }
9392
Douglas Gregor06a9f362010-05-01 20:49:11 +00009393 // Assign non-static members.
9394 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9395 FieldEnd = ClassDecl->field_end();
9396 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00009397 if (Field->isUnnamedBitfield())
9398 continue;
Eli Friedman8150da32013-06-07 01:48:56 +00009399
9400 if (Field->isInvalidDecl()) {
9401 Invalid = true;
9402 continue;
9403 }
9404
Douglas Gregor06a9f362010-05-01 20:49:11 +00009405 // Check for members of reference type; we can't copy those.
9406 if (Field->getType()->isReferenceType()) {
9407 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9408 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9409 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00009410 Diag(CurrentLocation, diag::note_member_synthesized_at)
9411 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009412 Invalid = true;
9413 continue;
9414 }
9415
9416 // Check for members of const-qualified, non-class type.
9417 QualType BaseType = Context.getBaseElementType(Field->getType());
9418 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9419 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9420 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9421 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00009422 Diag(CurrentLocation, diag::note_member_synthesized_at)
9423 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009424 Invalid = true;
9425 continue;
9426 }
John McCallb77115d2011-06-17 00:18:42 +00009427
9428 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00009429 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9430 continue;
Douglas Gregor06a9f362010-05-01 20:49:11 +00009431
9432 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00009433 if (FieldType->isIncompleteArrayType()) {
9434 assert(ClassDecl->hasFlexibleArrayMember() &&
9435 "Incomplete array type is not valid");
9436 continue;
9437 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00009438
9439 // Build references to the field in the object we're copying from and to.
9440 CXXScopeSpec SS; // Intentionally empty
9441 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9442 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00009443 MemberLookup.addDecl(*Field);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009444 MemberLookup.resolveKind();
Pavel Labath66ea35d2013-08-30 08:52:28 +00009445
9446 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
9447
9448 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009449
Douglas Gregor06a9f362010-05-01 20:49:11 +00009450 // Build the copy of this field.
Richard Smith8c889532012-11-14 00:50:40 +00009451 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath66ea35d2013-08-30 08:52:28 +00009452 To, From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009453 /*CopyingBaseSubobject=*/false,
9454 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009455 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00009456 Diag(CurrentLocation, diag::note_member_synthesized_at)
9457 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9458 CopyAssignOperator->setInvalidDecl();
9459 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00009460 }
9461
9462 // Success! Record the copy.
9463 Statements.push_back(Copy.takeAs<Stmt>());
9464 }
9465
9466 if (!Invalid) {
9467 // Add a "return *this;"
Pavel Labath66ea35d2013-08-30 08:52:28 +00009468 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00009469
John McCall60d7b3a2010-08-24 06:29:42 +00009470 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00009471 if (Return.isInvalid())
9472 Invalid = true;
9473 else {
9474 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00009475
9476 if (Trap.hasErrorOccurred()) {
9477 Diag(CurrentLocation, diag::note_member_synthesized_at)
9478 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9479 Invalid = true;
9480 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00009481 }
9482 }
9483
9484 if (Invalid) {
9485 CopyAssignOperator->setInvalidDecl();
9486 return;
9487 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009488
9489 StmtResult Body;
9490 {
9491 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009492 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009493 /*isStmtExpr=*/false);
9494 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9495 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00009496 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redl58a2cd82011-04-24 16:28:06 +00009497
9498 if (ASTMutationListener *L = getASTMutationListener()) {
9499 L->CompletedImplicitDefinition(CopyAssignOperator);
9500 }
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009501}
9502
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009503Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00009504Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
9505 CXXRecordDecl *ClassDecl = MD->getParent();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009506
Richard Smithb9d0b762012-07-27 04:22:15 +00009507 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009508 if (ClassDecl->isInvalidDecl())
9509 return ExceptSpec;
9510
9511 // C++0x [except.spec]p14:
9512 // An implicitly declared special member function (Clause 12) shall have an
9513 // exception-specification. [...]
9514
9515 // It is unspecified whether or not an implicit move assignment operator
9516 // attempts to deduplicate calls to assignment operators of virtual bases are
9517 // made. As such, this exception specification is effectively unspecified.
9518 // Based on a similar decision made for constness in C++0x, we're erring on
9519 // the side of assuming such calls to be made regardless of whether they
9520 // actually happen.
9521 // Note that a move constructor is not implicitly declared when there are
9522 // virtual bases, but it can still be user-declared and explicitly defaulted.
9523 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9524 BaseEnd = ClassDecl->bases_end();
9525 Base != BaseEnd; ++Base) {
9526 if (Base->isVirtual())
9527 continue;
9528
9529 CXXRecordDecl *BaseClassDecl
9530 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9531 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00009532 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009533 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009534 }
9535
9536 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9537 BaseEnd = ClassDecl->vbases_end();
9538 Base != BaseEnd; ++Base) {
9539 CXXRecordDecl *BaseClassDecl
9540 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9541 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00009542 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009543 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009544 }
9545
9546 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9547 FieldEnd = ClassDecl->field_end();
9548 Field != FieldEnd;
9549 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009550 QualType FieldType = Context.getBaseElementType(Field->getType());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009551 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith6a06e5f2012-07-18 03:36:00 +00009552 if (CXXMethodDecl *MoveAssign =
9553 LookupMovingAssignment(FieldClassDecl,
9554 FieldType.getCVRQualifiers(),
9555 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009556 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009557 }
9558 }
9559
9560 return ExceptSpec;
9561}
9562
Richard Smith1c931be2012-04-02 18:40:40 +00009563/// Determine whether the class type has any direct or indirect virtual base
9564/// classes which have a non-trivial move assignment operator.
9565static bool
9566hasVirtualBaseWithNonTrivialMoveAssignment(Sema &S, CXXRecordDecl *ClassDecl) {
9567 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9568 BaseEnd = ClassDecl->vbases_end();
9569 Base != BaseEnd; ++Base) {
9570 CXXRecordDecl *BaseClass =
9571 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9572
9573 // Try to declare the move assignment. If it would be deleted, then the
9574 // class does not have a non-trivial move assignment.
9575 if (BaseClass->needsImplicitMoveAssignment())
9576 S.DeclareImplicitMoveAssignment(BaseClass);
9577
Richard Smith426391c2012-11-16 00:53:38 +00009578 if (BaseClass->hasNonTrivialMoveAssignment())
Richard Smith1c931be2012-04-02 18:40:40 +00009579 return true;
9580 }
9581
9582 return false;
9583}
9584
9585/// Determine whether the given type either has a move constructor or is
9586/// trivially copyable.
9587static bool
9588hasMoveOrIsTriviallyCopyable(Sema &S, QualType Type, bool IsConstructor) {
9589 Type = S.Context.getBaseElementType(Type);
9590
9591 // FIXME: Technically, non-trivially-copyable non-class types, such as
9592 // reference types, are supposed to return false here, but that appears
9593 // to be a standard defect.
9594 CXXRecordDecl *ClassDecl = Type->getAsCXXRecordDecl();
Argyrios Kyrtzidisb5e4ace2012-10-10 16:14:06 +00009595 if (!ClassDecl || !ClassDecl->getDefinition() || ClassDecl->isInvalidDecl())
Richard Smith1c931be2012-04-02 18:40:40 +00009596 return true;
9597
9598 if (Type.isTriviallyCopyableType(S.Context))
9599 return true;
9600
9601 if (IsConstructor) {
Richard Smithe5411b72012-12-01 02:35:44 +00009602 // FIXME: Need this because otherwise hasMoveConstructor isn't guaranteed to
9603 // give the right answer.
Richard Smith1c931be2012-04-02 18:40:40 +00009604 if (ClassDecl->needsImplicitMoveConstructor())
9605 S.DeclareImplicitMoveConstructor(ClassDecl);
Richard Smithe5411b72012-12-01 02:35:44 +00009606 return ClassDecl->hasMoveConstructor();
Richard Smith1c931be2012-04-02 18:40:40 +00009607 }
9608
Richard Smithe5411b72012-12-01 02:35:44 +00009609 // FIXME: Need this because otherwise hasMoveAssignment isn't guaranteed to
9610 // give the right answer.
Richard Smith1c931be2012-04-02 18:40:40 +00009611 if (ClassDecl->needsImplicitMoveAssignment())
9612 S.DeclareImplicitMoveAssignment(ClassDecl);
Richard Smithe5411b72012-12-01 02:35:44 +00009613 return ClassDecl->hasMoveAssignment();
Richard Smith1c931be2012-04-02 18:40:40 +00009614}
9615
9616/// Determine whether all non-static data members and direct or virtual bases
9617/// of class \p ClassDecl have either a move operation, or are trivially
9618/// copyable.
9619static bool subobjectsHaveMoveOrTrivialCopy(Sema &S, CXXRecordDecl *ClassDecl,
9620 bool IsConstructor) {
9621 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9622 BaseEnd = ClassDecl->bases_end();
9623 Base != BaseEnd; ++Base) {
9624 if (Base->isVirtual())
9625 continue;
9626
9627 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
9628 return false;
9629 }
9630
9631 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9632 BaseEnd = ClassDecl->vbases_end();
9633 Base != BaseEnd; ++Base) {
9634 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
9635 return false;
9636 }
9637
9638 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9639 FieldEnd = ClassDecl->field_end();
9640 Field != FieldEnd; ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009641 if (!hasMoveOrIsTriviallyCopyable(S, Field->getType(), IsConstructor))
Richard Smith1c931be2012-04-02 18:40:40 +00009642 return false;
9643 }
9644
9645 return true;
9646}
9647
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009648CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00009649 // C++11 [class.copy]p20:
9650 // If the definition of a class X does not explicitly declare a move
9651 // assignment operator, one will be implicitly declared as defaulted
9652 // if and only if:
9653 //
9654 // - [first 4 bullets]
9655 assert(ClassDecl->needsImplicitMoveAssignment());
9656
Richard Smithafb49182012-11-29 01:34:07 +00009657 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
9658 if (DSM.isAlreadyBeingDeclared())
9659 return 0;
9660
Richard Smith1c931be2012-04-02 18:40:40 +00009661 // [Checked after we build the declaration]
9662 // - the move assignment operator would not be implicitly defined as
9663 // deleted,
9664
9665 // [DR1402]:
9666 // - X has no direct or indirect virtual base class with a non-trivial
9667 // move assignment operator, and
9668 // - each of X's non-static data members and direct or virtual base classes
9669 // has a type that either has a move assignment operator or is trivially
9670 // copyable.
9671 if (hasVirtualBaseWithNonTrivialMoveAssignment(*this, ClassDecl) ||
9672 !subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl,/*Constructor*/false)) {
9673 ClassDecl->setFailedImplicitMoveAssignment();
9674 return 0;
9675 }
9676
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009677 // Note: The following rules are largely analoguous to the move
9678 // constructor rules.
9679
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009680 QualType ArgType = Context.getTypeDeclType(ClassDecl);
9681 QualType RetType = Context.getLValueReferenceType(ArgType);
9682 ArgType = Context.getRValueReferenceType(ArgType);
9683
Richard Smitha8942d72013-05-07 03:19:20 +00009684 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9685 CXXMoveAssignment,
9686 false);
9687
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009688 // An implicitly-declared move assignment operator is an inline public
9689 // member of its class.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009690 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9691 SourceLocation ClassLoc = ClassDecl->getLocation();
9692 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smitha8942d72013-05-07 03:19:20 +00009693 CXXMethodDecl *MoveAssignment =
9694 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
9695 /*TInfo=*/0, /*StorageClass=*/SC_None,
9696 /*isInline=*/true, Constexpr, SourceLocation());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009697 MoveAssignment->setAccess(AS_public);
9698 MoveAssignment->setDefaulted();
9699 MoveAssignment->setImplicit();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009700
Richard Smithb9d0b762012-07-27 04:22:15 +00009701 // Build an exception specification pointing back at this member.
Reid Kleckneref072032013-08-27 23:08:25 +00009702 FunctionProtoType::ExtProtoInfo EPI =
9703 getImplicitMethodEPI(*this, MoveAssignment);
Jordan Rosebea522f2013-03-08 21:51:21 +00009704 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009705
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009706 // Add the parameter to the operator.
9707 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
9708 ClassLoc, ClassLoc, /*Id=*/0,
9709 ArgType, /*TInfo=*/0,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009710 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009711 MoveAssignment->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009712
Richard Smithbc2a35d2012-12-08 08:32:28 +00009713 AddOverriddenMethods(ClassDecl, MoveAssignment);
9714
9715 MoveAssignment->setTrivial(
9716 ClassDecl->needsOverloadResolutionForMoveAssignment()
9717 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
9718 : ClassDecl->hasTrivialMoveAssignment());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009719
9720 // C++0x [class.copy]p9:
9721 // If the definition of a class X does not explicitly declare a move
9722 // assignment operator, one will be implicitly declared as defaulted if and
9723 // only if:
9724 // [...]
9725 // - the move assignment operator would not be implicitly defined as
9726 // deleted.
Richard Smith7d5088a2012-02-18 02:02:13 +00009727 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009728 // Cache this result so that we don't try to generate this over and over
9729 // on every lookup, leaking memory and wasting time.
9730 ClassDecl->setFailedImplicitMoveAssignment();
9731 return 0;
9732 }
9733
Richard Smithbc2a35d2012-12-08 08:32:28 +00009734 // Note that we have added this copy-assignment operator.
9735 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
9736
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009737 if (Scope *S = getScopeForContext(ClassDecl))
9738 PushOnScopeChains(MoveAssignment, S, false);
9739 ClassDecl->addDecl(MoveAssignment);
9740
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009741 return MoveAssignment;
9742}
9743
9744void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
9745 CXXMethodDecl *MoveAssignOperator) {
9746 assert((MoveAssignOperator->isDefaulted() &&
9747 MoveAssignOperator->isOverloadedOperator() &&
9748 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00009749 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
9750 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009751 "DefineImplicitMoveAssignment called for wrong function");
9752
9753 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
9754
9755 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
9756 MoveAssignOperator->setInvalidDecl();
9757 return;
9758 }
9759
Eli Friedman86164e82013-09-05 00:02:25 +00009760 MoveAssignOperator->markUsed(Context);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009761
Eli Friedman9a14db32012-10-18 20:14:08 +00009762 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009763 DiagnosticErrorTrap Trap(Diags);
9764
9765 // C++0x [class.copy]p28:
9766 // The implicitly-defined or move assignment operator for a non-union class
9767 // X performs memberwise move assignment of its subobjects. The direct base
9768 // classes of X are assigned first, in the order of their declaration in the
9769 // base-specifier-list, and then the immediate non-static data members of X
9770 // are assigned, in the order in which they were declared in the class
9771 // definition.
9772
9773 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00009774 SmallVector<Stmt*, 8> Statements;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009775
9776 // The parameter for the "other" object, which we are move from.
9777 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
9778 QualType OtherRefType = Other->getType()->
9779 getAs<RValueReferenceType>()->getPointeeType();
David Blaikie7247c882013-05-15 07:37:26 +00009780 assert(!OtherRefType.getQualifiers() &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009781 "Bad argument type of defaulted move assignment");
9782
9783 // Our location for everything implicitly-generated.
9784 SourceLocation Loc = MoveAssignOperator->getLocation();
9785
Pavel Labath66ea35d2013-08-30 08:52:28 +00009786 // Builds a reference to the "other" object.
9787 RefBuilder OtherRef(Other, OtherRefType);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009788 // Cast to rvalue.
Pavel Labath66ea35d2013-08-30 08:52:28 +00009789 MoveCastBuilder MoveOther(OtherRef);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009790
Pavel Labath66ea35d2013-08-30 08:52:28 +00009791 // Builds the "this" pointer.
9792 ThisBuilder This;
Richard Smith1c931be2012-04-02 18:40:40 +00009793
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009794 // Assign base classes.
9795 bool Invalid = false;
9796 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9797 E = ClassDecl->bases_end(); Base != E; ++Base) {
9798 // Form the assignment:
9799 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
9800 QualType BaseType = Base->getType().getUnqualifiedType();
9801 if (!BaseType->isRecordType()) {
9802 Invalid = true;
9803 continue;
9804 }
9805
9806 CXXCastPath BasePath;
9807 BasePath.push_back(Base);
9808
9809 // Construct the "from" expression, which is an implicit cast to the
9810 // appropriately-qualified base type.
Pavel Labath66ea35d2013-08-30 08:52:28 +00009811 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009812
9813 // Dereference "this".
Pavel Labath66ea35d2013-08-30 08:52:28 +00009814 DerefBuilder DerefThis(This);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009815
9816 // Implicitly cast "this" to the appropriately-qualified base type.
Pavel Labath66ea35d2013-08-30 08:52:28 +00009817 CastBuilder To(DerefThis,
9818 Context.getCVRQualifiedType(
9819 BaseType, MoveAssignOperator->getTypeQualifiers()),
9820 VK_LValue, BasePath);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009821
9822 // Build the move.
Richard Smith8c889532012-11-14 00:50:40 +00009823 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath66ea35d2013-08-30 08:52:28 +00009824 To, From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009825 /*CopyingBaseSubobject=*/true,
9826 /*Copying=*/false);
9827 if (Move.isInvalid()) {
9828 Diag(CurrentLocation, diag::note_member_synthesized_at)
9829 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9830 MoveAssignOperator->setInvalidDecl();
9831 return;
9832 }
9833
9834 // Success! Record the move.
9835 Statements.push_back(Move.takeAs<Expr>());
9836 }
9837
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009838 // Assign non-static members.
9839 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9840 FieldEnd = ClassDecl->field_end();
9841 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00009842 if (Field->isUnnamedBitfield())
9843 continue;
9844
Eli Friedman8150da32013-06-07 01:48:56 +00009845 if (Field->isInvalidDecl()) {
9846 Invalid = true;
9847 continue;
9848 }
9849
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009850 // Check for members of reference type; we can't move those.
9851 if (Field->getType()->isReferenceType()) {
9852 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9853 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9854 Diag(Field->getLocation(), diag::note_declared_at);
9855 Diag(CurrentLocation, diag::note_member_synthesized_at)
9856 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9857 Invalid = true;
9858 continue;
9859 }
9860
9861 // Check for members of const-qualified, non-class type.
9862 QualType BaseType = Context.getBaseElementType(Field->getType());
9863 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9864 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9865 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9866 Diag(Field->getLocation(), diag::note_declared_at);
9867 Diag(CurrentLocation, diag::note_member_synthesized_at)
9868 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9869 Invalid = true;
9870 continue;
9871 }
9872
9873 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00009874 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9875 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009876
9877 QualType FieldType = Field->getType().getNonReferenceType();
9878 if (FieldType->isIncompleteArrayType()) {
9879 assert(ClassDecl->hasFlexibleArrayMember() &&
9880 "Incomplete array type is not valid");
9881 continue;
9882 }
9883
9884 // Build references to the field in the object we're copying from and to.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009885 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9886 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00009887 MemberLookup.addDecl(*Field);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009888 MemberLookup.resolveKind();
Pavel Labath66ea35d2013-08-30 08:52:28 +00009889 MemberBuilder From(MoveOther, OtherRefType,
9890 /*IsArrow=*/false, MemberLookup);
9891 MemberBuilder To(This, getCurrentThisType(),
9892 /*IsArrow=*/true, MemberLookup);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009893
Pavel Labath66ea35d2013-08-30 08:52:28 +00009894 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009895 "Member reference with rvalue base must be rvalue except for reference "
9896 "members, which aren't allowed for move assignment.");
9897
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009898 // Build the move of this field.
Richard Smith8c889532012-11-14 00:50:40 +00009899 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath66ea35d2013-08-30 08:52:28 +00009900 To, From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009901 /*CopyingBaseSubobject=*/false,
9902 /*Copying=*/false);
9903 if (Move.isInvalid()) {
9904 Diag(CurrentLocation, diag::note_member_synthesized_at)
9905 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9906 MoveAssignOperator->setInvalidDecl();
9907 return;
9908 }
Richard Smithe7ce7092012-11-12 23:33:00 +00009909
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009910 // Success! Record the copy.
9911 Statements.push_back(Move.takeAs<Stmt>());
9912 }
9913
9914 if (!Invalid) {
9915 // Add a "return *this;"
Pavel Labath66ea35d2013-08-30 08:52:28 +00009916 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009917
9918 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
9919 if (Return.isInvalid())
9920 Invalid = true;
9921 else {
9922 Statements.push_back(Return.takeAs<Stmt>());
9923
9924 if (Trap.hasErrorOccurred()) {
9925 Diag(CurrentLocation, diag::note_member_synthesized_at)
9926 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9927 Invalid = true;
9928 }
9929 }
9930 }
9931
9932 if (Invalid) {
9933 MoveAssignOperator->setInvalidDecl();
9934 return;
9935 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009936
9937 StmtResult Body;
9938 {
9939 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009940 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009941 /*isStmtExpr=*/false);
9942 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9943 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009944 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
9945
9946 if (ASTMutationListener *L = getASTMutationListener()) {
9947 L->CompletedImplicitDefinition(MoveAssignOperator);
9948 }
9949}
9950
Richard Smithb9d0b762012-07-27 04:22:15 +00009951Sema::ImplicitExceptionSpecification
9952Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
9953 CXXRecordDecl *ClassDecl = MD->getParent();
9954
9955 ImplicitExceptionSpecification ExceptSpec(*this);
9956 if (ClassDecl->isInvalidDecl())
9957 return ExceptSpec;
9958
9959 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
9960 assert(T->getNumArgs() >= 1 && "not a copy ctor");
9961 unsigned Quals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
9962
Douglas Gregor0d405db2010-07-01 20:59:04 +00009963 // C++ [except.spec]p14:
9964 // An implicitly declared special member function (Clause 12) shall have an
9965 // exception-specification. [...]
Douglas Gregor0d405db2010-07-01 20:59:04 +00009966 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9967 BaseEnd = ClassDecl->bases_end();
9968 Base != BaseEnd;
9969 ++Base) {
9970 // Virtual bases are handled below.
9971 if (Base->isVirtual())
9972 continue;
9973
Douglas Gregor22584312010-07-02 23:41:54 +00009974 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00009975 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00009976 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00009977 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00009978 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009979 }
9980 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9981 BaseEnd = ClassDecl->vbases_end();
9982 Base != BaseEnd;
9983 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00009984 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00009985 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00009986 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00009987 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00009988 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009989 }
9990 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9991 FieldEnd = ClassDecl->field_end();
9992 Field != FieldEnd;
9993 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009994 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Huntc530d172011-06-10 04:44:37 +00009995 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9996 if (CXXConstructorDecl *CopyConstructor =
Richard Smith6a06e5f2012-07-18 03:36:00 +00009997 LookupCopyingConstructor(FieldClassDecl,
9998 Quals | FieldType.getCVRQualifiers()))
Richard Smithe6975e92012-04-17 00:58:00 +00009999 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +000010000 }
10001 }
Sebastian Redl60618fa2011-03-12 11:50:43 +000010002
Richard Smithb9d0b762012-07-27 04:22:15 +000010003 return ExceptSpec;
Sean Hunt49634cf2011-05-13 06:10:58 +000010004}
10005
10006CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
10007 CXXRecordDecl *ClassDecl) {
10008 // C++ [class.copy]p4:
10009 // If the class definition does not explicitly declare a copy
10010 // constructor, one is declared implicitly.
Richard Smithe5411b72012-12-01 02:35:44 +000010011 assert(ClassDecl->needsImplicitCopyConstructor());
Sean Hunt49634cf2011-05-13 06:10:58 +000010012
Richard Smithafb49182012-11-29 01:34:07 +000010013 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
10014 if (DSM.isAlreadyBeingDeclared())
10015 return 0;
10016
Sean Hunt49634cf2011-05-13 06:10:58 +000010017 QualType ClassType = Context.getTypeDeclType(ClassDecl);
10018 QualType ArgType = ClassType;
Richard Smithacf796b2012-11-28 06:23:12 +000010019 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
Sean Hunt49634cf2011-05-13 06:10:58 +000010020 if (Const)
10021 ArgType = ArgType.withConst();
10022 ArgType = Context.getLValueReferenceType(ArgType);
Sean Hunt49634cf2011-05-13 06:10:58 +000010023
Richard Smith7756afa2012-06-10 05:43:50 +000010024 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10025 CXXCopyConstructor,
10026 Const);
10027
Douglas Gregor4a0c26f2010-07-01 17:57:27 +000010028 DeclarationName Name
10029 = Context.DeclarationNames.getCXXConstructorName(
10030 Context.getCanonicalType(ClassType));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010031 SourceLocation ClassLoc = ClassDecl->getLocation();
10032 DeclarationNameInfo NameInfo(Name, ClassLoc);
Sean Hunt49634cf2011-05-13 06:10:58 +000010033
10034 // An implicitly-declared copy constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +000010035 // member of its class.
10036 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +000010037 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +000010038 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +000010039 Constexpr);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +000010040 CopyConstructor->setAccess(AS_public);
Sean Hunt49634cf2011-05-13 06:10:58 +000010041 CopyConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +000010042
Richard Smithb9d0b762012-07-27 04:22:15 +000010043 // Build an exception specification pointing back at this member.
Reid Kleckneref072032013-08-27 23:08:25 +000010044 FunctionProtoType::ExtProtoInfo EPI =
10045 getImplicitMethodEPI(*this, CopyConstructor);
Richard Smithb9d0b762012-07-27 04:22:15 +000010046 CopyConstructor->setType(
Jordan Rosebea522f2013-03-08 21:51:21 +000010047 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +000010048
Douglas Gregor4a0c26f2010-07-01 17:57:27 +000010049 // Add the parameter to the constructor.
10050 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010051 ClassLoc, ClassLoc,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +000010052 /*IdentifierInfo=*/0,
10053 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +000010054 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +000010055 CopyConstructor->setParams(FromParam);
Sean Hunt49634cf2011-05-13 06:10:58 +000010056
Richard Smithbc2a35d2012-12-08 08:32:28 +000010057 CopyConstructor->setTrivial(
10058 ClassDecl->needsOverloadResolutionForCopyConstructor()
10059 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
10060 : ClassDecl->hasTrivialCopyConstructor());
Sean Hunt71a682f2011-05-18 03:41:58 +000010061
Nico Weberafcc96a2012-01-23 03:19:29 +000010062 // C++11 [class.copy]p8:
10063 // ... If the class definition does not explicitly declare a copy
10064 // constructor, there is no user-declared move constructor, and there is no
10065 // user-declared move assignment operator, a copy constructor is implicitly
10066 // declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +000010067 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +000010068 SetDeclDeleted(CopyConstructor, ClassLoc);
Richard Smith6c4c36c2012-03-30 20:53:28 +000010069
Richard Smithbc2a35d2012-12-08 08:32:28 +000010070 // Note that we have declared this constructor.
10071 ++ASTContext::NumImplicitCopyConstructorsDeclared;
10072
10073 if (Scope *S = getScopeForContext(ClassDecl))
10074 PushOnScopeChains(CopyConstructor, S, false);
10075 ClassDecl->addDecl(CopyConstructor);
10076
Douglas Gregor4a0c26f2010-07-01 17:57:27 +000010077 return CopyConstructor;
10078}
10079
Fariborz Jahanian485f0872009-06-22 23:34:40 +000010080void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Sean Hunt49634cf2011-05-13 06:10:58 +000010081 CXXConstructorDecl *CopyConstructor) {
10082 assert((CopyConstructor->isDefaulted() &&
10083 CopyConstructor->isCopyConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +000010084 !CopyConstructor->doesThisDeclarationHaveABody() &&
10085 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +000010086 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +000010087
Anders Carlsson63010a72010-04-23 16:24:12 +000010088 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +000010089 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +000010090
Richard Smith36155c12013-06-13 03:23:42 +000010091 // C++11 [class.copy]p7:
Benjamin Kramere5753592013-09-09 14:48:42 +000010092 // The [definition of an implicitly declared copy constructor] is
Richard Smith36155c12013-06-13 03:23:42 +000010093 // deprecated if the class has a user-declared copy assignment operator
10094 // or a user-declared destructor.
10095 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
10096 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
10097
Eli Friedman9a14db32012-10-18 20:14:08 +000010098 SynthesizedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +000010099 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +000010100
David Blaikie93c86172013-01-17 05:26:25 +000010101 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +000010102 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +000010103 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +000010104 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +000010105 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +000010106 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +000010107 Sema::CompoundScopeRAII CompoundScope(*this);
Robert Wilhelmc895f4d2013-08-19 20:51:20 +000010108 CopyConstructor->setBody(ActOnCompoundStmt(
10109 CopyConstructor->getLocation(), CopyConstructor->getLocation(), None,
10110 /*isStmtExpr=*/ false).takeAs<Stmt>());
Anders Carlsson8e142cc2010-04-25 00:52:09 +000010111 }
Robert Wilhelmc895f4d2013-08-19 20:51:20 +000010112
Eli Friedman86164e82013-09-05 00:02:25 +000010113 CopyConstructor->markUsed(Context);
Sebastian Redl58a2cd82011-04-24 16:28:06 +000010114 if (ASTMutationListener *L = getASTMutationListener()) {
10115 L->CompletedImplicitDefinition(CopyConstructor);
10116 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +000010117}
10118
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010119Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +000010120Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
10121 CXXRecordDecl *ClassDecl = MD->getParent();
10122
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010123 // C++ [except.spec]p14:
10124 // An implicitly declared special member function (Clause 12) shall have an
10125 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +000010126 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010127 if (ClassDecl->isInvalidDecl())
10128 return ExceptSpec;
10129
10130 // Direct base-class constructors.
10131 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
10132 BEnd = ClassDecl->bases_end();
10133 B != BEnd; ++B) {
10134 if (B->isVirtual()) // Handled below.
10135 continue;
10136
10137 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
10138 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +000010139 CXXConstructorDecl *Constructor =
10140 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010141 // If this is a deleted function, add it anyway. This might be conformant
10142 // with the standard. This might not. I'm not sure. It might not matter.
10143 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +000010144 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010145 }
10146 }
10147
10148 // Virtual base-class constructors.
10149 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
10150 BEnd = ClassDecl->vbases_end();
10151 B != BEnd; ++B) {
10152 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
10153 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +000010154 CXXConstructorDecl *Constructor =
10155 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010156 // If this is a deleted function, add it anyway. This might be conformant
10157 // with the standard. This might not. I'm not sure. It might not matter.
10158 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +000010159 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010160 }
10161 }
10162
10163 // Field constructors.
10164 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
10165 FEnd = ClassDecl->field_end();
10166 F != FEnd; ++F) {
Richard Smith6a06e5f2012-07-18 03:36:00 +000010167 QualType FieldType = Context.getBaseElementType(F->getType());
10168 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
10169 CXXConstructorDecl *Constructor =
10170 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010171 // If this is a deleted function, add it anyway. This might be conformant
10172 // with the standard. This might not. I'm not sure. It might not matter.
10173 // In particular, the problem is that this function never gets called. It
10174 // might just be ill-formed because this function attempts to refer to
10175 // a deleted function here.
10176 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +000010177 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010178 }
10179 }
10180
10181 return ExceptSpec;
10182}
10183
10184CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
10185 CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +000010186 // C++11 [class.copy]p9:
10187 // If the definition of a class X does not explicitly declare a move
10188 // constructor, one will be implicitly declared as defaulted if and only if:
10189 //
10190 // - [first 4 bullets]
10191 assert(ClassDecl->needsImplicitMoveConstructor());
10192
Richard Smithafb49182012-11-29 01:34:07 +000010193 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
10194 if (DSM.isAlreadyBeingDeclared())
10195 return 0;
10196
Richard Smith1c931be2012-04-02 18:40:40 +000010197 // [Checked after we build the declaration]
10198 // - the move assignment operator would not be implicitly defined as
10199 // deleted,
10200
10201 // [DR1402]:
10202 // - each of X's non-static data members and direct or virtual base classes
10203 // has a type that either has a move constructor or is trivially copyable.
10204 if (!subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl, /*Constructor*/true)) {
10205 ClassDecl->setFailedImplicitMoveConstructor();
10206 return 0;
10207 }
10208
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010209 QualType ClassType = Context.getTypeDeclType(ClassDecl);
10210 QualType ArgType = Context.getRValueReferenceType(ClassType);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010211
Richard Smith7756afa2012-06-10 05:43:50 +000010212 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10213 CXXMoveConstructor,
10214 false);
10215
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010216 DeclarationName Name
10217 = Context.DeclarationNames.getCXXConstructorName(
10218 Context.getCanonicalType(ClassType));
10219 SourceLocation ClassLoc = ClassDecl->getLocation();
10220 DeclarationNameInfo NameInfo(Name, ClassLoc);
10221
Richard Smitha8942d72013-05-07 03:19:20 +000010222 // C++11 [class.copy]p11:
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010223 // An implicitly-declared copy/move constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +000010224 // member of its class.
10225 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +000010226 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +000010227 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +000010228 Constexpr);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010229 MoveConstructor->setAccess(AS_public);
10230 MoveConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +000010231
Richard Smithb9d0b762012-07-27 04:22:15 +000010232 // Build an exception specification pointing back at this member.
Reid Kleckneref072032013-08-27 23:08:25 +000010233 FunctionProtoType::ExtProtoInfo EPI =
10234 getImplicitMethodEPI(*this, MoveConstructor);
Richard Smithb9d0b762012-07-27 04:22:15 +000010235 MoveConstructor->setType(
Jordan Rosebea522f2013-03-08 21:51:21 +000010236 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +000010237
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010238 // Add the parameter to the constructor.
10239 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
10240 ClassLoc, ClassLoc,
10241 /*IdentifierInfo=*/0,
10242 ArgType, /*TInfo=*/0,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010243 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +000010244 MoveConstructor->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010245
Richard Smithbc2a35d2012-12-08 08:32:28 +000010246 MoveConstructor->setTrivial(
10247 ClassDecl->needsOverloadResolutionForMoveConstructor()
10248 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
10249 : ClassDecl->hasTrivialMoveConstructor());
10250
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010251 // C++0x [class.copy]p9:
10252 // If the definition of a class X does not explicitly declare a move
10253 // constructor, one will be implicitly declared as defaulted if and only if:
10254 // [...]
10255 // - the move constructor would not be implicitly defined as deleted.
Sean Hunt769bb2d2011-10-11 06:43:29 +000010256 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010257 // Cache this result so that we don't try to generate this over and over
10258 // on every lookup, leaking memory and wasting time.
10259 ClassDecl->setFailedImplicitMoveConstructor();
10260 return 0;
10261 }
10262
10263 // Note that we have declared this constructor.
10264 ++ASTContext::NumImplicitMoveConstructorsDeclared;
10265
10266 if (Scope *S = getScopeForContext(ClassDecl))
10267 PushOnScopeChains(MoveConstructor, S, false);
10268 ClassDecl->addDecl(MoveConstructor);
10269
10270 return MoveConstructor;
10271}
10272
10273void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
10274 CXXConstructorDecl *MoveConstructor) {
10275 assert((MoveConstructor->isDefaulted() &&
10276 MoveConstructor->isMoveConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +000010277 !MoveConstructor->doesThisDeclarationHaveABody() &&
10278 !MoveConstructor->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010279 "DefineImplicitMoveConstructor - call it for implicit move ctor");
10280
10281 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
10282 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
10283
Eli Friedman9a14db32012-10-18 20:14:08 +000010284 SynthesizedFunctionScope Scope(*this, MoveConstructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010285 DiagnosticErrorTrap Trap(Diags);
10286
David Blaikie93c86172013-01-17 05:26:25 +000010287 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010288 Trap.hasErrorOccurred()) {
10289 Diag(CurrentLocation, diag::note_member_synthesized_at)
10290 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
10291 MoveConstructor->setInvalidDecl();
10292 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +000010293 Sema::CompoundScopeRAII CompoundScope(*this);
Robert Wilhelmc895f4d2013-08-19 20:51:20 +000010294 MoveConstructor->setBody(ActOnCompoundStmt(
10295 MoveConstructor->getLocation(), MoveConstructor->getLocation(), None,
10296 /*isStmtExpr=*/ false).takeAs<Stmt>());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010297 }
10298
Eli Friedman86164e82013-09-05 00:02:25 +000010299 MoveConstructor->markUsed(Context);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010300
10301 if (ASTMutationListener *L = getASTMutationListener()) {
10302 L->CompletedImplicitDefinition(MoveConstructor);
10303 }
10304}
10305
Douglas Gregore4e68d42012-02-15 19:33:52 +000010306bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
Eli Friedmanc4ef9482013-07-18 23:29:14 +000010307 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
Douglas Gregore4e68d42012-02-15 19:33:52 +000010308}
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010309
10310void Sema::DefineImplicitLambdaToFunctionPointerConversion(
Faisal Valid6992ab2013-09-29 08:45:24 +000010311 SourceLocation CurrentLocation,
10312 CXXConversionDecl *Conv) {
10313 CXXRecordDecl *Lambda = Conv->getParent();
10314 CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
10315 // If we are defining a specialization of a conversion to function-ptr
10316 // cache the deduced template arguments for this specialization
10317 // so that we can use them to retrieve the corresponding call-operator
10318 // and static-invoker.
10319 const TemplateArgumentList *DeducedTemplateArgs = 0;
10320
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010321
Faisal Valid6992ab2013-09-29 08:45:24 +000010322 // Retrieve the corresponding call-operator specialization.
10323 if (Lambda->isGenericLambda()) {
10324 assert(Conv->isFunctionTemplateSpecialization());
10325 FunctionTemplateDecl *CallOpTemplate =
10326 CallOp->getDescribedFunctionTemplate();
10327 DeducedTemplateArgs = Conv->getTemplateSpecializationArgs();
10328 void *InsertPos = 0;
10329 FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization(
10330 DeducedTemplateArgs->data(),
10331 DeducedTemplateArgs->size(),
10332 InsertPos);
10333 assert(CallOpSpec &&
10334 "Conversion operator must have a corresponding call operator");
10335 CallOp = cast<CXXMethodDecl>(CallOpSpec);
10336 }
10337 // Mark the call operator referenced (and add to pending instantiations
10338 // if necessary).
10339 // For both the conversion and static-invoker template specializations
10340 // we construct their body's in this function, so no need to add them
10341 // to the PendingInstantiations.
10342 MarkFunctionReferenced(CurrentLocation, CallOp);
10343
Eli Friedman9a14db32012-10-18 20:14:08 +000010344 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010345 DiagnosticErrorTrap Trap(Diags);
Faisal Valid6992ab2013-09-29 08:45:24 +000010346
10347 // Retreive the static invoker...
10348 CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker();
10349 // ... and get the corresponding specialization for a generic lambda.
10350 if (Lambda->isGenericLambda()) {
10351 assert(DeducedTemplateArgs &&
10352 "Must have deduced template arguments from Conversion Operator");
10353 FunctionTemplateDecl *InvokeTemplate =
10354 Invoker->getDescribedFunctionTemplate();
10355 void *InsertPos = 0;
10356 FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization(
10357 DeducedTemplateArgs->data(),
10358 DeducedTemplateArgs->size(),
10359 InsertPos);
10360 assert(InvokeSpec &&
10361 "Must have a corresponding static invoker specialization");
10362 Invoker = cast<CXXMethodDecl>(InvokeSpec);
10363 }
10364 // Construct the body of the conversion function { return __invoke; }.
10365 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
10366 VK_LValue, Conv->getLocation()).take();
10367 assert(FunctionRef && "Can't refer to __invoke function?");
10368 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
10369 Conv->setBody(new (Context) CompoundStmt(Context, Return,
10370 Conv->getLocation(),
10371 Conv->getLocation()));
10372
10373 Conv->markUsed(Context);
10374 Conv->setReferenced();
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010375
Faisal Valid6992ab2013-09-29 08:45:24 +000010376 // Fill in the __invoke function with a dummy implementation. IR generation
10377 // will fill in the actual details.
10378 Invoker->markUsed(Context);
10379 Invoker->setReferenced();
10380 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
10381
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010382 if (ASTMutationListener *L = getASTMutationListener()) {
10383 L->CompletedImplicitDefinition(Conv);
Faisal Valid6992ab2013-09-29 08:45:24 +000010384 L->CompletedImplicitDefinition(Invoker);
10385 }
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010386}
10387
Faisal Valid6992ab2013-09-29 08:45:24 +000010388
10389
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010390void Sema::DefineImplicitLambdaToBlockPointerConversion(
10391 SourceLocation CurrentLocation,
10392 CXXConversionDecl *Conv)
10393{
Faisal Vali56fe35b2013-09-29 17:08:32 +000010394 assert(!Conv->getParent()->isGenericLambda());
Faisal Valid6992ab2013-09-29 08:45:24 +000010395
Eli Friedman86164e82013-09-05 00:02:25 +000010396 Conv->markUsed(Context);
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010397
Eli Friedman9a14db32012-10-18 20:14:08 +000010398 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010399 DiagnosticErrorTrap Trap(Diags);
10400
Douglas Gregorac1303e2012-02-22 05:02:47 +000010401 // Copy-initialize the lambda object as needed to capture it.
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010402 Expr *This = ActOnCXXThis(CurrentLocation).take();
10403 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010404
Eli Friedman23f02672012-03-01 04:01:32 +000010405 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
10406 Conv->getLocation(),
10407 Conv, DerefThis);
10408
10409 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
10410 // behavior. Note that only the general conversion function does this
10411 // (since it's unusable otherwise); in the case where we inline the
10412 // block literal, it has block literal lifetime semantics.
David Blaikie4e4d0842012-03-11 07:00:24 +000010413 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman23f02672012-03-01 04:01:32 +000010414 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
10415 CK_CopyAndAutoreleaseBlockObject,
10416 BuildBlock.get(), 0, VK_RValue);
10417
10418 if (BuildBlock.isInvalid()) {
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010419 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregorac1303e2012-02-22 05:02:47 +000010420 Conv->setInvalidDecl();
10421 return;
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010422 }
Douglas Gregorac1303e2012-02-22 05:02:47 +000010423
Douglas Gregorac1303e2012-02-22 05:02:47 +000010424 // Create the return statement that returns the block from the conversion
10425 // function.
Eli Friedman23f02672012-03-01 04:01:32 +000010426 StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregorac1303e2012-02-22 05:02:47 +000010427 if (Return.isInvalid()) {
10428 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
10429 Conv->setInvalidDecl();
10430 return;
10431 }
10432
10433 // Set the body of the conversion function.
10434 Stmt *ReturnS = Return.take();
Nico Weberd36aa352012-12-29 20:03:39 +000010435 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
Douglas Gregorac1303e2012-02-22 05:02:47 +000010436 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010437 Conv->getLocation()));
10438
Douglas Gregorac1303e2012-02-22 05:02:47 +000010439 // We're done; notify the mutation listener, if any.
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010440 if (ASTMutationListener *L = getASTMutationListener()) {
10441 L->CompletedImplicitDefinition(Conv);
10442 }
10443}
10444
Douglas Gregorf52757d2012-03-10 06:53:13 +000010445/// \brief Determine whether the given list arguments contains exactly one
10446/// "real" (non-default) argument.
10447static bool hasOneRealArgument(MultiExprArg Args) {
10448 switch (Args.size()) {
10449 case 0:
10450 return false;
10451
10452 default:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010453 if (!Args[1]->isDefaultArgument())
Douglas Gregorf52757d2012-03-10 06:53:13 +000010454 return false;
10455
10456 // fall through
10457 case 1:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010458 return !Args[0]->isDefaultArgument();
Douglas Gregorf52757d2012-03-10 06:53:13 +000010459 }
10460
10461 return false;
10462}
10463
John McCall60d7b3a2010-08-24 06:29:42 +000010464ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +000010465Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +000010466 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +000010467 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010468 bool HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +000010469 bool IsListInitialization,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +000010470 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +000010471 unsigned ConstructKind,
10472 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +000010473 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +000010474
Douglas Gregor2f599792010-04-02 18:24:57 +000010475 // C++0x [class.copy]p34:
10476 // When certain criteria are met, an implementation is allowed to
10477 // omit the copy/move construction of a class object, even if the
10478 // copy/move constructor and/or destructor for the object have
10479 // side effects. [...]
10480 // - when a temporary class object that has not been bound to a
10481 // reference (12.2) would be copied/moved to a class object
10482 // with the same cv-unqualified type, the copy/move operation
10483 // can be omitted by constructing the temporary object
10484 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +000010485 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregorf52757d2012-03-10 06:53:13 +000010486 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Benjamin Kramer5354e772012-08-23 23:38:35 +000010487 Expr *SubExpr = ExprArgs[0];
John McCall558d2ab2010-09-15 10:14:12 +000010488 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +000010489 }
Mike Stump1eb44332009-09-09 15:08:12 +000010490
10491 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010492 Elidable, ExprArgs, HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +000010493 IsListInitialization, RequiresZeroInit,
10494 ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +000010495}
10496
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +000010497/// BuildCXXConstructExpr - Creates a complete call to a constructor,
10498/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +000010499ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +000010500Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
10501 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +000010502 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010503 bool HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +000010504 bool IsListInitialization,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +000010505 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +000010506 unsigned ConstructKind,
10507 SourceRange ParenRange) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010508 MarkFunctionReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +000010509 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010510 Constructor, Elidable, ExprArgs,
Richard Smithc83c2302012-12-19 01:39:02 +000010511 HadMultipleCandidates,
10512 IsListInitialization, RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +000010513 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
10514 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +000010515}
10516
John McCall68c6c9a2010-02-02 09:10:11 +000010517void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010518 if (VD->isInvalidDecl()) return;
10519
John McCall68c6c9a2010-02-02 09:10:11 +000010520 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010521 if (ClassDecl->isInvalidDecl()) return;
Richard Smith213d70b2012-02-18 04:13:32 +000010522 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010523 if (ClassDecl->isDependentContext()) return;
John McCall626e96e2010-08-01 20:20:59 +000010524
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010525 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedman5f2987c2012-02-02 03:46:19 +000010526 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010527 CheckDestructorAccess(VD->getLocation(), Destructor,
10528 PDiag(diag::err_access_dtor_var)
10529 << VD->getDeclName()
10530 << VD->getType());
Richard Smith213d70b2012-02-18 04:13:32 +000010531 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson2b32dad2011-03-24 01:01:41 +000010532
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010533 if (!VD->hasGlobalStorage()) return;
10534
10535 // Emit warning for non-trivial dtor in global scope (a real global,
10536 // class-static, function-static).
10537 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
10538
10539 // TODO: this should be re-enabled for static locals by !CXAAtExit
10540 if (!VD->isStaticLocal())
10541 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +000010542}
10543
Douglas Gregor39da0b82009-09-09 23:08:42 +000010544/// \brief Given a constructor and the set of arguments provided for the
10545/// constructor, convert the arguments and add any required default arguments
10546/// to form a proper call to this constructor.
10547///
10548/// \returns true if an error occurred, false otherwise.
10549bool
10550Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
10551 MultiExprArg ArgsPtr,
Richard Smith831421f2012-06-25 20:30:08 +000010552 SourceLocation Loc,
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +000010553 SmallVectorImpl<Expr*> &ConvertedArgs,
Richard Smitha4dc51b2013-02-05 05:52:24 +000010554 bool AllowExplicit,
10555 bool IsListInitialization) {
Douglas Gregor39da0b82009-09-09 23:08:42 +000010556 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
10557 unsigned NumArgs = ArgsPtr.size();
Benjamin Kramer5354e772012-08-23 23:38:35 +000010558 Expr **Args = ArgsPtr.data();
Douglas Gregor39da0b82009-09-09 23:08:42 +000010559
10560 const FunctionProtoType *Proto
10561 = Constructor->getType()->getAs<FunctionProtoType>();
10562 assert(Proto && "Constructor without a prototype?");
10563 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +000010564
10565 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010566 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +000010567 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010568 else
Douglas Gregor39da0b82009-09-09 23:08:42 +000010569 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010570
10571 VariadicCallType CallType =
10572 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner5f9e2722011-07-23 10:55:15 +000010573 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010574 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010575 Proto, 0,
10576 llvm::makeArrayRef(Args, NumArgs),
10577 AllArgs,
Richard Smitha4dc51b2013-02-05 05:52:24 +000010578 CallType, AllowExplicit,
10579 IsListInitialization);
Benjamin Kramer14c59822012-02-14 12:06:21 +000010580 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmane61eb042012-02-18 04:48:30 +000010581
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010582 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
Eli Friedmane61eb042012-02-18 04:48:30 +000010583
Dmitri Gribenko1c030e92013-01-13 20:46:02 +000010584 CheckConstructorCall(Constructor,
10585 llvm::makeArrayRef<const Expr *>(AllArgs.data(),
10586 AllArgs.size()),
Richard Smith831421f2012-06-25 20:30:08 +000010587 Proto, Loc);
Eli Friedmane61eb042012-02-18 04:48:30 +000010588
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010589 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +000010590}
10591
Anders Carlsson20d45d22009-12-12 00:32:00 +000010592static inline bool
10593CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
10594 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000010595 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +000010596 if (isa<NamespaceDecl>(DC)) {
10597 return SemaRef.Diag(FnDecl->getLocation(),
10598 diag::err_operator_new_delete_declared_in_namespace)
10599 << FnDecl->getDeclName();
10600 }
10601
10602 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +000010603 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +000010604 return SemaRef.Diag(FnDecl->getLocation(),
10605 diag::err_operator_new_delete_declared_static)
10606 << FnDecl->getDeclName();
10607 }
10608
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +000010609 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +000010610}
10611
Anders Carlsson156c78e2009-12-13 17:53:43 +000010612static inline bool
10613CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
10614 CanQualType ExpectedResultType,
10615 CanQualType ExpectedFirstParamType,
10616 unsigned DependentParamTypeDiag,
10617 unsigned InvalidParamTypeDiag) {
10618 QualType ResultType =
10619 FnDecl->getType()->getAs<FunctionType>()->getResultType();
10620
10621 // Check that the result type is not dependent.
10622 if (ResultType->isDependentType())
10623 return SemaRef.Diag(FnDecl->getLocation(),
10624 diag::err_operator_new_delete_dependent_result_type)
10625 << FnDecl->getDeclName() << ExpectedResultType;
10626
10627 // Check that the result type is what we expect.
10628 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
10629 return SemaRef.Diag(FnDecl->getLocation(),
10630 diag::err_operator_new_delete_invalid_result_type)
10631 << FnDecl->getDeclName() << ExpectedResultType;
10632
10633 // A function template must have at least 2 parameters.
10634 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
10635 return SemaRef.Diag(FnDecl->getLocation(),
10636 diag::err_operator_new_delete_template_too_few_parameters)
10637 << FnDecl->getDeclName();
10638
10639 // The function decl must have at least 1 parameter.
10640 if (FnDecl->getNumParams() == 0)
10641 return SemaRef.Diag(FnDecl->getLocation(),
10642 diag::err_operator_new_delete_too_few_parameters)
10643 << FnDecl->getDeclName();
10644
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +000010645 // Check the first parameter type is not dependent.
Anders Carlsson156c78e2009-12-13 17:53:43 +000010646 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
10647 if (FirstParamType->isDependentType())
10648 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
10649 << FnDecl->getDeclName() << ExpectedFirstParamType;
10650
10651 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +000010652 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +000010653 ExpectedFirstParamType)
10654 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
10655 << FnDecl->getDeclName() << ExpectedFirstParamType;
10656
10657 return false;
10658}
10659
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010660static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +000010661CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +000010662 // C++ [basic.stc.dynamic.allocation]p1:
10663 // A program is ill-formed if an allocation function is declared in a
10664 // namespace scope other than global scope or declared static in global
10665 // scope.
10666 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10667 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +000010668
10669 CanQualType SizeTy =
10670 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
10671
10672 // C++ [basic.stc.dynamic.allocation]p1:
10673 // The return type shall be void*. The first parameter shall have type
10674 // std::size_t.
10675 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
10676 SizeTy,
10677 diag::err_operator_new_dependent_param_type,
10678 diag::err_operator_new_param_type))
10679 return true;
10680
10681 // C++ [basic.stc.dynamic.allocation]p1:
10682 // The first parameter shall not have an associated default argument.
10683 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +000010684 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +000010685 diag::err_operator_new_default_arg)
10686 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
10687
10688 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +000010689}
10690
10691static bool
Richard Smith444d3842012-10-20 08:26:51 +000010692CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010693 // C++ [basic.stc.dynamic.deallocation]p1:
10694 // A program is ill-formed if deallocation functions are declared in a
10695 // namespace scope other than global scope or declared static in global
10696 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +000010697 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10698 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010699
10700 // C++ [basic.stc.dynamic.deallocation]p2:
10701 // Each deallocation function shall return void and its first parameter
10702 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +000010703 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
10704 SemaRef.Context.VoidPtrTy,
10705 diag::err_operator_delete_dependent_param_type,
10706 diag::err_operator_delete_param_type))
10707 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010708
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010709 return false;
10710}
10711
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010712/// CheckOverloadedOperatorDeclaration - Check whether the declaration
10713/// of this overloaded operator is well-formed. If so, returns false;
10714/// otherwise, emits appropriate diagnostics and returns true.
10715bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010716 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010717 "Expected an overloaded operator declaration");
10718
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010719 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
10720
Mike Stump1eb44332009-09-09 15:08:12 +000010721 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010722 // The allocation and deallocation functions, operator new,
10723 // operator new[], operator delete and operator delete[], are
10724 // described completely in 3.7.3. The attributes and restrictions
10725 // found in the rest of this subclause do not apply to them unless
10726 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +000010727 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010728 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +000010729
Anders Carlssona3ccda52009-12-12 00:26:23 +000010730 if (Op == OO_New || Op == OO_Array_New)
10731 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010732
10733 // C++ [over.oper]p6:
10734 // An operator function shall either be a non-static member
10735 // function or be a non-member function and have at least one
10736 // parameter whose type is a class, a reference to a class, an
10737 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010738 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
10739 if (MethodDecl->isStatic())
10740 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010741 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010742 } else {
10743 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010744 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
10745 ParamEnd = FnDecl->param_end();
10746 Param != ParamEnd; ++Param) {
10747 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +000010748 if (ParamType->isDependentType() || ParamType->isRecordType() ||
10749 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010750 ClassOrEnumParam = true;
10751 break;
10752 }
10753 }
10754
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010755 if (!ClassOrEnumParam)
10756 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +000010757 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010758 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010759 }
10760
10761 // C++ [over.oper]p8:
10762 // An operator function cannot have default arguments (8.3.6),
10763 // except where explicitly stated below.
10764 //
Mike Stump1eb44332009-09-09 15:08:12 +000010765 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010766 // (C++ [over.call]p1).
10767 if (Op != OO_Call) {
10768 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
10769 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +000010770 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +000010771 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +000010772 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +000010773 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010774 }
10775 }
10776
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010777 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
10778 { false, false, false }
10779#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
10780 , { Unary, Binary, MemberOnly }
10781#include "clang/Basic/OperatorKinds.def"
10782 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010783
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010784 bool CanBeUnaryOperator = OperatorUses[Op][0];
10785 bool CanBeBinaryOperator = OperatorUses[Op][1];
10786 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010787
10788 // C++ [over.oper]p8:
10789 // [...] Operator functions cannot have more or fewer parameters
10790 // than the number required for the corresponding operator, as
10791 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +000010792 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010793 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010794 if (Op != OO_Call &&
10795 ((NumParams == 1 && !CanBeUnaryOperator) ||
10796 (NumParams == 2 && !CanBeBinaryOperator) ||
10797 (NumParams < 1) || (NumParams > 2))) {
10798 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +000010799 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010800 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +000010801 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010802 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +000010803 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010804 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +000010805 assert(CanBeBinaryOperator &&
10806 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +000010807 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010808 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010809
Chris Lattner416e46f2008-11-21 07:57:12 +000010810 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010811 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010812 }
Sebastian Redl64b45f72009-01-05 20:52:13 +000010813
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010814 // Overloaded operators other than operator() cannot be variadic.
10815 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +000010816 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +000010817 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010818 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010819 }
10820
10821 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010822 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
10823 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +000010824 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010825 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010826 }
10827
10828 // C++ [over.inc]p1:
10829 // The user-defined function called operator++ implements the
10830 // prefix and postfix ++ operator. If this function is a member
10831 // function with no parameters, or a non-member function with one
10832 // parameter of class or enumeration type, it defines the prefix
10833 // increment operator ++ for objects of that type. If the function
10834 // is a member function with one parameter (which shall be of type
10835 // int) or a non-member function with two parameters (the second
10836 // of which shall be of type int), it defines the postfix
10837 // increment operator ++ for objects of that type.
10838 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
10839 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
10840 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +000010841 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010842 ParamIsInt = BT->getKind() == BuiltinType::Int;
10843
Chris Lattneraf7ae4e2008-11-21 07:50:02 +000010844 if (!ParamIsInt)
10845 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +000010846 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +000010847 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010848 }
10849
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010850 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010851}
Chris Lattner5a003a42008-12-17 07:09:26 +000010852
Sean Hunta6c058d2010-01-13 09:01:02 +000010853/// CheckLiteralOperatorDeclaration - Check whether the declaration
10854/// of this literal operator function is well-formed. If so, returns
10855/// false; otherwise, emits appropriate diagnostics and returns true.
10856bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smithe5658f02012-03-10 22:18:57 +000010857 if (isa<CXXMethodDecl>(FnDecl)) {
Sean Hunta6c058d2010-01-13 09:01:02 +000010858 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
10859 << FnDecl->getDeclName();
10860 return true;
10861 }
10862
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010863 if (FnDecl->isExternC()) {
10864 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
10865 return true;
10866 }
10867
Sean Hunta6c058d2010-01-13 09:01:02 +000010868 bool Valid = false;
10869
Richard Smith36f5cfe2012-03-09 08:00:36 +000010870 // This might be the definition of a literal operator template.
10871 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
10872 // This might be a specialization of a literal operator template.
10873 if (!TpDecl)
10874 TpDecl = FnDecl->getPrimaryTemplate();
10875
Richard Smithb328e292013-10-07 19:57:58 +000010876 // template <char...> type operator "" name() and
10877 // template <class T, T...> type operator "" name() are the only valid
10878 // template signatures, and the only valid signatures with no parameters.
Richard Smith36f5cfe2012-03-09 08:00:36 +000010879 if (TpDecl) {
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010880 if (FnDecl->param_size() == 0) {
Richard Smithb328e292013-10-07 19:57:58 +000010881 // Must have one or two template parameters
Sean Hunt216c2782010-04-07 23:11:06 +000010882 TemplateParameterList *Params = TpDecl->getTemplateParameters();
10883 if (Params->size() == 1) {
10884 NonTypeTemplateParmDecl *PmDecl =
Richard Smith5295b972012-08-03 21:14:57 +000010885 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +000010886
Sean Hunt216c2782010-04-07 23:11:06 +000010887 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +000010888 if (PmDecl && PmDecl->isTemplateParameterPack() &&
10889 Context.hasSameType(PmDecl->getType(), Context.CharTy))
10890 Valid = true;
Richard Smithb328e292013-10-07 19:57:58 +000010891 } else if (Params->size() == 2) {
10892 TemplateTypeParmDecl *PmType =
10893 dyn_cast<TemplateTypeParmDecl>(Params->getParam(0));
10894 NonTypeTemplateParmDecl *PmArgs =
10895 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
10896
10897 // The second template parameter must be a parameter pack with the
10898 // first template parameter as its type.
10899 if (PmType && PmArgs &&
10900 !PmType->isTemplateParameterPack() &&
10901 PmArgs->isTemplateParameterPack()) {
10902 const TemplateTypeParmType *TArgs =
10903 PmArgs->getType()->getAs<TemplateTypeParmType>();
10904 if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
10905 TArgs->getIndex() == PmType->getIndex()) {
10906 Valid = true;
10907 if (ActiveTemplateInstantiations.empty())
10908 Diag(FnDecl->getLocation(),
10909 diag::ext_string_literal_operator_template);
10910 }
10911 }
Sean Hunt216c2782010-04-07 23:11:06 +000010912 }
10913 }
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010914 } else if (FnDecl->param_size()) {
Sean Hunta6c058d2010-01-13 09:01:02 +000010915 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +000010916 FunctionDecl::param_iterator Param = FnDecl->param_begin();
10917
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010918 QualType T = (*Param)->getType().getUnqualifiedType();
Sean Hunta6c058d2010-01-13 09:01:02 +000010919
Sean Hunt30019c02010-04-07 22:57:35 +000010920 // unsigned long long int, long double, and any character type are allowed
10921 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +000010922 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
10923 Context.hasSameType(T, Context.LongDoubleTy) ||
10924 Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg15f92ba2013-05-10 10:08:40 +000010925 Context.hasSameType(T, Context.WideCharTy) ||
Sean Hunta6c058d2010-01-13 09:01:02 +000010926 Context.hasSameType(T, Context.Char16Ty) ||
10927 Context.hasSameType(T, Context.Char32Ty)) {
10928 if (++Param == FnDecl->param_end())
10929 Valid = true;
10930 goto FinishedParams;
10931 }
10932
Sean Hunt30019c02010-04-07 22:57:35 +000010933 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +000010934 const PointerType *PT = T->getAs<PointerType>();
10935 if (!PT)
10936 goto FinishedParams;
10937 T = PT->getPointeeType();
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010938 if (!T.isConstQualified() || T.isVolatileQualified())
Sean Hunta6c058d2010-01-13 09:01:02 +000010939 goto FinishedParams;
10940 T = T.getUnqualifiedType();
10941
10942 // Move on to the second parameter;
10943 ++Param;
10944
10945 // If there is no second parameter, the first must be a const char *
10946 if (Param == FnDecl->param_end()) {
10947 if (Context.hasSameType(T, Context.CharTy))
10948 Valid = true;
10949 goto FinishedParams;
10950 }
10951
10952 // const char *, const wchar_t*, const char16_t*, and const char32_t*
10953 // are allowed as the first parameter to a two-parameter function
10954 if (!(Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg15f92ba2013-05-10 10:08:40 +000010955 Context.hasSameType(T, Context.WideCharTy) ||
Sean Hunta6c058d2010-01-13 09:01:02 +000010956 Context.hasSameType(T, Context.Char16Ty) ||
10957 Context.hasSameType(T, Context.Char32Ty)))
10958 goto FinishedParams;
10959
10960 // The second and final parameter must be an std::size_t
10961 T = (*Param)->getType().getUnqualifiedType();
10962 if (Context.hasSameType(T, Context.getSizeType()) &&
10963 ++Param == FnDecl->param_end())
10964 Valid = true;
10965 }
10966
10967 // FIXME: This diagnostic is absolutely terrible.
10968FinishedParams:
10969 if (!Valid) {
10970 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
10971 << FnDecl->getDeclName();
10972 return true;
10973 }
10974
Richard Smitha9e88b22012-03-09 08:16:22 +000010975 // A parameter-declaration-clause containing a default argument is not
10976 // equivalent to any of the permitted forms.
10977 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
10978 ParamEnd = FnDecl->param_end();
10979 Param != ParamEnd; ++Param) {
10980 if ((*Param)->hasDefaultArg()) {
10981 Diag((*Param)->getDefaultArgRange().getBegin(),
10982 diag::err_literal_operator_default_argument)
10983 << (*Param)->getDefaultArgRange();
10984 break;
10985 }
10986 }
10987
Richard Smith2fb4ae32012-03-08 02:39:21 +000010988 StringRef LiteralName
Douglas Gregor1155c422011-08-30 22:40:35 +000010989 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
10990 if (LiteralName[0] != '_') {
Richard Smith2fb4ae32012-03-08 02:39:21 +000010991 // C++11 [usrlit.suffix]p1:
10992 // Literal suffix identifiers that do not start with an underscore
10993 // are reserved for future standardization.
Richard Smith4ac537b2013-07-23 08:14:48 +000010994 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
10995 << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
Douglas Gregor1155c422011-08-30 22:40:35 +000010996 }
Richard Smith2fb4ae32012-03-08 02:39:21 +000010997
Sean Hunta6c058d2010-01-13 09:01:02 +000010998 return false;
10999}
11000
Douglas Gregor074149e2009-01-05 19:45:36 +000011001/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
11002/// linkage specification, including the language and (if present)
11003/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
11004/// the location of the language string literal, which is provided
11005/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
11006/// the '{' brace. Otherwise, this linkage specification does not
11007/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +000011008Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
11009 SourceLocation LangLoc,
Chris Lattner5f9e2722011-07-23 10:55:15 +000011010 StringRef Lang,
Chris Lattner7d642712010-11-09 20:15:55 +000011011 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +000011012 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +000011013 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +000011014 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +000011015 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +000011016 Language = LinkageSpecDecl::lang_cxx;
11017 else {
Douglas Gregor074149e2009-01-05 19:45:36 +000011018 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +000011019 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +000011020 }
Mike Stump1eb44332009-09-09 15:08:12 +000011021
Chris Lattnercc98eac2008-12-17 07:13:27 +000011022 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +000011023
Douglas Gregor074149e2009-01-05 19:45:36 +000011024 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Rafael Espindolae5e575d2013-04-26 01:30:23 +000011025 ExternLoc, LangLoc, Language,
11026 LBraceLoc.isValid());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000011027 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +000011028 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +000011029 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +000011030}
11031
Abramo Bagnara35f9a192010-07-30 16:47:02 +000011032/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +000011033/// the C++ linkage specification LinkageSpec. If RBraceLoc is
11034/// valid, it's the position of the closing '}' brace in a linkage
11035/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +000011036Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000011037 Decl *LinkageSpec,
11038 SourceLocation RBraceLoc) {
11039 if (LinkageSpec) {
11040 if (RBraceLoc.isValid()) {
11041 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
11042 LSDecl->setRBraceLoc(RBraceLoc);
11043 }
Douglas Gregor074149e2009-01-05 19:45:36 +000011044 PopDeclContext();
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000011045 }
Douglas Gregor074149e2009-01-05 19:45:36 +000011046 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +000011047}
11048
Michael Han684aa732013-02-22 17:15:32 +000011049Decl *Sema::ActOnEmptyDeclaration(Scope *S,
11050 AttributeList *AttrList,
11051 SourceLocation SemiLoc) {
11052 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
11053 // Attribute declarations appertain to empty declaration so we handle
11054 // them here.
11055 if (AttrList)
11056 ProcessDeclAttributeList(S, ED, AttrList);
Richard Smith6b3d3e52013-02-20 19:22:51 +000011057
Michael Han684aa732013-02-22 17:15:32 +000011058 CurContext->addDecl(ED);
11059 return ED;
Richard Smith6b3d3e52013-02-20 19:22:51 +000011060}
11061
Douglas Gregord308e622009-05-18 20:51:54 +000011062/// \brief Perform semantic analysis for the variable declaration that
11063/// occurs within a C++ catch clause, returning the newly-created
11064/// variable.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000011065VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +000011066 TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000011067 SourceLocation StartLoc,
11068 SourceLocation Loc,
11069 IdentifierInfo *Name) {
Douglas Gregord308e622009-05-18 20:51:54 +000011070 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +000011071 QualType ExDeclType = TInfo->getType();
11072
Sebastian Redl4b07b292008-12-22 19:15:10 +000011073 // Arrays and functions decay.
11074 if (ExDeclType->isArrayType())
11075 ExDeclType = Context.getArrayDecayedType(ExDeclType);
11076 else if (ExDeclType->isFunctionType())
11077 ExDeclType = Context.getPointerType(ExDeclType);
11078
11079 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
11080 // The exception-declaration shall not denote a pointer or reference to an
11081 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +000011082 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +000011083 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +000011084 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +000011085 Invalid = true;
11086 }
Douglas Gregord308e622009-05-18 20:51:54 +000011087
Sebastian Redl4b07b292008-12-22 19:15:10 +000011088 QualType BaseType = ExDeclType;
11089 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +000011090 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +000011091 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000011092 BaseType = Ptr->getPointeeType();
11093 Mode = 1;
Douglas Gregorecd7b042012-01-24 19:01:26 +000011094 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +000011095 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +000011096 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +000011097 BaseType = Ref->getPointeeType();
11098 Mode = 2;
Douglas Gregorecd7b042012-01-24 19:01:26 +000011099 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +000011100 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +000011101 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregorecd7b042012-01-24 19:01:26 +000011102 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +000011103 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000011104
Mike Stump1eb44332009-09-09 15:08:12 +000011105 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +000011106 RequireNonAbstractType(Loc, ExDeclType,
11107 diag::err_abstract_type_in_decl,
11108 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +000011109 Invalid = true;
11110
John McCall5a180392010-07-24 00:37:23 +000011111 // Only the non-fragile NeXT runtime currently supports C++ catches
11112 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikie4e4d0842012-03-11 07:00:24 +000011113 if (!Invalid && getLangOpts().ObjC1) {
John McCall5a180392010-07-24 00:37:23 +000011114 QualType T = ExDeclType;
11115 if (const ReferenceType *RT = T->getAs<ReferenceType>())
11116 T = RT->getPointeeType();
11117
11118 if (T->isObjCObjectType()) {
11119 Diag(Loc, diag::err_objc_object_catch);
11120 Invalid = true;
11121 } else if (T->isObjCObjectPointerType()) {
John McCall260611a2012-06-20 06:18:46 +000011122 // FIXME: should this be a test for macosx-fragile specifically?
11123 if (getLangOpts().ObjCRuntime.isFragile())
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +000011124 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall5a180392010-07-24 00:37:23 +000011125 }
11126 }
11127
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000011128 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
Rafael Espindolad2615cc2013-04-03 19:27:57 +000011129 ExDeclType, TInfo, SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +000011130 ExDecl->setExceptionVariable(true);
11131
Douglas Gregor9aab9c42011-12-10 01:22:52 +000011132 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +000011133 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor9aab9c42011-12-10 01:22:52 +000011134 Invalid = true;
11135
Douglas Gregorc41b8782011-07-06 18:14:43 +000011136 if (!Invalid && !ExDeclType->isDependentType()) {
John McCalle996ffd2011-02-16 08:02:54 +000011137 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
John McCallb760f112013-03-22 02:10:40 +000011138 // Insulate this from anything else we might currently be parsing.
11139 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
11140
Douglas Gregor6d182892010-03-05 23:38:39 +000011141 // C++ [except.handle]p16:
Nick Lewyckyee0bc3b2013-09-22 10:06:57 +000011142 // The object declared in an exception-declaration or, if the
11143 // exception-declaration does not specify a name, a temporary (12.2) is
Douglas Gregor6d182892010-03-05 23:38:39 +000011144 // copy-initialized (8.5) from the exception object. [...]
11145 // The object is destroyed when the handler exits, after the destruction
11146 // of any automatic objects initialized within the handler.
11147 //
Nick Lewyckyee0bc3b2013-09-22 10:06:57 +000011148 // We just pretend to initialize the object with itself, then make sure
Douglas Gregor6d182892010-03-05 23:38:39 +000011149 // it can be destroyed later.
John McCalle996ffd2011-02-16 08:02:54 +000011150 QualType initType = ExDeclType;
11151
11152 InitializedEntity entity =
11153 InitializedEntity::InitializeVariable(ExDecl);
11154 InitializationKind initKind =
11155 InitializationKind::CreateCopy(Loc, SourceLocation());
11156
11157 Expr *opaqueValue =
11158 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +000011159 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
11160 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
John McCalle996ffd2011-02-16 08:02:54 +000011161 if (result.isInvalid())
Douglas Gregor6d182892010-03-05 23:38:39 +000011162 Invalid = true;
John McCalle996ffd2011-02-16 08:02:54 +000011163 else {
11164 // If the constructor used was non-trivial, set this as the
11165 // "initializer".
Nick Lewyckyee0bc3b2013-09-22 10:06:57 +000011166 CXXConstructExpr *construct = result.takeAs<CXXConstructExpr>();
John McCalle996ffd2011-02-16 08:02:54 +000011167 if (!construct->getConstructor()->isTrivial()) {
11168 Expr *init = MaybeCreateExprWithCleanups(construct);
11169 ExDecl->setInit(init);
11170 }
11171
11172 // And make sure it's destructable.
11173 FinalizeVarWithDestructor(ExDecl, recordType);
11174 }
Douglas Gregor6d182892010-03-05 23:38:39 +000011175 }
11176 }
11177
Douglas Gregord308e622009-05-18 20:51:54 +000011178 if (Invalid)
11179 ExDecl->setInvalidDecl();
11180
11181 return ExDecl;
11182}
11183
11184/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
11185/// handler.
John McCalld226f652010-08-21 09:40:31 +000011186Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +000011187 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +000011188 bool Invalid = D.isInvalidType();
11189
11190 // Check for unexpanded parameter packs.
Jordan Rose41f3f3a2013-03-05 01:27:54 +000011191 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
11192 UPPC_ExceptionType)) {
Douglas Gregora669c532010-12-16 17:48:04 +000011193 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
11194 D.getIdentifierLoc());
11195 Invalid = true;
11196 }
11197
Sebastian Redl4b07b292008-12-22 19:15:10 +000011198 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +000011199 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +000011200 LookupOrdinaryName,
11201 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000011202 // The scope should be freshly made just for us. There is just no way
11203 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +000011204 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +000011205 if (PrevDecl->isTemplateParameter()) {
11206 // Maybe we will complain about the shadowed template parameter.
11207 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregorcb8f9512011-10-20 17:58:49 +000011208 PrevDecl = 0;
Sebastian Redl4b07b292008-12-22 19:15:10 +000011209 }
11210 }
11211
Chris Lattnereaaebc72009-04-25 08:06:05 +000011212 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000011213 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
11214 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +000011215 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000011216 }
11217
Douglas Gregor83cb9422010-09-09 17:09:21 +000011218 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar96a00142012-03-09 18:35:03 +000011219 D.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000011220 D.getIdentifierLoc(),
11221 D.getIdentifier());
Chris Lattnereaaebc72009-04-25 08:06:05 +000011222 if (Invalid)
11223 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +000011224
Sebastian Redl4b07b292008-12-22 19:15:10 +000011225 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +000011226 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +000011227 PushOnScopeChains(ExDecl, S);
11228 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000011229 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +000011230
Douglas Gregor9cdda0c2009-06-17 21:51:59 +000011231 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +000011232 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +000011233}
Anders Carlssonfb311762009-03-14 00:25:26 +000011234
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000011235Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +000011236 Expr *AssertExpr,
Richard Smithe3f470a2012-07-11 22:37:56 +000011237 Expr *AssertMessageExpr,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000011238 SourceLocation RParenLoc) {
Richard Smithe3f470a2012-07-11 22:37:56 +000011239 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr);
Anders Carlssonfb311762009-03-14 00:25:26 +000011240
Richard Smithe3f470a2012-07-11 22:37:56 +000011241 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
11242 return 0;
11243
11244 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
11245 AssertMessage, RParenLoc, false);
11246}
11247
11248Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
11249 Expr *AssertExpr,
11250 StringLiteral *AssertMessage,
11251 SourceLocation RParenLoc,
11252 bool Failed) {
11253 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
11254 !Failed) {
Richard Smith282e7e62012-02-04 09:53:13 +000011255 // In a static_assert-declaration, the constant-expression shall be a
11256 // constant expression that can be contextually converted to bool.
11257 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
11258 if (Converted.isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000011259 Failed = true;
Richard Smith282e7e62012-02-04 09:53:13 +000011260
Richard Smithdaaefc52011-12-14 23:32:26 +000011261 llvm::APSInt Cond;
Richard Smithe3f470a2012-07-11 22:37:56 +000011262 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregorab41fe92012-05-04 22:38:52 +000011263 diag::err_static_assert_expression_is_not_constant,
Richard Smith282e7e62012-02-04 09:53:13 +000011264 /*AllowFold=*/false).isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000011265 Failed = true;
Anders Carlssonfb311762009-03-14 00:25:26 +000011266
Richard Smithe3f470a2012-07-11 22:37:56 +000011267 if (!Failed && !Cond) {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000011268 SmallString<256> MsgBuffer;
Richard Smith0cc323c2012-03-05 23:20:05 +000011269 llvm::raw_svector_ostream Msg(MsgBuffer);
Richard Smithd1420c62012-08-16 03:56:14 +000011270 AssertMessage->printPretty(Msg, 0, getPrintingPolicy());
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000011271 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smith0cc323c2012-03-05 23:20:05 +000011272 << Msg.str() << AssertExpr->getSourceRange();
Richard Smithe3f470a2012-07-11 22:37:56 +000011273 Failed = true;
Richard Smith0cc323c2012-03-05 23:20:05 +000011274 }
Anders Carlssonc3082412009-03-14 00:33:21 +000011275 }
Mike Stump1eb44332009-09-09 15:08:12 +000011276
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000011277 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
Richard Smithe3f470a2012-07-11 22:37:56 +000011278 AssertExpr, AssertMessage, RParenLoc,
11279 Failed);
Mike Stump1eb44332009-09-09 15:08:12 +000011280
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000011281 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +000011282 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +000011283}
Sebastian Redl50de12f2009-03-24 22:27:57 +000011284
Douglas Gregor1d869352010-04-07 16:53:43 +000011285/// \brief Perform semantic analysis of the given friend type declaration.
11286///
11287/// \returns A friend declaration that.
Richard Smithd6f80da2012-09-20 01:31:00 +000011288FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
Abramo Bagnara0216df82011-10-29 20:52:52 +000011289 SourceLocation FriendLoc,
Douglas Gregor1d869352010-04-07 16:53:43 +000011290 TypeSourceInfo *TSInfo) {
11291 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
11292
11293 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +000011294 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +000011295
Richard Smith6b130222011-10-18 21:39:00 +000011296 // C++03 [class.friend]p2:
11297 // An elaborated-type-specifier shall be used in a friend declaration
11298 // for a class.*
11299 //
11300 // * The class-key of the elaborated-type-specifier is required.
11301 if (!ActiveTemplateInstantiations.empty()) {
11302 // Do not complain about the form of friend template types during
11303 // template instantiation; we will already have complained when the
11304 // template was declared.
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000011305 } else {
11306 if (!T->isElaboratedTypeSpecifier()) {
11307 // If we evaluated the type to a record type, suggest putting
11308 // a tag in front.
11309 if (const RecordType *RT = T->getAs<RecordType>()) {
11310 RecordDecl *RD = RT->getDecl();
Richard Smith6b130222011-10-18 21:39:00 +000011311
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000011312 std::string InsertionText = std::string(" ") + RD->getKindName();
Richard Smith6b130222011-10-18 21:39:00 +000011313
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000011314 Diag(TypeRange.getBegin(),
11315 getLangOpts().CPlusPlus11 ?
11316 diag::warn_cxx98_compat_unelaborated_friend_type :
11317 diag::ext_unelaborated_friend_type)
11318 << (unsigned) RD->getTagKind()
11319 << T
11320 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
11321 InsertionText);
11322 } else {
11323 Diag(FriendLoc,
11324 getLangOpts().CPlusPlus11 ?
11325 diag::warn_cxx98_compat_nonclass_type_friend :
11326 diag::ext_nonclass_type_friend)
11327 << T
11328 << TypeRange;
11329 }
11330 } else if (T->getAs<EnumType>()) {
Richard Smith6b130222011-10-18 21:39:00 +000011331 Diag(FriendLoc,
Richard Smith80ad52f2013-01-02 11:42:31 +000011332 getLangOpts().CPlusPlus11 ?
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000011333 diag::warn_cxx98_compat_enum_friend :
11334 diag::ext_enum_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +000011335 << T
Richard Smithd6f80da2012-09-20 01:31:00 +000011336 << TypeRange;
Douglas Gregor1d869352010-04-07 16:53:43 +000011337 }
Douglas Gregor1d869352010-04-07 16:53:43 +000011338
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000011339 // C++11 [class.friend]p3:
11340 // A friend declaration that does not declare a function shall have one
11341 // of the following forms:
11342 // friend elaborated-type-specifier ;
11343 // friend simple-type-specifier ;
11344 // friend typename-specifier ;
11345 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
11346 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
11347 }
Richard Smithd6f80da2012-09-20 01:31:00 +000011348
Douglas Gregor06245bf2010-04-07 17:57:12 +000011349 // If the type specifier in a friend declaration designates a (possibly
Richard Smithd6f80da2012-09-20 01:31:00 +000011350 // cv-qualified) class type, that class is declared as a friend; otherwise,
Douglas Gregor06245bf2010-04-07 17:57:12 +000011351 // the friend declaration is ignored.
Richard Smithd6f80da2012-09-20 01:31:00 +000011352 return FriendDecl::Create(Context, CurContext, LocStart, TSInfo, FriendLoc);
Douglas Gregor1d869352010-04-07 16:53:43 +000011353}
11354
John McCall9a34edb2010-10-19 01:40:49 +000011355/// Handle a friend tag declaration where the scope specifier was
11356/// templated.
11357Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
11358 unsigned TagSpec, SourceLocation TagLoc,
11359 CXXScopeSpec &SS,
Enea Zaffanella8c840282013-01-31 09:54:08 +000011360 IdentifierInfo *Name,
11361 SourceLocation NameLoc,
John McCall9a34edb2010-10-19 01:40:49 +000011362 AttributeList *Attr,
11363 MultiTemplateParamsArg TempParamLists) {
11364 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
11365
11366 bool isExplicitSpecialization = false;
John McCall9a34edb2010-10-19 01:40:49 +000011367 bool Invalid = false;
11368
Robert Wilhelm1169e2f2013-07-21 15:20:44 +000011369 if (TemplateParameterList *TemplateParams =
11370 MatchTemplateParametersToScopeSpecifier(
11371 TagLoc, NameLoc, SS, TempParamLists, /*friend*/ true,
11372 isExplicitSpecialization, Invalid)) {
John McCall9a34edb2010-10-19 01:40:49 +000011373 if (TemplateParams->size() > 0) {
11374 // This is a declaration of a class template.
11375 if (Invalid)
11376 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +000011377
Eric Christopher4110e132011-07-21 05:34:24 +000011378 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
11379 SS, Name, NameLoc, Attr,
11380 TemplateParams, AS_public,
Douglas Gregore7612302011-09-09 19:05:14 +000011381 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher4110e132011-07-21 05:34:24 +000011382 TempParamLists.size() - 1,
Benjamin Kramer5354e772012-08-23 23:38:35 +000011383 TempParamLists.data()).take();
John McCall9a34edb2010-10-19 01:40:49 +000011384 } else {
11385 // The "template<>" header is extraneous.
11386 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
11387 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
11388 isExplicitSpecialization = true;
11389 }
11390 }
11391
11392 if (Invalid) return 0;
11393
John McCall9a34edb2010-10-19 01:40:49 +000011394 bool isAllExplicitSpecializations = true;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +000011395 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000011396 if (TempParamLists[I]->size()) {
John McCall9a34edb2010-10-19 01:40:49 +000011397 isAllExplicitSpecializations = false;
11398 break;
11399 }
11400 }
11401
11402 // FIXME: don't ignore attributes.
11403
11404 // If it's explicit specializations all the way down, just forget
11405 // about the template header and build an appropriate non-templated
11406 // friend. TODO: for source fidelity, remember the headers.
11407 if (isAllExplicitSpecializations) {
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000011408 if (SS.isEmpty()) {
11409 bool Owned = false;
11410 bool IsDependent = false;
11411 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
11412 Attr, AS_public,
11413 /*ModulePrivateLoc=*/SourceLocation(),
11414 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smithbdad7a22012-01-10 01:33:14 +000011415 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000011416 /*ScopedEnumUsesClassTag=*/false,
11417 /*UnderlyingType=*/TypeResult());
11418 }
11419
Douglas Gregor2494dd02011-03-01 01:34:45 +000011420 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall9a34edb2010-10-19 01:40:49 +000011421 ElaboratedTypeKeyword Keyword
11422 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor2494dd02011-03-01 01:34:45 +000011423 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +000011424 *Name, NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000011425 if (T.isNull())
11426 return 0;
11427
11428 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
11429 if (isa<DependentNameType>(T)) {
David Blaikie39e6ab42013-02-18 22:06:02 +000011430 DependentNameTypeLoc TL =
11431 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000011432 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000011433 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +000011434 TL.setNameLoc(NameLoc);
11435 } else {
David Blaikie39e6ab42013-02-18 22:06:02 +000011436 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000011437 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +000011438 TL.setQualifierLoc(QualifierLoc);
David Blaikie39e6ab42013-02-18 22:06:02 +000011439 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000011440 }
11441
11442 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanella8c840282013-01-31 09:54:08 +000011443 TSI, FriendLoc, TempParamLists);
John McCall9a34edb2010-10-19 01:40:49 +000011444 Friend->setAccess(AS_public);
11445 CurContext->addDecl(Friend);
11446 return Friend;
11447 }
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000011448
11449 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
11450
11451
John McCall9a34edb2010-10-19 01:40:49 +000011452
11453 // Handle the case of a templated-scope friend class. e.g.
11454 // template <class T> class A<T>::B;
11455 // FIXME: we don't support these right now.
11456 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
11457 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
11458 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
David Blaikie39e6ab42013-02-18 22:06:02 +000011459 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000011460 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000011461 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCall9a34edb2010-10-19 01:40:49 +000011462 TL.setNameLoc(NameLoc);
11463
11464 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanella8c840282013-01-31 09:54:08 +000011465 TSI, FriendLoc, TempParamLists);
John McCall9a34edb2010-10-19 01:40:49 +000011466 Friend->setAccess(AS_public);
11467 Friend->setUnsupportedFriend(true);
11468 CurContext->addDecl(Friend);
11469 return Friend;
11470}
11471
11472
John McCalldd4a3b02009-09-16 22:47:08 +000011473/// Handle a friend type declaration. This works in tandem with
11474/// ActOnTag.
11475///
11476/// Notes on friend class templates:
11477///
11478/// We generally treat friend class declarations as if they were
11479/// declaring a class. So, for example, the elaborated type specifier
11480/// in a friend declaration is required to obey the restrictions of a
11481/// class-head (i.e. no typedefs in the scope chain), template
11482/// parameters are required to match up with simple template-ids, &c.
11483/// However, unlike when declaring a template specialization, it's
11484/// okay to refer to a template specialization without an empty
11485/// template parameter declaration, e.g.
11486/// friend class A<T>::B<unsigned>;
11487/// We permit this as a special case; if there are any template
11488/// parameters present at all, require proper matching, i.e.
James Dennettef2b5b32012-06-15 22:23:43 +000011489/// template <> template \<class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +000011490Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +000011491 MultiTemplateParamsArg TempParams) {
Daniel Dunbar96a00142012-03-09 18:35:03 +000011492 SourceLocation Loc = DS.getLocStart();
John McCall67d1a672009-08-06 02:15:43 +000011493
11494 assert(DS.isFriendSpecified());
11495 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11496
John McCalldd4a3b02009-09-16 22:47:08 +000011497 // Try to convert the decl specifier to a type. This works for
11498 // friend templates because ActOnTag never produces a ClassTemplateDecl
11499 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +000011500 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +000011501 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
11502 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +000011503 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +000011504 return 0;
John McCall67d1a672009-08-06 02:15:43 +000011505
Douglas Gregor6ccab972010-12-16 01:14:37 +000011506 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
11507 return 0;
11508
John McCalldd4a3b02009-09-16 22:47:08 +000011509 // This is definitely an error in C++98. It's probably meant to
11510 // be forbidden in C++0x, too, but the specification is just
11511 // poorly written.
11512 //
11513 // The problem is with declarations like the following:
11514 // template <T> friend A<T>::foo;
11515 // where deciding whether a class C is a friend or not now hinges
11516 // on whether there exists an instantiation of A that causes
11517 // 'foo' to equal C. There are restrictions on class-heads
11518 // (which we declare (by fiat) elaborated friend declarations to
11519 // be) that makes this tractable.
11520 //
11521 // FIXME: handle "template <> friend class A<T>;", which
11522 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +000011523 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +000011524 Diag(Loc, diag::err_tagless_friend_type_template)
11525 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +000011526 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +000011527 }
Douglas Gregor1d869352010-04-07 16:53:43 +000011528
John McCall02cace72009-08-28 07:59:38 +000011529 // C++98 [class.friend]p1: A friend of a class is a function
11530 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +000011531 // This is fixed in DR77, which just barely didn't make the C++03
11532 // deadline. It's also a very silly restriction that seriously
11533 // affects inner classes and which nobody else seems to implement;
11534 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +000011535 //
11536 // But note that we could warn about it: it's always useless to
11537 // friend one of your own members (it's not, however, worthless to
11538 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +000011539
John McCalldd4a3b02009-09-16 22:47:08 +000011540 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +000011541 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +000011542 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +000011543 NumTempParamLists,
Benjamin Kramer5354e772012-08-23 23:38:35 +000011544 TempParams.data(),
John McCall32f2fb52010-03-25 18:04:51 +000011545 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +000011546 DS.getFriendSpecLoc());
11547 else
Abramo Bagnara0216df82011-10-29 20:52:52 +000011548 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregor1d869352010-04-07 16:53:43 +000011549
11550 if (!D)
John McCalld226f652010-08-21 09:40:31 +000011551 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +000011552
John McCalldd4a3b02009-09-16 22:47:08 +000011553 D->setAccess(AS_public);
11554 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +000011555
John McCalld226f652010-08-21 09:40:31 +000011556 return D;
John McCall02cace72009-08-28 07:59:38 +000011557}
11558
Rafael Espindolafc35cbc2013-01-08 20:44:06 +000011559NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
11560 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +000011561 const DeclSpec &DS = D.getDeclSpec();
11562
11563 assert(DS.isFriendSpecified());
11564 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11565
11566 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +000011567 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall67d1a672009-08-06 02:15:43 +000011568
11569 // C++ [class.friend]p1
11570 // A friend of a class is a function or class....
11571 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +000011572 // It *doesn't* see through dependent types, which is correct
11573 // according to [temp.arg.type]p3:
11574 // If a declaration acquires a function type through a
11575 // type dependent on a template-parameter and this causes
11576 // a declaration that does not use the syntactic form of a
11577 // function declarator to have a function type, the program
11578 // is ill-formed.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011579 if (!TInfo->getType()->isFunctionType()) {
John McCall67d1a672009-08-06 02:15:43 +000011580 Diag(Loc, diag::err_unexpected_friend);
11581
11582 // It might be worthwhile to try to recover by creating an
11583 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +000011584 return 0;
John McCall67d1a672009-08-06 02:15:43 +000011585 }
11586
11587 // C++ [namespace.memdef]p3
11588 // - If a friend declaration in a non-local class first declares a
11589 // class or function, the friend class or function is a member
11590 // of the innermost enclosing namespace.
11591 // - The name of the friend is not found by simple name lookup
11592 // until a matching declaration is provided in that namespace
11593 // scope (either before or after the class declaration granting
11594 // friendship).
11595 // - If a friend function is called, its name may be found by the
11596 // name lookup that considers functions from namespaces and
11597 // classes associated with the types of the function arguments.
11598 // - When looking for a prior declaration of a class or a function
11599 // declared as a friend, scopes outside the innermost enclosing
11600 // namespace scope are not considered.
11601
John McCall337ec3d2010-10-12 23:13:28 +000011602 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +000011603 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
11604 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +000011605 assert(Name);
11606
Douglas Gregor6ccab972010-12-16 01:14:37 +000011607 // Check for unexpanded parameter packs.
11608 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
11609 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
11610 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
11611 return 0;
11612
John McCall67d1a672009-08-06 02:15:43 +000011613 // The context we found the declaration in, or in which we should
11614 // create the declaration.
11615 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +000011616 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +000011617 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +000011618 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +000011619
Richard Smith4e9686b2013-08-09 04:35:01 +000011620 // There are five cases here.
11621 // - There's no scope specifier and we're in a local class. Only look
11622 // for functions declared in the immediately-enclosing block scope.
11623 // We recover from invalid scope qualifiers as if they just weren't there.
11624 FunctionDecl *FunctionContainingLocalClass = 0;
11625 if ((SS.isInvalid() || !SS.isSet()) &&
11626 (FunctionContainingLocalClass =
11627 cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
11628 // C++11 [class.friend]p11:
John McCall29ae6e52010-10-13 05:45:15 +000011629 // If a friend declaration appears in a local class and the name
11630 // specified is an unqualified name, a prior declaration is
11631 // looked up without considering scopes that are outside the
11632 // innermost enclosing non-class scope. For a friend function
11633 // declaration, if there is no prior declaration, the program is
11634 // ill-formed.
Richard Smith4e9686b2013-08-09 04:35:01 +000011635
11636 // Find the innermost enclosing non-class scope. This is the block
11637 // scope containing the local class definition (or for a nested class,
11638 // the outer local class).
11639 DCScope = S->getFnParent();
11640
11641 // Look up the function name in the scope.
11642 Previous.clear(LookupLocalFriendName);
11643 LookupName(Previous, S, /*AllowBuiltinCreation*/false);
11644
11645 if (!Previous.empty()) {
11646 // All possible previous declarations must have the same context:
11647 // either they were declared at block scope or they are members of
11648 // one of the enclosing local classes.
11649 DC = Previous.getRepresentativeDecl()->getDeclContext();
11650 } else {
11651 // This is ill-formed, but provide the context that we would have
11652 // declared the function in, if we were permitted to, for error recovery.
11653 DC = FunctionContainingLocalClass;
11654 }
Richard Smitha41c97a2013-09-20 01:15:31 +000011655 adjustContextForLocalExternDecl(DC);
Richard Smith4e9686b2013-08-09 04:35:01 +000011656
11657 // C++ [class.friend]p6:
11658 // A function can be defined in a friend declaration of a class if and
11659 // only if the class is a non-local class (9.8), the function name is
11660 // unqualified, and the function has namespace scope.
11661 if (D.isFunctionDefinition()) {
11662 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
11663 }
11664
11665 // - There's no scope specifier, in which case we just go to the
11666 // appropriate scope and look for a function or function template
11667 // there as appropriate.
11668 } else if (SS.isInvalid() || !SS.isSet()) {
11669 // C++11 [namespace.memdef]p3:
11670 // If the name in a friend declaration is neither qualified nor
11671 // a template-id and the declaration is a function or an
11672 // elaborated-type-specifier, the lookup to determine whether
11673 // the entity has been previously declared shall not consider
11674 // any scopes outside the innermost enclosing namespace.
John McCall8a407372010-10-14 22:22:28 +000011675 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +000011676
John McCall29ae6e52010-10-13 05:45:15 +000011677 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +000011678 DC = CurContext;
John McCall67d1a672009-08-06 02:15:43 +000011679
Rafael Espindola11dc6342013-04-25 20:12:36 +000011680 // Skip class contexts. If someone can cite chapter and verse
11681 // for this behavior, that would be nice --- it's what GCC and
11682 // EDG do, and it seems like a reasonable intent, but the spec
11683 // really only says that checks for unqualified existing
11684 // declarations should stop at the nearest enclosing namespace,
11685 // not that they should only consider the nearest enclosing
11686 // namespace.
11687 while (DC->isRecord())
11688 DC = DC->getParent();
11689
11690 DeclContext *LookupDC = DC;
11691 while (LookupDC->isTransparentContext())
11692 LookupDC = LookupDC->getParent();
11693
11694 while (true) {
11695 LookupQualifiedName(Previous, LookupDC);
John McCall67d1a672009-08-06 02:15:43 +000011696
Rafael Espindola11dc6342013-04-25 20:12:36 +000011697 if (!Previous.empty()) {
11698 DC = LookupDC;
11699 break;
John McCall8a407372010-10-14 22:22:28 +000011700 }
Rafael Espindola11dc6342013-04-25 20:12:36 +000011701
11702 if (isTemplateId) {
11703 if (isa<TranslationUnitDecl>(LookupDC)) break;
11704 } else {
11705 if (LookupDC->isFileContext()) break;
11706 }
11707 LookupDC = LookupDC->getParent();
John McCall67d1a672009-08-06 02:15:43 +000011708 }
11709
John McCall380aaa42010-10-13 06:22:15 +000011710 DCScope = getScopeForDeclContext(S, DC);
Richard Smith4e9686b2013-08-09 04:35:01 +000011711
John McCall337ec3d2010-10-12 23:13:28 +000011712 // - There's a non-dependent scope specifier, in which case we
11713 // compute it and do a previous lookup there for a function
11714 // or function template.
11715 } else if (!SS.getScopeRep()->isDependent()) {
11716 DC = computeDeclContext(SS);
11717 if (!DC) return 0;
11718
11719 if (RequireCompleteDeclContext(SS, DC)) return 0;
11720
11721 LookupQualifiedName(Previous, DC);
11722
11723 // Ignore things found implicitly in the wrong scope.
11724 // TODO: better diagnostics for this case. Suggesting the right
11725 // qualified scope would be nice...
11726 LookupResult::Filter F = Previous.makeFilter();
11727 while (F.hasNext()) {
11728 NamedDecl *D = F.next();
11729 if (!DC->InEnclosingNamespaceSetOf(
11730 D->getDeclContext()->getRedeclContext()))
11731 F.erase();
11732 }
11733 F.done();
11734
11735 if (Previous.empty()) {
11736 D.setInvalidType();
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011737 Diag(Loc, diag::err_qualified_friend_not_found)
11738 << Name << TInfo->getType();
John McCall337ec3d2010-10-12 23:13:28 +000011739 return 0;
11740 }
11741
11742 // C++ [class.friend]p1: A friend of a class is a function or
11743 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000011744 if (DC->Equals(CurContext))
11745 Diag(DS.getFriendSpecLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +000011746 getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +000011747 diag::warn_cxx98_compat_friend_is_member :
11748 diag::err_friend_is_member);
Douglas Gregor883af832011-10-10 01:11:59 +000011749
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011750 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000011751 // C++ [class.friend]p6:
11752 // A function can be defined in a friend declaration of a class if and
11753 // only if the class is a non-local class (9.8), the function name is
11754 // unqualified, and the function has namespace scope.
11755 SemaDiagnosticBuilder DB
11756 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
11757
11758 DB << SS.getScopeRep();
11759 if (DC->isFileContext())
11760 DB << FixItHint::CreateRemoval(SS.getRange());
11761 SS.clear();
11762 }
John McCall337ec3d2010-10-12 23:13:28 +000011763
11764 // - There's a scope specifier that does not match any template
11765 // parameter lists, in which case we use some arbitrary context,
11766 // create a method or method template, and wait for instantiation.
11767 // - There's a scope specifier that does match some template
11768 // parameter lists, which we don't handle right now.
11769 } else {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011770 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000011771 // C++ [class.friend]p6:
11772 // A function can be defined in a friend declaration of a class if and
11773 // only if the class is a non-local class (9.8), the function name is
11774 // unqualified, and the function has namespace scope.
11775 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
11776 << SS.getScopeRep();
11777 }
11778
John McCall337ec3d2010-10-12 23:13:28 +000011779 DC = CurContext;
11780 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +000011781 }
Douglas Gregor883af832011-10-10 01:11:59 +000011782
John McCall29ae6e52010-10-13 05:45:15 +000011783 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +000011784 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +000011785 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
11786 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
11787 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +000011788 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +000011789 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
11790 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +000011791 return 0;
John McCall67d1a672009-08-06 02:15:43 +000011792 }
John McCall67d1a672009-08-06 02:15:43 +000011793 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011794
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000011795 // FIXME: This is an egregious hack to cope with cases where the scope stack
11796 // does not contain the declaration context, i.e., in an out-of-line
11797 // definition of a class.
11798 Scope FakeDCScope(S, Scope::DeclScope, Diags);
11799 if (!DCScope) {
11800 FakeDCScope.setEntity(DC);
11801 DCScope = &FakeDCScope;
11802 }
Richard Smith4e9686b2013-08-09 04:35:01 +000011803
Francois Pichetaf0f4d02011-08-14 03:52:19 +000011804 bool AddToScope = true;
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011805 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000011806 TemplateParams, AddToScope);
John McCalld226f652010-08-21 09:40:31 +000011807 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +000011808
Douglas Gregor182ddf02009-09-28 00:08:27 +000011809 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +000011810
Richard Smith4e9686b2013-08-09 04:35:01 +000011811 // If we performed typo correction, we might have added a scope specifier
11812 // and changed the decl context.
11813 DC = ND->getDeclContext();
11814
John McCallab88d972009-08-31 22:39:49 +000011815 // Add the function declaration to the appropriate lookup tables,
11816 // adjusting the redeclarations list as necessary. We don't
11817 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +000011818 //
John McCallab88d972009-08-31 22:39:49 +000011819 // Also update the scope-based lookup if the target context's
11820 // lookup context is in lexical scope.
11821 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000011822 DC = DC->getRedeclContext();
Richard Smith1b7f9cb2012-03-13 03:12:56 +000011823 DC->makeDeclVisibleInContext(ND);
John McCallab88d972009-08-31 22:39:49 +000011824 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +000011825 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +000011826 }
John McCall02cace72009-08-28 07:59:38 +000011827
11828 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +000011829 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +000011830 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +000011831 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +000011832 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +000011833
John McCall1f2e1a92012-08-10 03:15:35 +000011834 if (ND->isInvalidDecl()) {
John McCall337ec3d2010-10-12 23:13:28 +000011835 FrD->setInvalidDecl();
John McCall1f2e1a92012-08-10 03:15:35 +000011836 } else {
11837 if (DC->isRecord()) CheckFriendAccess(ND);
11838
John McCall6102ca12010-10-16 06:59:13 +000011839 FunctionDecl *FD;
11840 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
11841 FD = FTD->getTemplatedDecl();
11842 else
11843 FD = cast<FunctionDecl>(ND);
11844
David Majnemerf6a144f2013-06-25 23:09:30 +000011845 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
11846 // default argument expression, that declaration shall be a definition
11847 // and shall be the only declaration of the function or function
11848 // template in the translation unit.
11849 if (functionDeclHasDefaultArgument(FD)) {
11850 if (FunctionDecl *OldFD = FD->getPreviousDecl()) {
11851 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
11852 Diag(OldFD->getLocation(), diag::note_previous_declaration);
11853 } else if (!D.isFunctionDefinition())
11854 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
11855 }
11856
John McCall6102ca12010-10-16 06:59:13 +000011857 // Mark templated-scope function declarations as unsupported.
11858 if (FD->getNumTemplateParameterLists())
11859 FrD->setUnsupportedFriend(true);
11860 }
John McCall337ec3d2010-10-12 23:13:28 +000011861
John McCalld226f652010-08-21 09:40:31 +000011862 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +000011863}
11864
John McCalld226f652010-08-21 09:40:31 +000011865void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
11866 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +000011867
Aaron Ballmanafb7ce32013-01-16 23:39:10 +000011868 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
Sebastian Redl50de12f2009-03-24 22:27:57 +000011869 if (!Fn) {
11870 Diag(DelLoc, diag::err_deleted_non_function);
11871 return;
11872 }
Richard Smith0ab5b4c2013-04-02 19:38:47 +000011873
Douglas Gregoref96ee02012-01-14 16:38:05 +000011874 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
David Blaikied9cf8262012-06-25 21:55:30 +000011875 // Don't consider the implicit declaration we generate for explicit
11876 // specializations. FIXME: Do not generate these implicit declarations.
David Blaikie619ee6a2012-06-29 18:00:25 +000011877 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization
11878 || Prev->getPreviousDecl()) && !Prev->isDefined()) {
David Blaikied9cf8262012-06-25 21:55:30 +000011879 Diag(DelLoc, diag::err_deleted_decl_not_first);
11880 Diag(Prev->getLocation(), diag::note_previous_declaration);
11881 }
Sebastian Redl50de12f2009-03-24 22:27:57 +000011882 // If the declaration wasn't the first, we delete the function anyway for
11883 // recovery.
Richard Smith0ab5b4c2013-04-02 19:38:47 +000011884 Fn = Fn->getCanonicalDecl();
Sebastian Redl50de12f2009-03-24 22:27:57 +000011885 }
Richard Smith0ab5b4c2013-04-02 19:38:47 +000011886
11887 if (Fn->isDeleted())
11888 return;
11889
11890 // See if we're deleting a function which is already known to override a
11891 // non-deleted virtual function.
11892 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
11893 bool IssuedDiagnostic = false;
11894 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
11895 E = MD->end_overridden_methods();
11896 I != E; ++I) {
11897 if (!(*MD->begin_overridden_methods())->isDeleted()) {
11898 if (!IssuedDiagnostic) {
11899 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
11900 IssuedDiagnostic = true;
11901 }
11902 Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
11903 }
11904 }
11905 }
11906
Sean Hunt10620eb2011-05-06 20:44:56 +000011907 Fn->setDeletedAsWritten();
Sebastian Redl50de12f2009-03-24 22:27:57 +000011908}
Sebastian Redl13e88542009-04-27 21:33:24 +000011909
Sean Hunte4246a62011-05-12 06:15:49 +000011910void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
Aaron Ballmanafb7ce32013-01-16 23:39:10 +000011911 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
Sean Hunte4246a62011-05-12 06:15:49 +000011912
11913 if (MD) {
Sean Hunteb88ae52011-05-23 21:07:59 +000011914 if (MD->getParent()->isDependentType()) {
11915 MD->setDefaulted();
11916 MD->setExplicitlyDefaulted();
11917 return;
11918 }
11919
Sean Hunte4246a62011-05-12 06:15:49 +000011920 CXXSpecialMember Member = getSpecialMember(MD);
11921 if (Member == CXXInvalid) {
Eli Friedmanfcb5a252013-07-11 23:55:07 +000011922 if (!MD->isInvalidDecl())
11923 Diag(DefaultLoc, diag::err_default_special_members);
Sean Hunte4246a62011-05-12 06:15:49 +000011924 return;
11925 }
11926
11927 MD->setDefaulted();
11928 MD->setExplicitlyDefaulted();
11929
Sean Huntcd10dec2011-05-23 23:14:04 +000011930 // If this definition appears within the record, do the checking when
11931 // the record is complete.
11932 const FunctionDecl *Primary = MD;
Richard Smitha8eaf002012-08-23 06:16:52 +000011933 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
Sean Huntcd10dec2011-05-23 23:14:04 +000011934 // Find the uninstantiated declaration that actually had the '= default'
11935 // on it.
Richard Smitha8eaf002012-08-23 06:16:52 +000011936 Pattern->isDefined(Primary);
Sean Huntcd10dec2011-05-23 23:14:04 +000011937
Richard Smith12fef492013-03-27 00:22:47 +000011938 // If the method was defaulted on its first declaration, we will have
11939 // already performed the checking in CheckCompletedCXXClass. Such a
11940 // declaration doesn't trigger an implicit definition.
Sean Huntcd10dec2011-05-23 23:14:04 +000011941 if (Primary == Primary->getCanonicalDecl())
Sean Hunte4246a62011-05-12 06:15:49 +000011942 return;
11943
Richard Smithb9d0b762012-07-27 04:22:15 +000011944 CheckExplicitlyDefaultedSpecialMember(MD);
11945
Richard Smith1d28caf2012-12-11 01:14:52 +000011946 // The exception specification is needed because we are defining the
11947 // function.
11948 ResolveExceptionSpec(DefaultLoc,
11949 MD->getType()->castAs<FunctionProtoType>());
11950
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000011951 if (MD->isInvalidDecl())
11952 return;
11953
Sean Hunte4246a62011-05-12 06:15:49 +000011954 switch (Member) {
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000011955 case CXXDefaultConstructor:
11956 DefineImplicitDefaultConstructor(DefaultLoc,
11957 cast<CXXConstructorDecl>(MD));
Sean Hunt49634cf2011-05-13 06:10:58 +000011958 break;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000011959 case CXXCopyConstructor:
11960 DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
Sean Hunte4246a62011-05-12 06:15:49 +000011961 break;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000011962 case CXXCopyAssignment:
11963 DefineImplicitCopyAssignment(DefaultLoc, MD);
Sean Hunt2b188082011-05-14 05:23:28 +000011964 break;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000011965 case CXXDestructor:
11966 DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
Sean Huntcb45a0f2011-05-12 22:46:25 +000011967 break;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000011968 case CXXMoveConstructor:
11969 DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
Sean Hunt82713172011-05-25 23:16:36 +000011970 break;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000011971 case CXXMoveAssignment:
11972 DefineImplicitMoveAssignment(DefaultLoc, MD);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011973 break;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011974 case CXXInvalid:
David Blaikieb219cfc2011-09-23 05:06:16 +000011975 llvm_unreachable("Invalid special member.");
Sean Hunte4246a62011-05-12 06:15:49 +000011976 }
11977 } else {
11978 Diag(DefaultLoc, diag::err_default_special_members);
11979 }
11980}
11981
Sebastian Redl13e88542009-04-27 21:33:24 +000011982static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +000011983 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +000011984 Stmt *SubStmt = *CI;
11985 if (!SubStmt)
11986 continue;
11987 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar96a00142012-03-09 18:35:03 +000011988 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl13e88542009-04-27 21:33:24 +000011989 diag::err_return_in_constructor_handler);
11990 if (!isa<Expr>(SubStmt))
11991 SearchForReturnInStmt(Self, SubStmt);
11992 }
11993}
11994
11995void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
11996 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
11997 CXXCatchStmt *Handler = TryBlock->getHandler(I);
11998 SearchForReturnInStmt(*this, Handler);
11999 }
12000}
Anders Carlssond7ba27d2009-05-14 01:09:04 +000012001
David Blaikie299adab2013-01-18 23:03:15 +000012002bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
Aaron Ballmanfff32482012-12-09 17:45:41 +000012003 const CXXMethodDecl *Old) {
12004 const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
12005 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
12006
12007 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
12008
12009 // If the calling conventions match, everything is fine
12010 if (NewCC == OldCC)
12011 return false;
12012
Reid Kleckneref072032013-08-27 23:08:25 +000012013 Diag(New->getLocation(),
12014 diag::err_conflicting_overriding_cc_attributes)
12015 << New->getDeclName() << New->getType() << Old->getType();
12016 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12017 return true;
Aaron Ballmanfff32482012-12-09 17:45:41 +000012018}
12019
Mike Stump1eb44332009-09-09 15:08:12 +000012020bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +000012021 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +000012022 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
12023 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +000012024
Chandler Carruth73857792010-02-15 11:53:20 +000012025 if (Context.hasSameType(NewTy, OldTy) ||
12026 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +000012027 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000012028
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012029 // Check if the return types are covariant
12030 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +000012031
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012032 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000012033 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
12034 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012035 NewClassTy = NewPT->getPointeeType();
12036 OldClassTy = OldPT->getPointeeType();
12037 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000012038 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
12039 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
12040 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
12041 NewClassTy = NewRT->getPointeeType();
12042 OldClassTy = OldRT->getPointeeType();
12043 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012044 }
12045 }
Mike Stump1eb44332009-09-09 15:08:12 +000012046
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012047 // The return types aren't either both pointers or references to a class type.
12048 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +000012049 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012050 diag::err_different_return_type_for_overriding_virtual_function)
12051 << New->getDeclName() << NewTy << OldTy;
12052 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +000012053
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012054 return true;
12055 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +000012056
Anders Carlssonbe2e2052009-12-31 18:34:24 +000012057 // C++ [class.virtual]p6:
12058 // If the return type of D::f differs from the return type of B::f, the
12059 // class type in the return type of D::f shall be complete at the point of
12060 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +000012061 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
12062 if (!RT->isBeingDefined() &&
12063 RequireCompleteType(New->getLocation(), NewClassTy,
Douglas Gregord10099e2012-05-04 16:32:21 +000012064 diag::err_covariant_return_incomplete,
12065 New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +000012066 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +000012067 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +000012068
Douglas Gregora4923eb2009-11-16 21:35:15 +000012069 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012070 // Check if the new class derives from the old class.
12071 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
12072 Diag(New->getLocation(),
12073 diag::err_covariant_return_not_derived)
12074 << New->getDeclName() << NewTy << OldTy;
12075 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12076 return true;
12077 }
Mike Stump1eb44332009-09-09 15:08:12 +000012078
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012079 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +000012080 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +000012081 diag::err_covariant_return_inaccessible_base,
12082 diag::err_covariant_return_ambiguous_derived_to_base_conv,
12083 // FIXME: Should this point to the return type?
12084 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCalleee1d542011-02-14 07:13:47 +000012085 // FIXME: this note won't trigger for delayed access control
12086 // diagnostics, and it's impossible to get an undelayed error
12087 // here from access control during the original parse because
12088 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012089 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12090 return true;
12091 }
12092 }
Mike Stump1eb44332009-09-09 15:08:12 +000012093
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012094 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000012095 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012096 Diag(New->getLocation(),
12097 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +000012098 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012099 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12100 return true;
12101 };
Mike Stump1eb44332009-09-09 15:08:12 +000012102
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012103
12104 // The new class type must have the same or less qualifiers as the old type.
12105 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
12106 Diag(New->getLocation(),
12107 diag::err_covariant_return_type_class_type_more_qualified)
12108 << New->getDeclName() << NewTy << OldTy;
12109 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12110 return true;
12111 };
Mike Stump1eb44332009-09-09 15:08:12 +000012112
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012113 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +000012114}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000012115
Douglas Gregor4ba31362009-12-01 17:24:26 +000012116/// \brief Mark the given method pure.
12117///
12118/// \param Method the method to be marked pure.
12119///
12120/// \param InitRange the source range that covers the "0" initializer.
12121bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnara796aa442011-03-12 11:17:06 +000012122 SourceLocation EndLoc = InitRange.getEnd();
12123 if (EndLoc.isValid())
12124 Method->setRangeEnd(EndLoc);
12125
Douglas Gregor4ba31362009-12-01 17:24:26 +000012126 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
12127 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +000012128 return false;
Abramo Bagnara796aa442011-03-12 11:17:06 +000012129 }
Douglas Gregor4ba31362009-12-01 17:24:26 +000012130
12131 if (!Method->isInvalidDecl())
12132 Diag(Method->getLocation(), diag::err_non_virtual_pure)
12133 << Method->getDeclName() << InitRange;
12134 return true;
12135}
12136
Douglas Gregor552e2992012-02-21 02:22:07 +000012137/// \brief Determine whether the given declaration is a static data member.
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012138static bool isStaticDataMember(const Decl *D) {
12139 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
12140 return Var->isStaticDataMember();
12141
12142 return false;
Douglas Gregor552e2992012-02-21 02:22:07 +000012143}
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012144
John McCall731ad842009-12-19 09:28:58 +000012145/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
12146/// an initializer for the out-of-line declaration 'Dcl'. The scope
12147/// is a fresh scope pushed for just this purpose.
12148///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000012149/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
12150/// static data member of class X, names should be looked up in the scope of
12151/// class X.
John McCalld226f652010-08-21 09:40:31 +000012152void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000012153 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000012154 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000012155
John McCall731ad842009-12-19 09:28:58 +000012156 // We should only get called for declarations with scope specifiers, like:
12157 // int foo::bar;
12158 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000012159 EnterDeclaratorContext(S, D->getDeclContext());
Douglas Gregor552e2992012-02-21 02:22:07 +000012160
12161 // If we are parsing the initializer for a static data member, push a
12162 // new expression evaluation context that is associated with this static
12163 // data member.
12164 if (isStaticDataMember(D))
12165 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000012166}
12167
12168/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +000012169/// initializer for the out-of-line declaration 'D'.
12170void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000012171 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000012172 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000012173
Douglas Gregor552e2992012-02-21 02:22:07 +000012174 if (isStaticDataMember(D))
12175 PopExpressionEvaluationContext();
12176
John McCall731ad842009-12-19 09:28:58 +000012177 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000012178 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000012179}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000012180
12181/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
12182/// C++ if/switch/while/for statement.
12183/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +000012184DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000012185 // C++ 6.4p2:
12186 // The declarator shall not specify a function or an array.
12187 // The type-specifier-seq shall not contain typedef and shall not declare a
12188 // new class or enumeration.
12189 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
12190 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000012191
12192 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor9a30c992011-07-05 16:13:20 +000012193 if (!Dcl)
12194 return true;
12195
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000012196 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
12197 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000012198 << D.getSourceRange();
Douglas Gregor9a30c992011-07-05 16:13:20 +000012199 return true;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000012200 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000012201
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000012202 return Dcl;
12203}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000012204
Douglas Gregordfe65432011-07-28 19:11:31 +000012205void Sema::LoadExternalVTableUses() {
12206 if (!ExternalSource)
12207 return;
12208
12209 SmallVector<ExternalVTableUse, 4> VTables;
12210 ExternalSource->ReadUsedVTables(VTables);
12211 SmallVector<VTableUse, 4> NewUses;
12212 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
12213 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
12214 = VTablesUsed.find(VTables[I].Record);
12215 // Even if a definition wasn't required before, it may be required now.
12216 if (Pos != VTablesUsed.end()) {
12217 if (!Pos->second && VTables[I].DefinitionRequired)
12218 Pos->second = true;
12219 continue;
12220 }
12221
12222 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
12223 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
12224 }
12225
12226 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
12227}
12228
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012229void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
12230 bool DefinitionRequired) {
12231 // Ignore any vtable uses in unevaluated operands or for classes that do
12232 // not have a vtable.
12233 if (!Class->isDynamicClass() || Class->isDependentContext() ||
John McCallaeeacf72013-05-03 00:10:13 +000012234 CurContext->isDependentContext() || isUnevaluatedContext())
Rafael Espindolabbf58bb2010-03-10 02:19:29 +000012235 return;
12236
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012237 // Try to insert this class into the map.
Douglas Gregordfe65432011-07-28 19:11:31 +000012238 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012239 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
12240 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
12241 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
12242 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +000012243 // If we already had an entry, check to see if we are promoting this vtable
12244 // to required a definition. If so, we need to reappend to the VTableUses
12245 // list, since we may have already processed the first entry.
12246 if (DefinitionRequired && !Pos.first->second) {
12247 Pos.first->second = true;
12248 } else {
12249 // Otherwise, we can early exit.
12250 return;
12251 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012252 }
12253
12254 // Local classes need to have their virtual members marked
12255 // immediately. For all other classes, we mark their virtual members
12256 // at the end of the translation unit.
12257 if (Class->isLocalClass())
12258 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +000012259 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012260 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +000012261}
12262
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012263bool Sema::DefineUsedVTables() {
Douglas Gregordfe65432011-07-28 19:11:31 +000012264 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012265 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +000012266 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +000012267
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012268 // Note: The VTableUses vector could grow as a result of marking
12269 // the members of a class as "used", so we check the size each
Richard Smithb9d0b762012-07-27 04:22:15 +000012270 // time through the loop and prefer indices (which are stable) to
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012271 // iterators (which are not).
Douglas Gregor78844032011-04-22 22:25:37 +000012272 bool DefinedAnything = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012273 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +000012274 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012275 if (!Class)
12276 continue;
12277
12278 SourceLocation Loc = VTableUses[I].second;
12279
Richard Smithb9d0b762012-07-27 04:22:15 +000012280 bool DefineVTable = true;
12281
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012282 // If this class has a key function, but that key function is
12283 // defined in another translation unit, we don't need to emit the
12284 // vtable even though we're using it.
John McCalld5617ee2013-01-25 22:31:03 +000012285 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +000012286 if (KeyFunction && !KeyFunction->hasBody()) {
Rafael Espindolafc218132013-08-26 23:23:21 +000012287 // The key function is in another translation unit.
12288 DefineVTable = false;
12289 TemplateSpecializationKind TSK =
12290 KeyFunction->getTemplateSpecializationKind();
12291 assert(TSK != TSK_ExplicitInstantiationDefinition &&
12292 TSK != TSK_ImplicitInstantiation &&
12293 "Instantiations don't have key functions");
12294 (void)TSK;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012295 } else if (!KeyFunction) {
12296 // If we have a class with no key function that is the subject
12297 // of an explicit instantiation declaration, suppress the
12298 // vtable; it will live with the explicit instantiation
12299 // definition.
12300 bool IsExplicitInstantiationDeclaration
12301 = Class->getTemplateSpecializationKind()
12302 == TSK_ExplicitInstantiationDeclaration;
12303 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
12304 REnd = Class->redecls_end();
12305 R != REnd; ++R) {
12306 TemplateSpecializationKind TSK
12307 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
12308 if (TSK == TSK_ExplicitInstantiationDeclaration)
12309 IsExplicitInstantiationDeclaration = true;
12310 else if (TSK == TSK_ExplicitInstantiationDefinition) {
12311 IsExplicitInstantiationDeclaration = false;
12312 break;
12313 }
12314 }
12315
12316 if (IsExplicitInstantiationDeclaration)
Richard Smithb9d0b762012-07-27 04:22:15 +000012317 DefineVTable = false;
12318 }
12319
12320 // The exception specifications for all virtual members may be needed even
12321 // if we are not providing an authoritative form of the vtable in this TU.
12322 // We may choose to emit it available_externally anyway.
12323 if (!DefineVTable) {
12324 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
12325 continue;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012326 }
12327
12328 // Mark all of the virtual members of this class as referenced, so
12329 // that we can build a vtable. Then, tell the AST consumer that a
12330 // vtable for this class is required.
Douglas Gregor78844032011-04-22 22:25:37 +000012331 DefinedAnything = true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012332 MarkVirtualMembersReferenced(Loc, Class);
12333 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
12334 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
12335
12336 // Optionally warn if we're emitting a weak vtable.
Rafael Espindola181e3ec2013-05-13 00:12:11 +000012337 if (Class->isExternallyVisible() &&
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012338 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Douglas Gregora120d012011-09-23 19:04:03 +000012339 const FunctionDecl *KeyFunctionDef = 0;
12340 if (!KeyFunction ||
12341 (KeyFunction->hasBody(KeyFunctionDef) &&
12342 KeyFunctionDef->isInlined()))
David Blaikie44d95b52011-12-09 18:32:50 +000012343 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
12344 TSK_ExplicitInstantiationDefinition
12345 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
12346 << Class;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012347 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000012348 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012349 VTableUses.clear();
12350
Douglas Gregor78844032011-04-22 22:25:37 +000012351 return DefinedAnything;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000012352}
Anders Carlssond6a637f2009-12-07 08:24:59 +000012353
Richard Smithb9d0b762012-07-27 04:22:15 +000012354void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
12355 const CXXRecordDecl *RD) {
12356 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
12357 E = RD->method_end(); I != E; ++I)
12358 if ((*I)->isVirtual() && !(*I)->isPure())
12359 ResolveExceptionSpec(Loc, (*I)->getType()->castAs<FunctionProtoType>());
12360}
12361
Rafael Espindola3e1ae932010-03-26 00:36:59 +000012362void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
12363 const CXXRecordDecl *RD) {
Richard Smithff817f72012-07-07 06:59:51 +000012364 // Mark all functions which will appear in RD's vtable as used.
12365 CXXFinalOverriderMap FinalOverriders;
12366 RD->getFinalOverriders(FinalOverriders);
12367 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
12368 E = FinalOverriders.end();
12369 I != E; ++I) {
12370 for (OverridingMethods::const_iterator OI = I->second.begin(),
12371 OE = I->second.end();
12372 OI != OE; ++OI) {
12373 assert(OI->second.size() > 0 && "no final overrider");
12374 CXXMethodDecl *Overrider = OI->second.front().Method;
Anders Carlssond6a637f2009-12-07 08:24:59 +000012375
Richard Smithff817f72012-07-07 06:59:51 +000012376 // C++ [basic.def.odr]p2:
12377 // [...] A virtual member function is used if it is not pure. [...]
12378 if (!Overrider->isPure())
12379 MarkFunctionReferenced(Loc, Overrider);
12380 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000012381 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +000012382
12383 // Only classes that have virtual bases need a VTT.
12384 if (RD->getNumVBases() == 0)
12385 return;
12386
12387 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
12388 e = RD->bases_end(); i != e; ++i) {
12389 const CXXRecordDecl *Base =
12390 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +000012391 if (Base->getNumVBases() == 0)
12392 continue;
12393 MarkVirtualMembersReferenced(Loc, Base);
12394 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000012395}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012396
12397/// SetIvarInitializers - This routine builds initialization ASTs for the
12398/// Objective-C implementation whose ivars need be initialized.
12399void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikie4e4d0842012-03-11 07:00:24 +000012400 if (!getLangOpts().CPlusPlus)
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012401 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +000012402 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +000012403 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012404 CollectIvarsToConstructOrDestruct(OID, ivars);
12405 if (ivars.empty())
12406 return;
Chris Lattner5f9e2722011-07-23 10:55:15 +000012407 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012408 for (unsigned i = 0; i < ivars.size(); i++) {
12409 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000012410 if (Field->isInvalidDecl())
12411 continue;
12412
Sean Huntcbb67482011-01-08 20:30:50 +000012413 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012414 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
12415 InitializationKind InitKind =
12416 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
Dmitri Gribenko62ed8892013-05-05 20:40:26 +000012417
12418 InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
12419 ExprResult MemberInit =
12420 InitSeq.Perform(*this, InitEntity, InitKind, None);
Douglas Gregor53c374f2010-12-07 00:41:46 +000012421 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012422 // Note, MemberInit could actually come back empty if no initialization
12423 // is required (e.g., because it would call a trivial default constructor)
12424 if (!MemberInit.get() || MemberInit.isInvalid())
12425 continue;
John McCallb4eb64d2010-10-08 02:01:28 +000012426
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012427 Member =
Sean Huntcbb67482011-01-08 20:30:50 +000012428 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
12429 SourceLocation(),
12430 MemberInit.takeAs<Expr>(),
12431 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012432 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000012433
12434 // Be sure that the destructor is accessible and is marked as referenced.
12435 if (const RecordType *RecordTy
12436 = Context.getBaseElementType(Field->getType())
12437 ->getAs<RecordType>()) {
12438 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +000012439 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000012440 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000012441 CheckDestructorAccess(Field->getLocation(), Destructor,
12442 PDiag(diag::err_access_dtor_ivar)
12443 << Context.getBaseElementType(Field->getType()));
12444 }
12445 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012446 }
12447 ObjCImplementation->setIvarInitializers(Context,
12448 AllToInit.data(), AllToInit.size());
12449 }
12450}
Sean Huntfe57eef2011-05-04 05:57:24 +000012451
Sean Huntebcbe1d2011-05-04 23:29:54 +000012452static
12453void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
12454 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
12455 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
12456 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
12457 Sema &S) {
Sean Huntebcbe1d2011-05-04 23:29:54 +000012458 if (Ctor->isInvalidDecl())
12459 return;
12460
Richard Smitha8eaf002012-08-23 06:16:52 +000012461 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
12462
12463 // Target may not be determinable yet, for instance if this is a dependent
12464 // call in an uninstantiated template.
12465 if (Target) {
12466 const FunctionDecl *FNTarget = 0;
12467 (void)Target->hasBody(FNTarget);
12468 Target = const_cast<CXXConstructorDecl*>(
12469 cast_or_null<CXXConstructorDecl>(FNTarget));
12470 }
Sean Huntebcbe1d2011-05-04 23:29:54 +000012471
12472 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
12473 // Avoid dereferencing a null pointer here.
12474 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
12475
12476 if (!Current.insert(Canonical))
12477 return;
12478
12479 // We know that beyond here, we aren't chaining into a cycle.
12480 if (!Target || !Target->isDelegatingConstructor() ||
12481 Target->isInvalidDecl() || Valid.count(TCanonical)) {
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012482 Valid.insert(Current.begin(), Current.end());
Sean Huntebcbe1d2011-05-04 23:29:54 +000012483 Current.clear();
12484 // We've hit a cycle.
12485 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
12486 Current.count(TCanonical)) {
12487 // If we haven't diagnosed this cycle yet, do so now.
12488 if (!Invalid.count(TCanonical)) {
12489 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Sean Huntc1598702011-05-05 00:05:47 +000012490 diag::warn_delegating_ctor_cycle)
Sean Huntebcbe1d2011-05-04 23:29:54 +000012491 << Ctor;
12492
Richard Smitha8eaf002012-08-23 06:16:52 +000012493 // Don't add a note for a function delegating directly to itself.
Sean Huntebcbe1d2011-05-04 23:29:54 +000012494 if (TCanonical != Canonical)
12495 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
12496
12497 CXXConstructorDecl *C = Target;
12498 while (C->getCanonicalDecl() != Canonical) {
Richard Smitha8eaf002012-08-23 06:16:52 +000012499 const FunctionDecl *FNTarget = 0;
Sean Huntebcbe1d2011-05-04 23:29:54 +000012500 (void)C->getTargetConstructor()->hasBody(FNTarget);
12501 assert(FNTarget && "Ctor cycle through bodiless function");
12502
Richard Smitha8eaf002012-08-23 06:16:52 +000012503 C = const_cast<CXXConstructorDecl*>(
12504 cast<CXXConstructorDecl>(FNTarget));
Sean Huntebcbe1d2011-05-04 23:29:54 +000012505 S.Diag(C->getLocation(), diag::note_which_delegates_to);
12506 }
12507 }
12508
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012509 Invalid.insert(Current.begin(), Current.end());
Sean Huntebcbe1d2011-05-04 23:29:54 +000012510 Current.clear();
12511 } else {
12512 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
12513 }
12514}
12515
12516
Sean Huntfe57eef2011-05-04 05:57:24 +000012517void Sema::CheckDelegatingCtorCycles() {
12518 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
12519
Douglas Gregor0129b562011-07-27 21:57:17 +000012520 for (DelegatingCtorDeclsType::iterator
12521 I = DelegatingCtorDecls.begin(ExternalSource),
Sean Huntebcbe1d2011-05-04 23:29:54 +000012522 E = DelegatingCtorDecls.end();
Richard Smitha8eaf002012-08-23 06:16:52 +000012523 I != E; ++I)
12524 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Sean Huntebcbe1d2011-05-04 23:29:54 +000012525
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012526 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
12527 CE = Invalid.end();
12528 CI != CE; ++CI)
Sean Huntebcbe1d2011-05-04 23:29:54 +000012529 (*CI)->setInvalidDecl();
Sean Huntfe57eef2011-05-04 05:57:24 +000012530}
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000012531
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012532namespace {
12533 /// \brief AST visitor that finds references to the 'this' expression.
12534 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
12535 Sema &S;
12536
12537 public:
12538 explicit FindCXXThisExpr(Sema &S) : S(S) { }
12539
12540 bool VisitCXXThisExpr(CXXThisExpr *E) {
12541 S.Diag(E->getLocation(), diag::err_this_static_member_func)
12542 << E->isImplicit();
12543 return false;
12544 }
12545 };
12546}
12547
12548bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
12549 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12550 if (!TSInfo)
12551 return false;
12552
12553 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +000012554 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012555 if (!ProtoTL)
12556 return false;
12557
12558 // C++11 [expr.prim.general]p3:
12559 // [The expression this] shall not appear before the optional
12560 // cv-qualifier-seq and it shall not appear within the declaration of a
12561 // static member function (although its type and value category are defined
12562 // within a static member function as they are within a non-static member
12563 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumic86d1fd2012-04-21 09:40:04 +000012564 // until the complete declarator is known. - end note ]
David Blaikie39e6ab42013-02-18 22:06:02 +000012565 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012566 FindCXXThisExpr Finder(*this);
12567
12568 // If the return type came after the cv-qualifier-seq, check it now.
12569 if (Proto->hasTrailingReturn() &&
David Blaikie39e6ab42013-02-18 22:06:02 +000012570 !Finder.TraverseTypeLoc(ProtoTL.getResultLoc()))
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012571 return true;
12572
12573 // Check the exception specification.
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012574 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
12575 return true;
12576
12577 return checkThisInStaticMemberFunctionAttributes(Method);
12578}
12579
12580bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
12581 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12582 if (!TSInfo)
12583 return false;
12584
12585 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +000012586 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012587 if (!ProtoTL)
12588 return false;
12589
David Blaikie39e6ab42013-02-18 22:06:02 +000012590 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012591 FindCXXThisExpr Finder(*this);
12592
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012593 switch (Proto->getExceptionSpecType()) {
Richard Smithe6975e92012-04-17 00:58:00 +000012594 case EST_Uninstantiated:
Richard Smithb9d0b762012-07-27 04:22:15 +000012595 case EST_Unevaluated:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012596 case EST_BasicNoexcept:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012597 case EST_DynamicNone:
12598 case EST_MSAny:
12599 case EST_None:
12600 break;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012601
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012602 case EST_ComputedNoexcept:
12603 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
12604 return true;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012605
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012606 case EST_Dynamic:
12607 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012608 EEnd = Proto->exception_end();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012609 E != EEnd; ++E) {
12610 if (!Finder.TraverseType(*E))
12611 return true;
12612 }
12613 break;
12614 }
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012615
12616 return false;
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012617}
12618
12619bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
12620 FindCXXThisExpr Finder(*this);
12621
12622 // Check attributes.
12623 for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end();
12624 A != AEnd; ++A) {
12625 // FIXME: This should be emitted by tblgen.
12626 Expr *Arg = 0;
12627 ArrayRef<Expr *> Args;
12628 if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A))
12629 Arg = G->getArg();
12630 else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A))
12631 Arg = G->getArg();
12632 else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A))
12633 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
12634 else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A))
12635 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
12636 else if (ExclusiveLockFunctionAttr *ELF
12637 = dyn_cast<ExclusiveLockFunctionAttr>(*A))
12638 Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size());
12639 else if (SharedLockFunctionAttr *SLF
12640 = dyn_cast<SharedLockFunctionAttr>(*A))
12641 Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size());
12642 else if (ExclusiveTrylockFunctionAttr *ETLF
12643 = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) {
12644 Arg = ETLF->getSuccessValue();
12645 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
12646 } else if (SharedTrylockFunctionAttr *STLF
12647 = dyn_cast<SharedTrylockFunctionAttr>(*A)) {
12648 Arg = STLF->getSuccessValue();
12649 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
12650 } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A))
12651 Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size());
12652 else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A))
12653 Arg = LR->getArg();
12654 else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A))
12655 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
12656 else if (ExclusiveLocksRequiredAttr *ELR
12657 = dyn_cast<ExclusiveLocksRequiredAttr>(*A))
12658 Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size());
12659 else if (SharedLocksRequiredAttr *SLR
12660 = dyn_cast<SharedLocksRequiredAttr>(*A))
12661 Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size());
12662
12663 if (Arg && !Finder.TraverseStmt(Arg))
12664 return true;
12665
12666 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
12667 if (!Finder.TraverseStmt(Args[I]))
12668 return true;
12669 }
12670 }
12671
12672 return false;
12673}
12674
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012675void
12676Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
12677 ArrayRef<ParsedType> DynamicExceptions,
12678 ArrayRef<SourceRange> DynamicExceptionRanges,
12679 Expr *NoexceptExpr,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000012680 SmallVectorImpl<QualType> &Exceptions,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012681 FunctionProtoType::ExtProtoInfo &EPI) {
12682 Exceptions.clear();
12683 EPI.ExceptionSpecType = EST;
12684 if (EST == EST_Dynamic) {
12685 Exceptions.reserve(DynamicExceptions.size());
12686 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
12687 // FIXME: Preserve type source info.
12688 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
12689
12690 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
12691 collectUnexpandedParameterPacks(ET, Unexpanded);
12692 if (!Unexpanded.empty()) {
12693 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
12694 UPPC_ExceptionType,
12695 Unexpanded);
12696 continue;
12697 }
12698
12699 // Check that the type is valid for an exception spec, and
12700 // drop it if not.
12701 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
12702 Exceptions.push_back(ET);
12703 }
12704 EPI.NumExceptions = Exceptions.size();
12705 EPI.Exceptions = Exceptions.data();
12706 return;
12707 }
12708
12709 if (EST == EST_ComputedNoexcept) {
12710 // If an error occurred, there's no expression here.
12711 if (NoexceptExpr) {
12712 assert((NoexceptExpr->isTypeDependent() ||
12713 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
12714 Context.BoolTy) &&
12715 "Parser should have made sure that the expression is boolean");
12716 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
12717 EPI.ExceptionSpecType = EST_BasicNoexcept;
12718 return;
12719 }
12720
12721 if (!NoexceptExpr->isValueDependent())
12722 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0,
Douglas Gregorab41fe92012-05-04 22:38:52 +000012723 diag::err_noexcept_needs_constant_expression,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012724 /*AllowFold*/ false).take();
12725 EPI.NoexceptExpr = NoexceptExpr;
12726 }
12727 return;
12728 }
12729}
12730
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000012731/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
12732Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
12733 // Implicitly declared functions (e.g. copy constructors) are
12734 // __host__ __device__
12735 if (D->isImplicit())
12736 return CFT_HostDevice;
12737
12738 if (D->hasAttr<CUDAGlobalAttr>())
12739 return CFT_Global;
12740
12741 if (D->hasAttr<CUDADeviceAttr>()) {
12742 if (D->hasAttr<CUDAHostAttr>())
12743 return CFT_HostDevice;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012744 return CFT_Device;
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000012745 }
12746
12747 return CFT_Host;
12748}
12749
12750bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
12751 CUDAFunctionTarget CalleeTarget) {
12752 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
12753 // Callable from the device only."
12754 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
12755 return true;
12756
12757 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
12758 // Callable from the host only."
12759 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
12760 // Callable from the host only."
12761 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
12762 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
12763 return true;
12764
12765 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
12766 return true;
12767
12768 return false;
12769}
John McCall76da55d2013-04-16 07:28:30 +000012770
12771/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
12772///
12773MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
12774 SourceLocation DeclStart,
12775 Declarator &D, Expr *BitWidth,
12776 InClassInitStyle InitStyle,
12777 AccessSpecifier AS,
12778 AttributeList *MSPropertyAttr) {
12779 IdentifierInfo *II = D.getIdentifier();
12780 if (!II) {
12781 Diag(DeclStart, diag::err_anonymous_property);
12782 return NULL;
12783 }
12784 SourceLocation Loc = D.getIdentifierLoc();
12785
12786 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12787 QualType T = TInfo->getType();
12788 if (getLangOpts().CPlusPlus) {
12789 CheckExtraCXXDefaultArguments(D);
12790
12791 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
12792 UPPC_DataMemberType)) {
12793 D.setInvalidType();
12794 T = Context.IntTy;
12795 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
12796 }
12797 }
12798
12799 DiagnoseFunctionSpecifiers(D.getDeclSpec());
12800
12801 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
12802 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
12803 diag::err_invalid_thread)
12804 << DeclSpec::getSpecifierName(TSCS);
12805
12806 // Check to see if this name was declared as a member previously
12807 NamedDecl *PrevDecl = 0;
12808 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
12809 LookupName(Previous, S);
12810 switch (Previous.getResultKind()) {
12811 case LookupResult::Found:
12812 case LookupResult::FoundUnresolvedValue:
12813 PrevDecl = Previous.getAsSingle<NamedDecl>();
12814 break;
12815
12816 case LookupResult::FoundOverloaded:
12817 PrevDecl = Previous.getRepresentativeDecl();
12818 break;
12819
12820 case LookupResult::NotFound:
12821 case LookupResult::NotFoundInCurrentInstantiation:
12822 case LookupResult::Ambiguous:
12823 break;
12824 }
12825
12826 if (PrevDecl && PrevDecl->isTemplateParameter()) {
12827 // Maybe we will complain about the shadowed template parameter.
12828 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12829 // Just pretend that we didn't see the previous declaration.
12830 PrevDecl = 0;
12831 }
12832
12833 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
12834 PrevDecl = 0;
12835
12836 SourceLocation TSSL = D.getLocStart();
12837 MSPropertyDecl *NewPD;
12838 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
12839 NewPD = new (Context) MSPropertyDecl(Record, Loc,
12840 II, T, TInfo, TSSL,
12841 Data.GetterId, Data.SetterId);
12842 ProcessDeclAttributes(TUScope, NewPD, D);
12843 NewPD->setAccess(AS);
12844
12845 if (NewPD->isInvalidDecl())
12846 Record->setInvalidDecl();
12847
12848 if (D.getDeclSpec().isModulePrivateSpecified())
12849 NewPD->setModulePrivate();
12850
12851 if (NewPD->isInvalidDecl() && PrevDecl) {
12852 // Don't introduce NewFD into scope; there's already something
12853 // with the same name in the same scope.
12854 } else if (II) {
12855 PushOnScopeChains(NewPD, S);
12856 } else
12857 Record->addDecl(NewPD);
12858
12859 return NewPD;
12860}