blob: da1664319b2afdf569d9d9063ce56af99430e185 [file] [log] [blame]
Chris Lattner199abbc2008-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 McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Argyrios Kyrtzidis2f67f372008-08-09 00:58:37 +000015#include "clang/AST/ASTConsumer.h"
Douglas Gregor556877c2008-04-13 21:30:24 +000016#include "clang/AST/ASTContext.h"
Faisal Vali2b391ab2013-09-26 19:54:12 +000017#include "clang/AST/ASTLambda.h"
Sebastian Redlab238a72011-04-24 16:28:06 +000018#include "clang/AST/ASTMutationListener.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000019#include "clang/AST/CXXInheritance.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "clang/AST/CharUnits.h"
Anders Carlssonb5a27b42009-03-24 01:19:16 +000021#include "clang/AST/DeclVisitor.h"
Richard Trieu4fc85362012-06-14 23:11:34 +000022#include "clang/AST/EvaluatedExprVisitor.h"
Alexis Huntc5575cc2011-02-26 19:13:13 +000023#include "clang/AST/ExprCXX.h"
Douglas Gregorb139cd52010-05-01 20:49:11 +000024#include "clang/AST/RecordLayout.h"
Douglas Gregor3024f072012-04-16 07:05:22 +000025#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregorb139cd52010-05-01 20:49:11 +000026#include "clang/AST/StmtVisitor.h"
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +000027#include "clang/AST/TypeLoc.h"
Douglas Gregordff6a8e2008-10-22 21:13:31 +000028#include "clang/AST/TypeOrdering.h"
Anders Carlssond624e162009-08-26 23:45:07 +000029#include "clang/Basic/PartialDiagnostic.h"
Aaron Ballman02df2e02012-12-09 17:45:41 +000030#include "clang/Basic/TargetInfo.h"
Richard Smithf4198b72013-07-23 08:14:48 +000031#include "clang/Lex/LiteralSupport.h"
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +000032#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-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 Gregor55297ac2008-12-23 00:26:44 +000040#include "llvm/ADT/STLExtras.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000041#include "llvm/ADT/SmallString.h"
Douglas Gregor29a92472008-10-22 17:49:05 +000042#include <map>
Douglas Gregor36d1b142009-10-06 17:59:45 +000043#include <set>
Chris Lattner199abbc2008-04-08 05:04:30 +000044
45using namespace clang;
46
Chris Lattner58258242008-04-10 02:22:51 +000047//===----------------------------------------------------------------------===//
48// CheckDefaultArgumentVisitor
49//===----------------------------------------------------------------------===//
50
Chris Lattnerb0d38442008-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 Kramer337e3a52009-11-28 19:45:26 +000057 class CheckDefaultArgumentVisitor
Chris Lattner574dee62008-07-26 22:17:49 +000058 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattnerb0d38442008-04-12 23:52:44 +000059 Expr *DefaultArg;
60 Sema *S;
Chris Lattner58258242008-04-10 02:22:51 +000061
Chris Lattnerb0d38442008-04-12 23:52:44 +000062 public:
Mike Stump11289f42009-09-09 15:08:12 +000063 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattnerb0d38442008-04-12 23:52:44 +000064 : DefaultArg(defarg), S(s) {}
Chris Lattner58258242008-04-10 02:22:51 +000065
Chris Lattnerb0d38442008-04-12 23:52:44 +000066 bool VisitExpr(Expr *Node);
67 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor97a9c812008-11-04 14:32:21 +000068 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Douglas Gregorf0d49512012-02-10 23:30:22 +000069 bool VisitLambdaExpr(LambdaExpr *Lambda);
John McCall7353c862013-04-09 01:56:28 +000070 bool VisitPseudoObjectExpr(PseudoObjectExpr *POE);
Chris Lattnerb0d38442008-04-12 23:52:44 +000071 };
Chris Lattner58258242008-04-10 02:22:51 +000072
Chris Lattnerb0d38442008-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 McCall8322c3a2011-02-13 04:07:26 +000076 for (Stmt::child_range I = Node->children(); I; ++I)
Chris Lattner574dee62008-07-26 22:17:49 +000077 IsInvalid |= Visit(*I);
Chris Lattnerb0d38442008-04-12 23:52:44 +000078 return IsInvalid;
Chris Lattner58258242008-04-10 02:22:51 +000079 }
80
Chris Lattnerb0d38442008-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 Gregor5251f1b2008-10-21 16:13:35 +000085 NamedDecl *Decl = DRE->getDecl();
Chris Lattnerb0d38442008-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 Dunbar62ee6412012-03-09 18:35:03 +000095 return S->Diag(DRE->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +000096 diag::err_param_default_argument_references_param)
Chris Lattnere3d20d92008-11-23 21:45:46 +000097 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff08899ff2008-04-15 22:42:06 +000098 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattnerb0d38442008-04-12 23:52:44 +000099 // C++ [dcl.fct.default]p7
100 // Local variables shall not be used in default argument
101 // expressions.
John McCall1c9c3fd2010-10-15 04:57:14 +0000102 if (VDecl->isLocalVarDecl())
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000103 return S->Diag(DRE->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +0000104 diag::err_param_default_argument_references_local)
Chris Lattnere3d20d92008-11-23 21:45:46 +0000105 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +0000106 }
Chris Lattner58258242008-04-10 02:22:51 +0000107
Douglas Gregor8e12c382008-11-04 13:41:56 +0000108 return false;
109 }
Chris Lattnerb0d38442008-04-12 23:52:44 +0000110
Douglas Gregor97a9c812008-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 Dunbar62ee6412012-03-09 18:35:03 +0000116 return S->Diag(ThisE->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +0000117 diag::err_param_default_argument_references_this)
118 << ThisE->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +0000119 }
Douglas Gregorf0d49512012-02-10 23:30:22 +0000120
John McCall7353c862013-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 Gregorf0d49512012-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 Lattner58258242008-04-10 02:22:51 +0000148}
149
Richard Smithb7151b92013-04-10 06:11:48 +0000150void
151Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
152 const CXXMethodDecl *Method) {
Richard Smithd3b5c9082012-07-27 04:22:15 +0000153 // If we have an MSAny spec already, don't bother.
154 if (!Method || ComputedEST == EST_MSAny)
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000155 return;
156
157 const FunctionProtoType *Proto
158 = Method->getType()->getAs<FunctionProtoType>();
Richard Smithf623c962012-04-17 00:58:00 +0000159 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
160 if (!Proto)
161 return;
Alexis Hunt6d5b96c2011-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 Smithd3b5c9082012-07-27 04:22:15 +0000166 if (EST == EST_MSAny || EST == EST_None) {
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000167 ClearExceptions();
168 ComputedEST = EST;
169 return;
170 }
171
Richard Smith938f40b2011-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
Alexis Hunt6d5b96c2011-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 Smithf623c962012-04-17 00:58:00 +0000193 FunctionProtoType::NoexceptResult NR =
194 Proto->getNoexceptSpec(Self->Context);
Alexis Hunt6d5b96c2011-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 Smithf623c962012-04-17 00:58:00 +0000218 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(*E)))
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000219 Exceptions.push_back(*E);
220}
221
Richard Smith938f40b2011-06-11 17:19:42 +0000222void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
Richard Smithd3b5c9082012-07-27 04:22:15 +0000223 if (!E || ComputedEST == EST_MSAny)
Richard Smith938f40b2011-06-11 17:19:42 +0000224 return;
225
226 // FIXME:
227 //
228 // C++0x [except.spec]p14:
NAKAMURA Takumi53648472011-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 Smith938f40b2011-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 Smithf623c962012-04-17 00:58:00 +0000247 if (Self->canThrow(E))
Richard Smith938f40b2011-06-11 17:19:42 +0000248 ComputedEST = EST_None;
249}
250
Anders Carlssonc80a1272009-08-25 02:29:20 +0000251bool
John McCallb268a282010-08-23 23:25:46 +0000252Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump11289f42009-09-09 15:08:12 +0000253 SourceLocation EqualLoc) {
Anders Carlsson114056f2009-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 Carlssonc80a1272009-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 Jahanian8fb87ae2010-09-24 17:30:16 +0000266 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
267 Param);
Douglas Gregor85dabae2009-12-16 01:38:02 +0000268 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
269 EqualLoc);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +0000270 InitializationSequence InitSeq(*this, Entity, Kind, Arg);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000271 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
Eli Friedman5f101b92009-12-22 02:46:13 +0000272 if (Result.isInvalid())
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000273 return true;
Eli Friedman5f101b92009-12-22 02:46:13 +0000274 Arg = Result.takeAs<Expr>();
Anders Carlssonc80a1272009-08-25 02:29:20 +0000275
Richard Smithc406cb72013-01-17 01:17:56 +0000276 CheckCompletedExpr(Arg, EqualLoc);
John McCall5d413782010-12-06 08:20:24 +0000277 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000278
Anders Carlssonc80a1272009-08-25 02:29:20 +0000279 // Okay: add the default argument to the parameter
280 Param->setDefaultArg(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000281
Douglas Gregor758cb672010-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 Carlsson4562f1f2009-08-25 03:18:48 +0000294 return false;
Anders Carlssonc80a1272009-08-25 02:29:20 +0000295}
296
Chris Lattner58258242008-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 Lattner199abbc2008-04-08 05:04:30 +0000300void
John McCall48871652010-08-21 09:40:31 +0000301Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCallb268a282010-08-23 23:25:46 +0000302 Expr *DefaultArg) {
303 if (!param || !DefaultArg)
Douglas Gregor71a57182009-06-22 23:20:33 +0000304 return;
Mike Stump11289f42009-09-09 15:08:12 +0000305
John McCall48871652010-08-21 09:40:31 +0000306 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson84613c42009-06-12 16:51:40 +0000307 UnparsedDefaultArgLocs.erase(Param);
308
Chris Lattner199abbc2008-04-08 05:04:30 +0000309 // Default arguments are only permitted in C++
David Blaikiebbafb8a2012-03-11 07:00:24 +0000310 if (!getLangOpts().CPlusPlus) {
Chris Lattner3b054132008-11-19 05:08:23 +0000311 Diag(EqualLoc, diag::err_param_default_argument)
312 << DefaultArg->getSourceRange();
Douglas Gregor4d87df52008-12-16 21:30:33 +0000313 Param->setInvalidDecl();
Chris Lattner199abbc2008-04-08 05:04:30 +0000314 return;
315 }
316
Douglas Gregor6ff1fbf2010-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 Carlssonf1c26952009-08-25 01:02:06 +0000323 // Check that the default argument is well-formed
John McCallb268a282010-08-23 23:25:46 +0000324 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
325 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlssonf1c26952009-08-25 01:02:06 +0000326 Param->setInvalidDecl();
327 return;
328 }
Mike Stump11289f42009-09-09 15:08:12 +0000329
John McCallb268a282010-08-23 23:25:46 +0000330 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner199abbc2008-04-08 05:04:30 +0000331}
332
Douglas Gregor58354032008-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 McCall48871652010-08-21 09:40:31 +0000337void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson84613c42009-06-12 16:51:40 +0000338 SourceLocation EqualLoc,
339 SourceLocation ArgLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000340 if (!param)
341 return;
Mike Stump11289f42009-09-09 15:08:12 +0000342
John McCall48871652010-08-21 09:40:31 +0000343 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Nick Lewycky0f292892013-09-22 10:06:57 +0000344 Param->setUnparsedDefaultArg();
Anders Carlsson84613c42009-06-12 16:51:40 +0000345 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor58354032008-12-24 00:01:03 +0000346}
347
Douglas Gregor4d87df52008-12-16 21:30:33 +0000348/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
349/// the default argument for the parameter param failed.
John McCall48871652010-08-21 09:40:31 +0000350void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000351 if (!param)
352 return;
Mike Stump11289f42009-09-09 15:08:12 +0000353
John McCall48871652010-08-21 09:40:31 +0000354 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson84613c42009-06-12 16:51:40 +0000355 Param->setInvalidDecl();
Anders Carlsson84613c42009-06-12 16:51:40 +0000356 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +0000357}
358
Douglas Gregorcaa8ace2008-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 Smith5afcdf3f2013-03-06 01:37:38 +0000372 bool MightBeFunction = D.isFunctionDeclarationContext();
Chris Lattner83f095c2009-03-28 19:18:32 +0000373 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000374 DeclaratorChunk &chunk = D.getTypeObject(i);
375 if (chunk.Kind == DeclaratorChunk::Function) {
Richard Smith5afcdf3f2013-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 }
Alp Tokerc5350722014-02-26 22:27:52 +0000383 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
384 ++argIdx) {
385 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
Douglas Gregor58354032008-12-24 00:01:03 +0000386 if (Param->hasUnparsedDefaultArg()) {
Alp Tokerc5350722014-02-26 22:27:52 +0000387 CachedTokens *Toks = chunk.Fun.Params[argIdx].DefaultArgTokens;
Douglas Gregor4d87df52008-12-16 21:30:33 +0000388 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000389 << SourceRange((*Toks)[1].getLocation(),
390 Toks->back().getLocation());
Douglas Gregor4d87df52008-12-16 21:30:33 +0000391 delete Toks;
Alp Tokerc5350722014-02-26 22:27:52 +0000392 chunk.Fun.Params[argIdx].DefaultArgTokens = 0;
Douglas Gregor58354032008-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 Gregorcaa8ace2008-05-07 04:49:29 +0000397 }
398 }
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000399 } else if (chunk.Kind != DeclaratorChunk::Paren) {
400 MightBeFunction = false;
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000401 }
402 }
403}
404
David Majnemer502b0ed2013-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 Toppere4794282012-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 Molloye9430032012-03-13 08:55:35 +0000420bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
421 Scope *S) {
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000422 bool Invalid = false;
423
Chris Lattner199abbc2008-04-08 05:04:30 +0000424 // C++ [dcl.fct.default]p4:
Chris Lattner199abbc2008-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 Gregorc732aba2009-09-11 18:44:32 +0000436 //
437 // C++ [dcl.fct.default]p6:
Richard Smith541b38b2013-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 Gregorc732aba2009-09-11 18:44:32 +0000441 // member function declaration in the class definition.
Chris Lattner199abbc2008-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 Molloye9430032012-03-13 08:55:35 +0000446 bool OldParamHasDfl = OldParam->hasDefaultArg();
447 bool NewParamHasDfl = NewParam->hasDefaultArg();
448
449 NamedDecl *ND = Old;
Richard Smith541b38b2013-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 Molloye9430032012-03-13 08:55:35 +0000459 // Ignore default parameters of old decl if they are not in
Richard Smith541b38b2013-09-20 01:15:31 +0000460 // the same scope and this is not an out-of-line definition of
461 // a member function.
James Molloye9430032012-03-13 08:55:35 +0000462 OldParamHasDfl = false;
463
464 if (OldParamHasDfl && NewParamHasDfl) {
Francois Pichet8cb243a2011-04-10 04:58:30 +0000465
Francois Pichet53fe2bb2011-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 Blaikiebbafb8a2012-03-11 07:00:24 +0000472 if (getLangOpts().MicrosoftExt) {
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000473 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
474 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cb243a2011-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 Pichet93921652011-04-22 08:25:24 +0000482 DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000483 Invalid = false;
484 }
485 }
Douglas Gregor08dc5842010-01-13 00:12:48 +0000486
Francois Pichet8cb243a2011-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 Gregor08dc5842010-01-13 00:12:48 +0000492 // int f(int);
493 // void g(int (*fp)(int) = f);
494 // void g(int (*fp)(int) = &f);
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000495 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor08dc5842010-01-13 00:12:48 +0000496 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-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 Gregorec9fd132012-01-14 16:38:05 +0000500 for (FunctionDecl *Older = Old->getPreviousDecl();
501 Older; Older = Older->getPreviousDecl()) {
Douglas Gregorc732aba2009-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 Molloye9430032012-03-13 08:55:35 +0000510 } else if (OldParamHasDfl) {
John McCalle61b02b2010-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 McCall5d413782010-12-06 08:20:24 +0000513 // strips off any top-level ExprWithCleanups.
John McCallf3cd6652010-03-12 18:31:32 +0000514 NewParam->setHasInheritedDefaultArg();
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000515 if (OldParam->hasUninstantiatedDefaultArg())
516 NewParam->setUninstantiatedDefaultArg(
517 OldParam->getUninstantiatedDefaultArg());
518 else
John McCalle61b02b2010-05-04 01:53:42 +0000519 NewParam->setDefaultArg(OldParam->getInit());
James Molloye9430032012-03-13 08:55:35 +0000520 } else if (NewParamHasDfl) {
Douglas Gregorc732aba2009-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 Gregor62e10f02009-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 Gregor3362bde2009-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 Gregor62e10f02009-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 Gregorc732aba2009-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 Lattner199abbc2008-04-08 05:04:30 +0000570 }
571 }
572
Richard Smith58c3cc12012-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 Smith5b8b3db2012-02-20 23:28:05 +0000589 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
Richard Smitheb3c10c2011-10-01 02:31:28 +0000590 // template has a constexpr specifier then all its declarations shall
Richard Smith5b8b3db2012-02-20 23:28:05 +0000591 // contain the constexpr specifier.
Richard Smitheb3c10c2011-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 Majnemer502b0ed2013-06-25 23:09:30 +0000599 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
NAKAMURA Takumi3e7db842013-07-17 17:57:52 +0000600 // argument expression, that declaration shall be a definition and shall be
David Majnemer502b0ed2013-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 Gregorf40863c2010-02-12 07:32:17 +0000610 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000611 Invalid = true;
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000612
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000613 return Invalid;
Chris Lattner199abbc2008-04-08 05:04:30 +0000614}
615
Sebastian Redlfa453cf2011-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 Blaikiebbafb8a2012-03-11 07:00:24 +0000623 if (!getLangOpts().CXXExceptions)
Sebastian Redlfa453cf2011-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 Lattner199abbc2008-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 Smith3cb4c632013-04-17 16:25:20 +0000668 if (Param->hasDefaultArg())
Chris Lattner199abbc2008-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 Stump11289f42009-09-09 15:08:12 +0000679 for (; p < NumParams; ++p) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000680 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000681 if (!Param->hasDefaultArg()) {
Douglas Gregor4d87df52008-12-16 21:30:33 +0000682 if (Param->isInvalidDecl())
683 /* We already complained about this parameter. */;
684 else if (Param->getIdentifier())
Mike Stump11289f42009-09-09 15:08:12 +0000685 Diag(Param->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000686 diag::err_param_default_argument_missing_name)
Chris Lattnerb91fd172008-11-19 07:32:16 +0000687 << Param->getIdentifier();
Chris Lattner199abbc2008-04-08 05:04:30 +0000688 else
Mike Stump11289f42009-09-09 15:08:12 +0000689 Diag(Param->getLocation(),
Chris Lattner199abbc2008-04-08 05:04:30 +0000690 diag::err_param_default_argument_missing);
Mike Stump11289f42009-09-09 15:08:12 +0000691
Chris Lattner199abbc2008-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 Carlsson84613c42009-06-12 16:51:40 +0000703 if (Param->hasDefaultArg()) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000704 Param->setDefaultArg(0);
705 }
706 }
707 }
708}
Douglas Gregor556877c2008-04-13 21:30:24 +0000709
Richard Smitheb3c10c2011-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 Smith3607ffe2012-02-13 03:54:03 +0000712// diagnostic and return false.
713static bool CheckConstexprParameterTypes(Sema &SemaRef,
714 const FunctionDecl *FD) {
Richard Smitheb3c10c2011-10-01 02:31:28 +0000715 unsigned ArgIndex = 0;
716 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +0000717 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
718 e = FT->param_type_end();
719 i != e; ++i, ++ArgIndex) {
Richard Smitheb3c10c2011-10-01 02:31:28 +0000720 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
721 SourceLocation ParamLoc = PD->getLocation();
722 if (!(*i)->isDependentType() &&
Richard Smith3607ffe2012-02-13 03:54:03 +0000723 SemaRef.RequireLiteralType(ParamLoc, *i,
Douglas Gregora6c5abb2012-05-04 16:48:41 +0000724 diag::err_constexpr_non_literal_param,
725 ArgIndex+1, PD->getSourceRange(),
726 isa<CXXConstructorDecl>(FD)))
Richard Smitheb3c10c2011-10-01 02:31:28 +0000727 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000728 }
Joao Matose9a3ed42012-08-31 22:18:20 +0000729 return true;
730}
731
732/// \brief Get diagnostic %select index for tag kind for
733/// record diagnostic message.
734/// WARNING: Indexes apply to particular diagnostics only!
735///
736/// \returns diagnostic %select index.
Joao Matosa5c42e92012-09-01 00:13:24 +0000737static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
Joao Matose9a3ed42012-08-31 22:18:20 +0000738 switch (Tag) {
Joao Matosa5c42e92012-09-01 00:13:24 +0000739 case TTK_Struct: return 0;
740 case TTK_Interface: return 1;
741 case TTK_Class: return 2;
742 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
Joao Matose9a3ed42012-08-31 22:18:20 +0000743 }
Joao Matose9a3ed42012-08-31 22:18:20 +0000744}
745
746// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
747// the requirements of a constexpr function definition or a constexpr
748// constructor definition. If so, return true. If not, produce appropriate
Richard Smith3607ffe2012-02-13 03:54:03 +0000749// diagnostics and return false.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000750//
Richard Smith3607ffe2012-02-13 03:54:03 +0000751// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
752bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
Richard Smith7971b692012-01-13 04:54:00 +0000753 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
754 if (MD && MD->isInstance()) {
Richard Smith3607ffe2012-02-13 03:54:03 +0000755 // C++11 [dcl.constexpr]p4:
756 // The definition of a constexpr constructor shall satisfy the following
757 // constraints:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000758 // - the class shall not have any virtual base classes;
Joao Matose9a3ed42012-08-31 22:18:20 +0000759 const CXXRecordDecl *RD = MD->getParent();
760 if (RD->getNumVBases()) {
761 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
762 << isa<CXXConstructorDecl>(NewFD)
763 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
Aaron Ballman445a9392014-03-13 16:15:17 +0000764 for (const auto &I : RD->vbases())
765 Diag(I.getLocStart(),
766 diag::note_constexpr_virtual_base_here) << I.getSourceRange();
Richard Smitheb3c10c2011-10-01 02:31:28 +0000767 return false;
768 }
Richard Smith7971b692012-01-13 04:54:00 +0000769 }
770
771 if (!isa<CXXConstructorDecl>(NewFD)) {
772 // C++11 [dcl.constexpr]p3:
Richard Smitheb3c10c2011-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 Smith3607ffe2012-02-13 03:54:03 +0000778 Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000779
Richard Smith3607ffe2012-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 Smitheb3c10c2011-10-01 02:31:28 +0000788 return false;
789 }
790
791 // - its return type shall be a literal type;
Alp Toker314cc812014-01-25 16:55:45 +0000792 QualType RT = NewFD->getReturnType();
Richard Smitheb3c10c2011-10-01 02:31:28 +0000793 if (!RT->isDependentType() &&
Richard Smith3607ffe2012-02-13 03:54:03 +0000794 RequireLiteralType(NewFD->getLocation(), RT,
Douglas Gregora6c5abb2012-05-04 16:48:41 +0000795 diag::err_constexpr_non_literal_return))
Richard Smitheb3c10c2011-10-01 02:31:28 +0000796 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000797 }
798
Richard Smith7971b692012-01-13 04:54:00 +0000799 // - each of its parameter types shall be a literal type;
Richard Smith3607ffe2012-02-13 03:54:03 +0000800 if (!CheckConstexprParameterTypes(*this, NewFD))
Richard Smith7971b692012-01-13 04:54:00 +0000801 return false;
802
Richard Smitheb3c10c2011-10-01 02:31:28 +0000803 return true;
804}
805
806/// Check the given declaration statement is legal within a constexpr function
Richard Smithd9f663b2013-04-22 15:31:51 +0000807/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000808///
Richard Smithd9f663b2013-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 Smitheb3c10c2011-10-01 02:31:28 +0000811static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
Richard Smithd9f663b2013-04-22 15:31:51 +0000812 DeclStmt *DS, SourceLocation &Cxx1yLoc) {
813 // C++11 [dcl.constexpr]p3 and p4:
Richard Smitheb3c10c2011-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 Smithd9f663b2013-04-22 15:31:51 +0000824 case Decl::UnresolvedUsingValue:
Richard Smitheb3c10c2011-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 Smithd9f663b2013-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 Smitheb3c10c2011-10-01 02:31:28 +0000854 << isa<CXXConstructorDecl>(Dcl);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000855 continue;
856
Richard Smithd9f663b2013-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 Smith3da88fa2013-04-26 14:36:30 +0000877 if (!VD->getType()->isDependentType() &&
878 SemaRef.RequireLiteralType(
Richard Smithd9f663b2013-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;
Richard Smithab44d5b2013-12-10 08:25:00 +0000883 if (!VD->getType()->isDependentType() &&
884 !VD->hasInit() && !VD->isCXXForRangeDecl()) {
Richard Smithd9f663b2013-04-22 15:31:51 +0000885 SemaRef.Diag(VD->getLocation(),
886 diag::err_constexpr_local_var_no_init)
887 << isa<CXXConstructorDecl>(Dcl);
888 return false;
889 }
890 }
891 SemaRef.Diag(VD->getLocation(),
892 SemaRef.getLangOpts().CPlusPlus1y
893 ? diag::warn_cxx11_compat_constexpr_local_var
894 : diag::ext_constexpr_local_var)
Richard Smitheb3c10c2011-10-01 02:31:28 +0000895 << isa<CXXConstructorDecl>(Dcl);
Richard Smithd9f663b2013-04-22 15:31:51 +0000896 continue;
897 }
898
899 case Decl::NamespaceAlias:
900 case Decl::Function:
901 // These are disallowed in C++11 and permitted in C++1y. Allow them
902 // everywhere as an extension.
903 if (!Cxx1yLoc.isValid())
904 Cxx1yLoc = DS->getLocStart();
905 continue;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000906
907 default:
908 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
909 << isa<CXXConstructorDecl>(Dcl);
910 return false;
911 }
912 }
913
914 return true;
915}
916
917/// Check that the given field is initialized within a constexpr constructor.
918///
919/// \param Dcl The constexpr constructor being checked.
920/// \param Field The field being checked. This may be a member of an anonymous
921/// struct or union nested within the class being checked.
922/// \param Inits All declarations, including anonymous struct/union members and
923/// indirect members, for which any initialization was provided.
924/// \param Diagnosed Set to true if an error is produced.
925static void CheckConstexprCtorInitializer(Sema &SemaRef,
926 const FunctionDecl *Dcl,
927 FieldDecl *Field,
928 llvm::SmallSet<Decl*, 16> &Inits,
929 bool &Diagnosed) {
Eli Friedmanb13e64e2013-06-28 21:07:41 +0000930 if (Field->isInvalidDecl())
931 return;
932
Douglas Gregor556e5862011-10-10 17:22:13 +0000933 if (Field->isUnnamedBitfield())
934 return;
Richard Smith4d59eeb2012-02-09 06:40:58 +0000935
Richard Smithab44d5b2013-12-10 08:25:00 +0000936 // Anonymous unions with no variant members and empty anonymous structs do not
937 // need to be explicitly initialized. FIXME: Anonymous structs that contain no
938 // indirect fields don't need initializing.
Richard Smith4d59eeb2012-02-09 06:40:58 +0000939 if (Field->isAnonymousStructOrUnion() &&
Richard Smithab44d5b2013-12-10 08:25:00 +0000940 (Field->getType()->isUnionType()
941 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
942 : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
Richard Smith4d59eeb2012-02-09 06:40:58 +0000943 return;
944
Richard Smitheb3c10c2011-10-01 02:31:28 +0000945 if (!Inits.count(Field)) {
946 if (!Diagnosed) {
947 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
948 Diagnosed = true;
949 }
950 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
951 } else if (Field->isAnonymousStructOrUnion()) {
952 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000953 for (auto *I : RD->fields())
Richard Smitheb3c10c2011-10-01 02:31:28 +0000954 // If an anonymous union contains an anonymous struct of which any member
955 // is initialized, all members must be initialized.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000956 if (!RD->isUnion() || Inits.count(I))
957 CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000958 }
959}
960
Richard Smithd9f663b2013-04-22 15:31:51 +0000961/// Check the provided statement is allowed in a constexpr function
962/// definition.
963static bool
964CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
Robert Wilhelmb869a8f2013-08-10 12:33:24 +0000965 SmallVectorImpl<SourceLocation> &ReturnStmts,
Richard Smithd9f663b2013-04-22 15:31:51 +0000966 SourceLocation &Cxx1yLoc) {
967 // - its function-body shall be [...] a compound-statement that contains only
968 switch (S->getStmtClass()) {
969 case Stmt::NullStmtClass:
970 // - null statements,
971 return true;
972
973 case Stmt::DeclStmtClass:
974 // - static_assert-declarations
975 // - using-declarations,
976 // - using-directives,
977 // - typedef declarations and alias-declarations that do not define
978 // classes or enumerations,
979 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
980 return false;
981 return true;
982
983 case Stmt::ReturnStmtClass:
984 // - and exactly one return statement;
985 if (isa<CXXConstructorDecl>(Dcl)) {
986 // C++1y allows return statements in constexpr constructors.
987 if (!Cxx1yLoc.isValid())
988 Cxx1yLoc = S->getLocStart();
989 return true;
990 }
991
992 ReturnStmts.push_back(S->getLocStart());
993 return true;
994
995 case Stmt::CompoundStmtClass: {
996 // C++1y allows compound-statements.
997 if (!Cxx1yLoc.isValid())
998 Cxx1yLoc = S->getLocStart();
999
1000 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
1001 for (CompoundStmt::body_iterator BodyIt = CompStmt->body_begin(),
1002 BodyEnd = CompStmt->body_end(); BodyIt != BodyEnd; ++BodyIt) {
1003 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, *BodyIt, ReturnStmts,
1004 Cxx1yLoc))
1005 return false;
1006 }
1007 return true;
1008 }
1009
1010 case Stmt::AttributedStmtClass:
1011 if (!Cxx1yLoc.isValid())
1012 Cxx1yLoc = S->getLocStart();
1013 return true;
1014
1015 case Stmt::IfStmtClass: {
1016 // C++1y allows if-statements.
1017 if (!Cxx1yLoc.isValid())
1018 Cxx1yLoc = S->getLocStart();
1019
1020 IfStmt *If = cast<IfStmt>(S);
1021 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1022 Cxx1yLoc))
1023 return false;
1024 if (If->getElse() &&
1025 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1026 Cxx1yLoc))
1027 return false;
1028 return true;
1029 }
1030
1031 case Stmt::WhileStmtClass:
1032 case Stmt::DoStmtClass:
1033 case Stmt::ForStmtClass:
1034 case Stmt::CXXForRangeStmtClass:
1035 case Stmt::ContinueStmtClass:
1036 // C++1y allows all of these. We don't allow them as extensions in C++11,
1037 // because they don't make sense without variable mutation.
1038 if (!SemaRef.getLangOpts().CPlusPlus1y)
1039 break;
1040 if (!Cxx1yLoc.isValid())
1041 Cxx1yLoc = S->getLocStart();
1042 for (Stmt::child_range Children = S->children(); Children; ++Children)
1043 if (*Children &&
1044 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1045 Cxx1yLoc))
1046 return false;
1047 return true;
1048
1049 case Stmt::SwitchStmtClass:
1050 case Stmt::CaseStmtClass:
1051 case Stmt::DefaultStmtClass:
1052 case Stmt::BreakStmtClass:
1053 // C++1y allows switch-statements, and since they don't need variable
1054 // mutation, we can reasonably allow them in C++11 as an extension.
1055 if (!Cxx1yLoc.isValid())
1056 Cxx1yLoc = S->getLocStart();
1057 for (Stmt::child_range Children = S->children(); Children; ++Children)
1058 if (*Children &&
1059 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1060 Cxx1yLoc))
1061 return false;
1062 return true;
1063
1064 default:
1065 if (!isa<Expr>(S))
1066 break;
1067
1068 // C++1y allows expression-statements.
1069 if (!Cxx1yLoc.isValid())
1070 Cxx1yLoc = S->getLocStart();
1071 return true;
1072 }
1073
1074 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1075 << isa<CXXConstructorDecl>(Dcl);
1076 return false;
1077}
1078
Richard Smitheb3c10c2011-10-01 02:31:28 +00001079/// Check the body for the given constexpr function declaration only contains
1080/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1081///
1082/// \return true if the body is OK, false if we have diagnosed a problem.
Richard Smith3607ffe2012-02-13 03:54:03 +00001083bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001084 if (isa<CXXTryStmt>(Body)) {
Richard Smith74388b42012-02-04 00:33:54 +00001085 // C++11 [dcl.constexpr]p3:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001086 // The definition of a constexpr function shall satisfy the following
1087 // constraints: [...]
1088 // - its function-body shall be = delete, = default, or a
1089 // compound-statement
1090 //
Richard Smith74388b42012-02-04 00:33:54 +00001091 // C++11 [dcl.constexpr]p4:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001092 // In the definition of a constexpr constructor, [...]
1093 // - its function-body shall not be a function-try-block;
1094 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1095 << isa<CXXConstructorDecl>(Dcl);
1096 return false;
1097 }
1098
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001099 SmallVector<SourceLocation, 4> ReturnStmts;
Richard Smithd9f663b2013-04-22 15:31:51 +00001100
1101 // - its function-body shall be [...] a compound-statement that contains only
1102 // [... list of cases ...]
1103 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1104 SourceLocation Cxx1yLoc;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001105 for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(),
1106 BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001107 if (!CheckConstexprFunctionStmt(*this, Dcl, *BodyIt, ReturnStmts, Cxx1yLoc))
1108 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001109 }
1110
Richard Smithd9f663b2013-04-22 15:31:51 +00001111 if (Cxx1yLoc.isValid())
1112 Diag(Cxx1yLoc,
1113 getLangOpts().CPlusPlus1y
1114 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1115 : diag::ext_constexpr_body_invalid_stmt)
1116 << isa<CXXConstructorDecl>(Dcl);
1117
Richard Smitheb3c10c2011-10-01 02:31:28 +00001118 if (const CXXConstructorDecl *Constructor
1119 = dyn_cast<CXXConstructorDecl>(Dcl)) {
1120 const CXXRecordDecl *RD = Constructor->getParent();
Richard Smith4d59eeb2012-02-09 06:40:58 +00001121 // DR1359:
1122 // - every non-variant non-static data member and base class sub-object
1123 // shall be initialized;
Richard Smithab44d5b2013-12-10 08:25:00 +00001124 // DR1460:
1125 // - if the class is a union having variant members, exactly one of them
Richard Smith4d59eeb2012-02-09 06:40:58 +00001126 // shall be initialized;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001127 if (RD->isUnion()) {
Richard Smithab44d5b2013-12-10 08:25:00 +00001128 if (Constructor->getNumCtorInitializers() == 0 &&
1129 RD->hasVariantMembers()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001130 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1131 return false;
1132 }
Richard Smithf368fb42011-10-10 16:38:04 +00001133 } else if (!Constructor->isDependentContext() &&
1134 !Constructor->isDelegatingConstructor()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001135 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1136
1137 // Skip detailed checking if we have enough initializers, and we would
1138 // allow at most one initializer per member.
1139 bool AnyAnonStructUnionMembers = false;
1140 unsigned Fields = 0;
1141 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1142 E = RD->field_end(); I != E; ++I, ++Fields) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001143 if (I->isAnonymousStructOrUnion()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001144 AnyAnonStructUnionMembers = true;
1145 break;
1146 }
1147 }
Richard Smithab44d5b2013-12-10 08:25:00 +00001148 // DR1460:
1149 // - if the class is a union-like class, but is not a union, for each of
1150 // its anonymous union members having variant members, exactly one of
1151 // them shall be initialized;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001152 if (AnyAnonStructUnionMembers ||
1153 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1154 // Check initialization of non-static data members. Base classes are
1155 // always initialized so do not need to be checked. Dependent bases
1156 // might not have initializers in the member initializer list.
1157 llvm::SmallSet<Decl*, 16> Inits;
Aaron Ballman0ad78302014-03-13 17:34:31 +00001158 for (const auto *I: Constructor->inits()) {
1159 if (FieldDecl *FD = I->getMember())
Richard Smitheb3c10c2011-10-01 02:31:28 +00001160 Inits.insert(FD);
Aaron Ballman0ad78302014-03-13 17:34:31 +00001161 else if (IndirectFieldDecl *ID = I->getIndirectMember())
Richard Smitheb3c10c2011-10-01 02:31:28 +00001162 Inits.insert(ID->chain_begin(), ID->chain_end());
1163 }
1164
1165 bool Diagnosed = false;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001166 for (auto *I : RD->fields())
1167 CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001168 if (Diagnosed)
1169 return false;
1170 }
1171 }
Richard Smitheb3c10c2011-10-01 02:31:28 +00001172 } else {
1173 if (ReturnStmts.empty()) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001174 // C++1y doesn't require constexpr functions to contain a 'return'
1175 // statement. We still do, unless the return type is void, because
1176 // otherwise if there's no return statement, the function cannot
1177 // be used in a core constant expression.
Alp Toker314cc812014-01-25 16:55:45 +00001178 bool OK = getLangOpts().CPlusPlus1y && Dcl->getReturnType()->isVoidType();
Richard Smithd9f663b2013-04-22 15:31:51 +00001179 Diag(Dcl->getLocation(),
Richard Smith3da88fa2013-04-26 14:36:30 +00001180 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
1181 : diag::err_constexpr_body_no_return);
1182 return OK;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001183 }
1184 if (ReturnStmts.size() > 1) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001185 Diag(ReturnStmts.back(),
1186 getLangOpts().CPlusPlus1y
1187 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
1188 : diag::ext_constexpr_body_multiple_return);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001189 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
1190 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001191 }
1192 }
1193
Richard Smith74388b42012-02-04 00:33:54 +00001194 // C++11 [dcl.constexpr]p5:
1195 // if no function argument values exist such that the function invocation
1196 // substitution would produce a constant expression, the program is
1197 // ill-formed; no diagnostic required.
1198 // C++11 [dcl.constexpr]p3:
1199 // - every constructor call and implicit conversion used in initializing the
1200 // return value shall be one of those allowed in a constant expression.
1201 // C++11 [dcl.constexpr]p4:
1202 // - every constructor involved in initializing non-static data members and
1203 // base class sub-objects shall be a constexpr constructor.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001204 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith3607ffe2012-02-13 03:54:03 +00001205 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smithf86b5dc2012-12-09 05:55:43 +00001206 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
Richard Smith253c2a32012-01-27 01:14:48 +00001207 << isa<CXXConstructorDecl>(Dcl);
1208 for (size_t I = 0, N = Diags.size(); I != N; ++I)
1209 Diag(Diags[I].first, Diags[I].second);
Richard Smithf86b5dc2012-12-09 05:55:43 +00001210 // Don't return false here: we allow this for compatibility in
1211 // system headers.
Richard Smith253c2a32012-01-27 01:14:48 +00001212 }
1213
Richard Smitheb3c10c2011-10-01 02:31:28 +00001214 return true;
1215}
1216
Douglas Gregor61956c42008-10-31 09:07:45 +00001217/// isCurrentClassName - Determine whether the identifier II is the
1218/// name of the class type currently being defined. In the case of
1219/// nested classes, this will only return true if II is the name of
1220/// the innermost class.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00001221bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1222 const CXXScopeSpec *SS) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001223 assert(getLangOpts().CPlusPlus && "No class names in C!");
Douglas Gregor411e5ac2010-01-11 23:29:10 +00001224
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00001225 CXXRecordDecl *CurDecl;
Douglas Gregor52537682009-03-19 00:18:19 +00001226 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregore5bbb7d2009-08-21 22:16:40 +00001227 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00001228 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1229 } else
1230 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1231
Douglas Gregor1aa3edb2010-02-05 06:12:42 +00001232 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregor61956c42008-10-31 09:07:45 +00001233 return &II == CurDecl->getIdentifier();
Benjamin Kramer8bf44352013-07-24 15:28:33 +00001234 return false;
Douglas Gregor61956c42008-10-31 09:07:45 +00001235}
1236
Richard Smithfb8b7b92013-10-15 00:00:26 +00001237/// \brief Determine whether the identifier II is a typo for the name of
1238/// the class type currently being defined. If so, update it to the identifier
1239/// that should have been used.
1240bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
1241 assert(getLangOpts().CPlusPlus && "No class names in C!");
1242
1243 if (!getLangOpts().SpellChecking)
1244 return false;
1245
1246 CXXRecordDecl *CurDecl;
1247 if (SS && SS->isSet() && !SS->isInvalid()) {
1248 DeclContext *DC = computeDeclContext(*SS, true);
1249 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1250 } else
1251 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1252
1253 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
1254 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
1255 < II->getLength()) {
1256 II = CurDecl->getIdentifier();
1257 return true;
1258 }
1259
1260 return false;
1261}
1262
Douglas Gregordc974572012-11-10 07:24:09 +00001263/// \brief Determine whether the given class is a base class of the given
1264/// class, including looking at dependent bases.
1265static bool findCircularInheritance(const CXXRecordDecl *Class,
1266 const CXXRecordDecl *Current) {
1267 SmallVector<const CXXRecordDecl*, 8> Queue;
1268
1269 Class = Class->getCanonicalDecl();
1270 while (true) {
Aaron Ballman574705e2014-03-13 15:41:46 +00001271 for (const auto &I : Current->bases()) {
1272 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
Douglas Gregordc974572012-11-10 07:24:09 +00001273 if (!Base)
1274 continue;
1275
1276 Base = Base->getDefinition();
1277 if (!Base)
1278 continue;
1279
1280 if (Base->getCanonicalDecl() == Class)
1281 return true;
1282
1283 Queue.push_back(Base);
1284 }
1285
1286 if (Queue.empty())
1287 return false;
1288
Robert Wilhelm25284cc2013-08-23 16:11:15 +00001289 Current = Queue.pop_back_val();
Douglas Gregordc974572012-11-10 07:24:09 +00001290 }
1291
1292 return false;
Douglas Gregor62004702012-11-10 01:18:17 +00001293}
1294
Mike Stump11289f42009-09-09 15:08:12 +00001295/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor463421d2009-03-03 04:44:36 +00001296///
1297/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1298/// and returns NULL otherwise.
1299CXXBaseSpecifier *
1300Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1301 SourceRange SpecifierRange,
1302 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +00001303 TypeSourceInfo *TInfo,
1304 SourceLocation EllipsisLoc) {
Nick Lewycky19b9f952010-07-26 16:56:01 +00001305 QualType BaseType = TInfo->getType();
1306
Douglas Gregor463421d2009-03-03 04:44:36 +00001307 // C++ [class.union]p1:
1308 // A union shall not have base classes.
1309 if (Class->isUnion()) {
1310 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1311 << SpecifierRange;
1312 return 0;
1313 }
1314
Douglas Gregor752a5952011-01-03 22:36:02 +00001315 if (EllipsisLoc.isValid() &&
1316 !TInfo->getType()->containsUnexpandedParameterPack()) {
1317 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1318 << TInfo->getTypeLoc().getSourceRange();
1319 EllipsisLoc = SourceLocation();
1320 }
Douglas Gregor62004702012-11-10 01:18:17 +00001321
1322 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1323
1324 if (BaseType->isDependentType()) {
1325 // Make sure that we don't have circular inheritance among our dependent
1326 // bases. For non-dependent bases, the check for completeness below handles
1327 // this.
1328 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1329 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1330 ((BaseDecl = BaseDecl->getDefinition()) &&
Douglas Gregordc974572012-11-10 07:24:09 +00001331 findCircularInheritance(Class, BaseDecl))) {
Douglas Gregor62004702012-11-10 01:18:17 +00001332 Diag(BaseLoc, diag::err_circular_inheritance)
1333 << BaseType << Context.getTypeDeclType(Class);
1334
1335 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1336 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1337 << BaseType;
1338
1339 return 0;
1340 }
1341 }
1342
Mike Stump11289f42009-09-09 15:08:12 +00001343 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +00001344 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +00001345 Access, TInfo, EllipsisLoc);
Douglas Gregor62004702012-11-10 01:18:17 +00001346 }
Douglas Gregor463421d2009-03-03 04:44:36 +00001347
1348 // Base specifiers must be record types.
1349 if (!BaseType->isRecordType()) {
1350 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1351 return 0;
1352 }
1353
1354 // C++ [class.union]p1:
1355 // A union shall not be used as a base class.
1356 if (BaseType->isUnionType()) {
1357 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1358 return 0;
1359 }
1360
1361 // C++ [class.derived]p2:
1362 // The class-name in a base-specifier shall not be an incompletely
1363 // defined class.
Mike Stump11289f42009-09-09 15:08:12 +00001364 if (RequireCompleteType(BaseLoc, BaseType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001365 diag::err_incomplete_base_class, SpecifierRange)) {
John McCall3696dcb2010-08-17 07:23:57 +00001366 Class->setInvalidDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +00001367 return 0;
John McCall3696dcb2010-08-17 07:23:57 +00001368 }
Douglas Gregor463421d2009-03-03 04:44:36 +00001369
Eli Friedmanc96d4962009-08-15 21:55:26 +00001370 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001371 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +00001372 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001373 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor463421d2009-03-03 04:44:36 +00001374 assert(BaseDecl && "Base type is not incomplete, but has no definition");
David Majnemer626032f2013-06-22 06:43:58 +00001375 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
Eli Friedmanc96d4962009-08-15 21:55:26 +00001376 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedman89c038e2009-12-05 23:03:49 +00001377
David Majnemer9b1754d2013-11-02 12:00:36 +00001378 // A class which contains a flexible array member is not suitable for use as a
1379 // base class:
1380 // - If the layout determines that a base comes before another base,
1381 // the flexible array member would index into the subsequent base.
1382 // - If the layout determines that base comes before the derived class,
1383 // the flexible array member would index into the derived class.
1384 if (CXXBaseDecl->hasFlexibleArrayMember()) {
1385 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
1386 << CXXBaseDecl->getDeclName();
1387 return 0;
1388 }
1389
Anders Carlsson65c76d32011-03-25 14:55:14 +00001390 // C++ [class]p3:
David Majnemer45897602013-11-02 11:24:41 +00001391 // If a class is marked final and it appears as a base-type-specifier in
Anders Carlsson65c76d32011-03-25 14:55:14 +00001392 // base-clause, the program is ill-formed.
David Majnemera5433082013-10-18 00:33:31 +00001393 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
David Majnemer45897602013-11-02 11:24:41 +00001394 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
David Majnemera5433082013-10-18 00:33:31 +00001395 << CXXBaseDecl->getDeclName()
1396 << FA->isSpelledAsSealed();
Anders Carlssonfc1eef42011-01-22 17:51:53 +00001397 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1398 << CXXBaseDecl->getDeclName();
1399 return 0;
1400 }
1401
John McCall3696dcb2010-08-17 07:23:57 +00001402 if (BaseDecl->isInvalidDecl())
1403 Class->setInvalidDecl();
David Majnemer45897602013-11-02 11:24:41 +00001404
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001405 // Create the base specifier.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001406 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +00001407 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +00001408 Access, TInfo, EllipsisLoc);
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001409}
1410
Douglas Gregor556877c2008-04-13 21:30:24 +00001411/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1412/// one entry in the base class list of a class specifier, for
Mike Stump11289f42009-09-09 15:08:12 +00001413/// example:
1414/// class foo : public bar, virtual private baz {
Douglas Gregor556877c2008-04-13 21:30:24 +00001415/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallfaf5fb42010-08-26 23:41:50 +00001416BaseResult
John McCall48871652010-08-21 09:40:31 +00001417Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Richard Smith4c96e992013-02-19 23:47:15 +00001418 ParsedAttributes &Attributes,
Douglas Gregor29a92472008-10-22 17:49:05 +00001419 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +00001420 ParsedType basetype, SourceLocation BaseLoc,
1421 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001422 if (!classdecl)
1423 return true;
1424
Douglas Gregorc40290e2009-03-09 23:48:35 +00001425 AdjustDeclIfTemplate(classdecl);
John McCall48871652010-08-21 09:40:31 +00001426 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregorbeab56e2010-02-27 00:25:28 +00001427 if (!Class)
1428 return true;
1429
Richard Smith4c96e992013-02-19 23:47:15 +00001430 // We do not support any C++11 attributes on base-specifiers yet.
1431 // Diagnose any attributes we see.
1432 if (!Attributes.empty()) {
1433 for (AttributeList *Attr = Attributes.getList(); Attr;
1434 Attr = Attr->getNext()) {
1435 if (Attr->isInvalid() ||
1436 Attr->getKind() == AttributeList::IgnoredAttribute)
1437 continue;
1438 Diag(Attr->getLoc(),
1439 Attr->getKind() == AttributeList::UnknownAttribute
1440 ? diag::warn_unknown_attribute_ignored
1441 : diag::err_base_specifier_attribute)
1442 << Attr->getName();
1443 }
1444 }
1445
Nick Lewycky19b9f952010-07-26 16:56:01 +00001446 TypeSourceInfo *TInfo = 0;
1447 GetTypeFromParser(basetype, &TInfo);
Douglas Gregor506bd562010-12-13 22:49:22 +00001448
Douglas Gregor752a5952011-01-03 22:36:02 +00001449 if (EllipsisLoc.isInvalid() &&
1450 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregor506bd562010-12-13 22:49:22 +00001451 UPPC_BaseType))
1452 return true;
Douglas Gregor752a5952011-01-03 22:36:02 +00001453
Douglas Gregor463421d2009-03-03 04:44:36 +00001454 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregor752a5952011-01-03 22:36:02 +00001455 Virtual, Access, TInfo,
1456 EllipsisLoc))
Douglas Gregor463421d2009-03-03 04:44:36 +00001457 return BaseSpec;
Douglas Gregorb9b8b812012-07-02 21:00:41 +00001458 else
1459 Class->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001460
Douglas Gregor463421d2009-03-03 04:44:36 +00001461 return true;
Douglas Gregor29a92472008-10-22 17:49:05 +00001462}
Douglas Gregor556877c2008-04-13 21:30:24 +00001463
Douglas Gregor463421d2009-03-03 04:44:36 +00001464/// \brief Performs the actual work of attaching the given base class
1465/// specifiers to a C++ class.
1466bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1467 unsigned NumBases) {
1468 if (NumBases == 0)
1469 return false;
Douglas Gregor29a92472008-10-22 17:49:05 +00001470
1471 // Used to keep track of which base types we have already seen, so
1472 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001473 // that the key is always the unqualified canonical type of the base
1474 // class.
Douglas Gregor29a92472008-10-22 17:49:05 +00001475 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1476
1477 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001478 unsigned NumGoodBases = 0;
Douglas Gregor463421d2009-03-03 04:44:36 +00001479 bool Invalid = false;
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001480 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump11289f42009-09-09 15:08:12 +00001481 QualType NewBaseType
Douglas Gregor463421d2009-03-03 04:44:36 +00001482 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001483 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Benjamin Kramer73ecd702012-03-05 17:20:04 +00001484
1485 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1486 if (KnownBase) {
Douglas Gregor29a92472008-10-22 17:49:05 +00001487 // C++ [class.mi]p3:
1488 // A class shall not be specified as a direct base class of a
1489 // derived class more than once.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001490 Diag(Bases[idx]->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001491 diag::err_duplicate_base_class)
Benjamin Kramer73ecd702012-03-05 17:20:04 +00001492 << KnownBase->getType()
Douglas Gregor463421d2009-03-03 04:44:36 +00001493 << Bases[idx]->getSourceRange();
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001494
1495 // Delete the duplicate base class specifier; we're going to
1496 // overwrite its pointer later.
Douglas Gregorb77af8f2009-07-22 20:55:49 +00001497 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +00001498
1499 Invalid = true;
Douglas Gregor29a92472008-10-22 17:49:05 +00001500 } else {
1501 // Okay, add this new base class.
Benjamin Kramer73ecd702012-03-05 17:20:04 +00001502 KnownBase = Bases[idx];
Douglas Gregor463421d2009-03-03 04:44:36 +00001503 Bases[NumGoodBases++] = Bases[idx];
John McCalldb632ac2012-09-25 07:32:39 +00001504 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1505 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1506 if (Class->isInterface() &&
1507 (!RD->isInterface() ||
1508 KnownBase->getAccessSpecifier() != AS_public)) {
1509 // The Microsoft extension __interface does not permit bases that
1510 // are not themselves public interfaces.
1511 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1512 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1513 << RD->getSourceRange();
1514 Invalid = true;
1515 }
1516 if (RD->hasAttr<WeakAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +00001517 Class->addAttr(WeakAttr::CreateImplicit(Context));
John McCalldb632ac2012-09-25 07:32:39 +00001518 }
Douglas Gregor29a92472008-10-22 17:49:05 +00001519 }
1520 }
1521
1522 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor4a62bdf2010-02-11 01:30:34 +00001523 Class->setBases(Bases, NumGoodBases);
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001524
1525 // Delete the remaining (good) base class specifiers, since their
1526 // data has been copied into the CXXRecordDecl.
1527 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregorb77af8f2009-07-22 20:55:49 +00001528 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +00001529
1530 return Invalid;
1531}
1532
1533/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1534/// class, after checking whether there are any duplicate base
1535/// classes.
Richard Trieu9becef62011-09-09 03:18:59 +00001536void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor463421d2009-03-03 04:44:36 +00001537 unsigned NumBases) {
1538 if (!ClassDecl || !Bases || !NumBases)
1539 return;
1540
1541 AdjustDeclIfTemplate(ClassDecl);
Robert Wilhelme3cea802013-07-22 05:04:01 +00001542 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases, NumBases);
Douglas Gregor556877c2008-04-13 21:30:24 +00001543}
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00001544
Douglas Gregor36d1b142009-10-06 17:59:45 +00001545/// \brief Determine whether the type \p Derived is a C++ class that is
1546/// derived from the type \p Base.
1547bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001548 if (!getLangOpts().CPlusPlus)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001549 return false;
John McCalle78aac42010-03-10 03:28:59 +00001550
Douglas Gregor45bb4832013-03-26 23:36:30 +00001551 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001552 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001553 return false;
1554
Douglas Gregor45bb4832013-03-26 23:36:30 +00001555 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001556 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001557 return false;
Douglas Gregor45bb4832013-03-26 23:36:30 +00001558
1559 // If either the base or the derived type is invalid, don't try to
1560 // check whether one is derived from the other.
1561 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
1562 return false;
1563
John McCall67da35c2010-02-04 22:26:26 +00001564 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1565 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregor36d1b142009-10-06 17:59:45 +00001566}
1567
1568/// \brief Determine whether the type \p Derived is a C++ class that is
1569/// derived from the type \p Base.
1570bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001571 if (!getLangOpts().CPlusPlus)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001572 return false;
1573
Douglas Gregor45bb4832013-03-26 23:36:30 +00001574 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001575 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001576 return false;
1577
Douglas Gregor45bb4832013-03-26 23:36:30 +00001578 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001579 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001580 return false;
1581
Douglas Gregor36d1b142009-10-06 17:59:45 +00001582 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1583}
1584
Anders Carlssona70cff62010-04-24 19:06:50 +00001585void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallcf142162010-08-07 06:22:56 +00001586 CXXCastPath &BasePathArray) {
Anders Carlssona70cff62010-04-24 19:06:50 +00001587 assert(BasePathArray.empty() && "Base path array must be empty!");
1588 assert(Paths.isRecordingPaths() && "Must record paths!");
1589
1590 const CXXBasePath &Path = Paths.front();
1591
1592 // We first go backward and check if we have a virtual base.
1593 // FIXME: It would be better if CXXBasePath had the base specifier for
1594 // the nearest virtual base.
1595 unsigned Start = 0;
1596 for (unsigned I = Path.size(); I != 0; --I) {
1597 if (Path[I - 1].Base->isVirtual()) {
1598 Start = I - 1;
1599 break;
1600 }
1601 }
1602
1603 // Now add all bases.
1604 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallcf142162010-08-07 06:22:56 +00001605 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlssona70cff62010-04-24 19:06:50 +00001606}
1607
Douglas Gregor88d292c2010-05-13 16:44:06 +00001608/// \brief Determine whether the given base path includes a virtual
1609/// base class.
John McCallcf142162010-08-07 06:22:56 +00001610bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1611 for (CXXCastPath::const_iterator B = BasePath.begin(),
1612 BEnd = BasePath.end();
Douglas Gregor88d292c2010-05-13 16:44:06 +00001613 B != BEnd; ++B)
1614 if ((*B)->isVirtual())
1615 return true;
1616
1617 return false;
1618}
1619
Douglas Gregor36d1b142009-10-06 17:59:45 +00001620/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1621/// conversion (where Derived and Base are class types) is
1622/// well-formed, meaning that the conversion is unambiguous (and
1623/// that all of the base classes are accessible). Returns true
1624/// and emits a diagnostic if the code is ill-formed, returns false
1625/// otherwise. Loc is the location where this routine should point to
1626/// if there is an error, and Range is the source range to highlight
1627/// if there is an error.
1628bool
1629Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall1064d7e2010-03-16 05:22:47 +00001630 unsigned InaccessibleBaseID,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001631 unsigned AmbigiousBaseConvID,
1632 SourceLocation Loc, SourceRange Range,
Anders Carlsson7afe4242010-04-24 17:11:09 +00001633 DeclarationName Name,
John McCallcf142162010-08-07 06:22:56 +00001634 CXXCastPath *BasePath) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001635 // First, determine whether the path from Derived to Base is
1636 // ambiguous. This is slightly more expensive than checking whether
1637 // the Derived to Base conversion exists, because here we need to
1638 // explore multiple paths to determine if there is an ambiguity.
1639 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1640 /*DetectVirtual=*/false);
1641 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1642 assert(DerivationOkay &&
1643 "Can only be used with a derived-to-base conversion");
1644 (void)DerivationOkay;
1645
1646 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlssona70cff62010-04-24 19:06:50 +00001647 if (InaccessibleBaseID) {
1648 // Check that the base class can be accessed.
1649 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1650 InaccessibleBaseID)) {
1651 case AR_inaccessible:
1652 return true;
1653 case AR_accessible:
1654 case AR_dependent:
1655 case AR_delayed:
1656 break;
Anders Carlsson7afe4242010-04-24 17:11:09 +00001657 }
John McCall5b0829a2010-02-10 09:31:12 +00001658 }
Anders Carlssona70cff62010-04-24 19:06:50 +00001659
1660 // Build a base path if necessary.
1661 if (BasePath)
1662 BuildBasePathArray(Paths, *BasePath);
1663 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +00001664 }
1665
David Majnemer626032f2013-06-22 06:43:58 +00001666 if (AmbigiousBaseConvID) {
1667 // We know that the derived-to-base conversion is ambiguous, and
1668 // we're going to produce a diagnostic. Perform the derived-to-base
1669 // search just one more time to compute all of the possible paths so
1670 // that we can print them out. This is more expensive than any of
1671 // the previous derived-to-base checks we've done, but at this point
1672 // performance isn't as much of an issue.
1673 Paths.clear();
1674 Paths.setRecordingPaths(true);
1675 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1676 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1677 (void)StillOkay;
1678
1679 // Build up a textual representation of the ambiguous paths, e.g.,
1680 // D -> B -> A, that will be used to illustrate the ambiguous
1681 // conversions in the diagnostic. We only print one of the paths
1682 // to each base class subobject.
1683 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1684
1685 Diag(Loc, AmbigiousBaseConvID)
1686 << Derived << Base << PathDisplayStr << Range << Name;
1687 }
Douglas Gregor36d1b142009-10-06 17:59:45 +00001688 return true;
1689}
1690
1691bool
1692Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redl7c353682009-11-14 21:15:49 +00001693 SourceLocation Loc, SourceRange Range,
John McCallcf142162010-08-07 06:22:56 +00001694 CXXCastPath *BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001695 bool IgnoreAccess) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001696 return CheckDerivedToBaseConversion(Derived, Base,
John McCall1064d7e2010-03-16 05:22:47 +00001697 IgnoreAccess ? 0
1698 : diag::err_upcast_to_inaccessible_base,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001699 diag::err_ambiguous_derived_to_base_conv,
Anders Carlsson7afe4242010-04-24 17:11:09 +00001700 Loc, Range, DeclarationName(),
1701 BasePath);
Douglas Gregor36d1b142009-10-06 17:59:45 +00001702}
1703
1704
1705/// @brief Builds a string representing ambiguous paths from a
1706/// specific derived class to different subobjects of the same base
1707/// class.
1708///
1709/// This function builds a string that can be used in error messages
1710/// to show the different paths that one can take through the
1711/// inheritance hierarchy to go from the derived class to different
1712/// subobjects of a base class. The result looks something like this:
1713/// @code
1714/// struct D -> struct B -> struct A
1715/// struct D -> struct C -> struct A
1716/// @endcode
1717std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1718 std::string PathDisplayStr;
1719 std::set<unsigned> DisplayedPaths;
1720 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1721 Path != Paths.end(); ++Path) {
1722 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1723 // We haven't displayed a path to this particular base
1724 // class subobject yet.
1725 PathDisplayStr += "\n ";
1726 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1727 for (CXXBasePath::const_iterator Element = Path->begin();
1728 Element != Path->end(); ++Element)
1729 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1730 }
1731 }
1732
1733 return PathDisplayStr;
1734}
1735
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001736//===----------------------------------------------------------------------===//
1737// C++ class member Handling
1738//===----------------------------------------------------------------------===//
1739
Abramo Bagnarad7340582010-06-05 05:09:32 +00001740/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00001741bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1742 SourceLocation ASLoc,
1743 SourceLocation ColonLoc,
1744 AttributeList *Attrs) {
Abramo Bagnarad7340582010-06-05 05:09:32 +00001745 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCall48871652010-08-21 09:40:31 +00001746 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnarad7340582010-06-05 05:09:32 +00001747 ASLoc, ColonLoc);
1748 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00001749 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnarad7340582010-06-05 05:09:32 +00001750}
1751
Richard Smith18f07db2012-08-06 03:25:17 +00001752/// CheckOverrideControl - Check C++11 override control semantics.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001753void Sema::CheckOverrideControl(NamedDecl *D) {
Richard Smith09b031f2012-09-06 18:32:18 +00001754 if (D->isInvalidDecl())
1755 return;
1756
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001757 // We only care about "override" and "final" declarations.
1758 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
1759 return;
Anders Carlssonfd835532011-01-20 05:57:14 +00001760
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001761 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlssonfa8e5d32011-01-20 06:33:26 +00001762
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001763 // We can't check dependent instance methods.
1764 if (MD && MD->isInstance() &&
1765 (MD->getParent()->hasAnyDependentBases() ||
1766 MD->getType()->isDependentType()))
1767 return;
1768
1769 if (MD && !MD->isVirtual()) {
1770 // If we have a non-virtual method, check if if hides a virtual method.
1771 // (In that case, it's most likely the method has the wrong type.)
1772 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
1773 FindHiddenVirtualMethods(MD, OverloadedMethods);
1774
1775 if (!OverloadedMethods.empty()) {
Richard Smith18f07db2012-08-06 03:25:17 +00001776 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1777 Diag(OA->getLocation(),
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001778 diag::override_keyword_hides_virtual_member_function)
1779 << "override" << (OverloadedMethods.size() > 1);
1780 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
Richard Smith18f07db2012-08-06 03:25:17 +00001781 Diag(FA->getLocation(),
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001782 diag::override_keyword_hides_virtual_member_function)
David Majnemera5433082013-10-18 00:33:31 +00001783 << (FA->isSpelledAsSealed() ? "sealed" : "final")
1784 << (OverloadedMethods.size() > 1);
Richard Smith18f07db2012-08-06 03:25:17 +00001785 }
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001786 NoteHiddenVirtualMethods(MD, OverloadedMethods);
1787 MD->setInvalidDecl();
1788 return;
1789 }
1790 // Fall through into the general case diagnostic.
1791 // FIXME: We might want to attempt typo correction here.
1792 }
1793
1794 if (!MD || !MD->isVirtual()) {
1795 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1796 Diag(OA->getLocation(),
1797 diag::override_keyword_only_allowed_on_virtual_member_functions)
1798 << "override" << FixItHint::CreateRemoval(OA->getLocation());
1799 D->dropAttr<OverrideAttr>();
1800 }
1801 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1802 Diag(FA->getLocation(),
1803 diag::override_keyword_only_allowed_on_virtual_member_functions)
David Majnemera5433082013-10-18 00:33:31 +00001804 << (FA->isSpelledAsSealed() ? "sealed" : "final")
1805 << FixItHint::CreateRemoval(FA->getLocation());
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001806 D->dropAttr<FinalAttr>();
Richard Smith18f07db2012-08-06 03:25:17 +00001807 }
Anders Carlssonfd835532011-01-20 05:57:14 +00001808 return;
1809 }
Richard Smith18f07db2012-08-06 03:25:17 +00001810
Richard Smith18f07db2012-08-06 03:25:17 +00001811 // C++11 [class.virtual]p5:
1812 // If a virtual function is marked with the virt-specifier override and
1813 // does not override a member function of a base class, the program is
1814 // ill-formed.
1815 bool HasOverriddenMethods =
1816 MD->begin_overridden_methods() != MD->end_overridden_methods();
1817 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1818 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1819 << MD->getDeclName();
Anders Carlssonfd835532011-01-20 05:57:14 +00001820}
1821
Richard Smith18f07db2012-08-06 03:25:17 +00001822/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
Anders Carlsson3f610c72011-01-20 16:25:36 +00001823/// function overrides a virtual member function marked 'final', according to
Richard Smith18f07db2012-08-06 03:25:17 +00001824/// C++11 [class.virtual]p4.
Anders Carlsson3f610c72011-01-20 16:25:36 +00001825bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1826 const CXXMethodDecl *Old) {
David Majnemera5433082013-10-18 00:33:31 +00001827 FinalAttr *FA = Old->getAttr<FinalAttr>();
1828 if (!FA)
Anders Carlsson19588aa2011-01-23 21:07:30 +00001829 return false;
1830
1831 Diag(New->getLocation(), diag::err_final_function_overridden)
David Majnemera5433082013-10-18 00:33:31 +00001832 << New->getDeclName()
1833 << FA->isSpelledAsSealed();
Anders Carlsson19588aa2011-01-23 21:07:30 +00001834 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1835 return true;
Anders Carlsson3f610c72011-01-20 16:25:36 +00001836}
1837
Daniel Jasper0baec5492012-06-06 08:32:04 +00001838static bool InitializationHasSideEffects(const FieldDecl &FD) {
Richard Smith0a8cfc72012-08-07 21:30:42 +00001839 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1840 // FIXME: Destruction of ObjC lifetime types has side-effects.
1841 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1842 return !RD->isCompleteDefinition() ||
1843 !RD->hasTrivialDefaultConstructor() ||
1844 !RD->hasTrivialDestructor();
Daniel Jasper0baec5492012-06-06 08:32:04 +00001845 return false;
1846}
1847
John McCall5e77d762013-04-16 07:28:30 +00001848static AttributeList *getMSPropertyAttr(AttributeList *list) {
1849 for (AttributeList* it = list; it != 0; it = it->getNext())
1850 if (it->isDeclspecPropertyAttribute())
1851 return it;
1852 return 0;
1853}
1854
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001855/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1856/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith938f40b2011-06-11 17:19:42 +00001857/// bitfield width if there is one, 'InitExpr' specifies the initializer if
Richard Smith2b013182012-06-10 03:12:00 +00001858/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1859/// present (but parsing it has been deferred).
Rafael Espindola0a67e2f2013-01-08 20:44:06 +00001860NamedDecl *
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001861Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +00001862 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieu2bd04012011-09-09 02:00:50 +00001863 Expr *BW, const VirtSpecifiers &VS,
Richard Smith2b013182012-06-10 03:12:00 +00001864 InClassInitStyle InitStyle) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001865 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001866 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1867 DeclarationName Name = NameInfo.getName();
1868 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor23ab7452010-11-09 03:31:16 +00001869
1870 // For anonymous bitfields, the location should point to the type.
1871 if (Loc.isInvalid())
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001872 Loc = D.getLocStart();
Douglas Gregor23ab7452010-11-09 03:31:16 +00001873
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001874 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001875
John McCallb1cd7da2010-06-04 08:34:12 +00001876 assert(isa<CXXRecordDecl>(CurContext));
John McCall07e91c02009-08-06 02:15:43 +00001877 assert(!DS.isFriendSpecified());
1878
Richard Smithcfcdf3a2011-06-25 02:28:38 +00001879 bool isFunc = D.isDeclarationOfFunction();
John McCallb1cd7da2010-06-04 08:34:12 +00001880
John McCalldb632ac2012-09-25 07:32:39 +00001881 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
1882 // The Microsoft extension __interface only permits public member functions
1883 // and prohibits constructors, destructors, operators, non-public member
1884 // functions, static methods and data members.
1885 unsigned InvalidDecl;
1886 bool ShowDeclName = true;
1887 if (!isFunc)
1888 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
1889 else if (AS != AS_public)
1890 InvalidDecl = 2;
1891 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
1892 InvalidDecl = 3;
1893 else switch (Name.getNameKind()) {
1894 case DeclarationName::CXXConstructorName:
1895 InvalidDecl = 4;
1896 ShowDeclName = false;
1897 break;
1898
1899 case DeclarationName::CXXDestructorName:
1900 InvalidDecl = 5;
1901 ShowDeclName = false;
1902 break;
1903
1904 case DeclarationName::CXXOperatorName:
1905 case DeclarationName::CXXConversionFunctionName:
1906 InvalidDecl = 6;
1907 break;
1908
1909 default:
1910 InvalidDecl = 0;
1911 break;
1912 }
1913
1914 if (InvalidDecl) {
1915 if (ShowDeclName)
1916 Diag(Loc, diag::err_invalid_member_in_interface)
1917 << (InvalidDecl-1) << Name;
1918 else
1919 Diag(Loc, diag::err_invalid_member_in_interface)
1920 << (InvalidDecl-1) << "";
1921 return 0;
1922 }
1923 }
1924
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001925 // C++ 9.2p6: A member shall not be declared to have automatic storage
1926 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001927 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1928 // data members and cannot be applied to names declared const or static,
1929 // and cannot be applied to reference members.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001930 switch (DS.getStorageClassSpec()) {
Richard Smithb4a9e862013-04-12 22:46:28 +00001931 case DeclSpec::SCS_unspecified:
1932 case DeclSpec::SCS_typedef:
1933 case DeclSpec::SCS_static:
1934 break;
1935 case DeclSpec::SCS_mutable:
1936 if (isFunc) {
1937 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +00001938
Richard Smithb4a9e862013-04-12 22:46:28 +00001939 // FIXME: It would be nicer if the keyword was ignored only for this
1940 // declarator. Otherwise we could get follow-up errors.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001941 D.getMutableDeclSpec().ClearStorageClassSpecs();
Richard Smithb4a9e862013-04-12 22:46:28 +00001942 }
1943 break;
1944 default:
1945 Diag(DS.getStorageClassSpecLoc(),
1946 diag::err_storageclass_invalid_for_member);
1947 D.getMutableDeclSpec().ClearStorageClassSpecs();
1948 break;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001949 }
1950
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001951 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1952 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +00001953 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001954
David Blaikie35506f82013-01-30 01:22:18 +00001955 if (DS.isConstexprSpecified() && isInstField) {
1956 SemaDiagnosticBuilder B =
1957 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
1958 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
1959 if (InitStyle == ICIS_NoInit) {
1960 B << 0 << 0 << FixItHint::CreateReplacement(ConstexprLoc, "const");
1961 D.getMutableDeclSpec().ClearConstexprSpec();
1962 const char *PrevSpec;
1963 unsigned DiagID;
1964 bool Failed = D.getMutableDeclSpec().SetTypeQual(DeclSpec::TQ_const, ConstexprLoc,
1965 PrevSpec, DiagID, getLangOpts());
Matt Beaumont-Gayefc270d2013-01-31 00:08:03 +00001966 (void)Failed;
David Blaikie35506f82013-01-30 01:22:18 +00001967 assert(!Failed && "Making a constexpr member const shouldn't fail");
1968 } else {
1969 B << 1;
1970 const char *PrevSpec;
1971 unsigned DiagID;
David Blaikie35506f82013-01-30 01:22:18 +00001972 if (D.getMutableDeclSpec().SetStorageClassSpec(
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001973 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
1974 Context.getPrintingPolicy())) {
Matt Beaumont-Gayefc270d2013-01-31 00:08:03 +00001975 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
David Blaikie35506f82013-01-30 01:22:18 +00001976 "This is the only DeclSpec that should fail to be applied");
1977 B << 1;
1978 } else {
1979 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
1980 isInstField = false;
1981 }
1982 }
1983 }
1984
Rafael Espindola0a67e2f2013-01-08 20:44:06 +00001985 NamedDecl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +00001986 if (isInstField) {
Douglas Gregora007d362010-10-13 22:19:53 +00001987 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorbb64afc2011-10-09 18:55:59 +00001988
1989 // Data members must have identifiers for names.
Benjamin Kramer365082d2012-05-19 16:34:46 +00001990 if (!Name.isIdentifier()) {
Douglas Gregorbb64afc2011-10-09 18:55:59 +00001991 Diag(Loc, diag::err_bad_variable_name)
1992 << Name;
1993 return 0;
1994 }
Douglas Gregor7c26c042011-09-21 14:40:46 +00001995
Benjamin Kramer365082d2012-05-19 16:34:46 +00001996 IdentifierInfo *II = Name.getAsIdentifierInfo();
1997
Douglas Gregor7c26c042011-09-21 14:40:46 +00001998 // Member field could not be with "template" keyword.
1999 // So TemplateParameterLists should be empty in this case.
2000 if (TemplateParameterLists.size()) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002001 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
Douglas Gregor7c26c042011-09-21 14:40:46 +00002002 if (TemplateParams->size()) {
2003 // There is no such thing as a member field template.
2004 Diag(D.getIdentifierLoc(), diag::err_template_member)
2005 << II
2006 << SourceRange(TemplateParams->getTemplateLoc(),
2007 TemplateParams->getRAngleLoc());
2008 } else {
2009 // There is an extraneous 'template<>' for this member.
2010 Diag(TemplateParams->getTemplateLoc(),
2011 diag::err_template_member_noparams)
2012 << II
2013 << SourceRange(TemplateParams->getTemplateLoc(),
2014 TemplateParams->getRAngleLoc());
2015 }
2016 return 0;
2017 }
2018
Douglas Gregora007d362010-10-13 22:19:53 +00002019 if (SS.isSet() && !SS.isInvalid()) {
2020 // The user provided a superfluous scope specifier inside a class
2021 // definition:
2022 //
2023 // class X {
2024 // int X::member;
2025 // };
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00002026 if (DeclContext *DC = computeDeclContext(SS, false))
2027 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
Douglas Gregora007d362010-10-13 22:19:53 +00002028 else
2029 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
2030 << Name << SS.getRange();
Douglas Gregorc3ae7c32011-11-01 22:13:30 +00002031
Douglas Gregora007d362010-10-13 22:19:53 +00002032 SS.clear();
2033 }
Douglas Gregor7c26c042011-09-21 14:40:46 +00002034
John McCall5e77d762013-04-16 07:28:30 +00002035 AttributeList *MSPropertyAttr =
2036 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002037 if (MSPropertyAttr) {
2038 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2039 BitWidth, InitStyle, AS, MSPropertyAttr);
2040 if (!Member)
2041 return 0;
2042 isInstField = false;
2043 } else {
2044 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2045 BitWidth, InitStyle, AS);
2046 assert(Member && "HandleField never returns null");
2047 }
2048 } else {
2049 assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static);
2050
2051 Member = HandleDeclarator(S, D, TemplateParameterLists);
2052 if (!Member)
2053 return 0;
2054
2055 // Non-instance-fields can't have a bitfield.
2056 if (BitWidth) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00002057 if (Member->isInvalidDecl()) {
2058 // don't emit another diagnostic.
Douglas Gregor212cab32009-03-11 20:22:50 +00002059 } else if (isa<VarDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00002060 // C++ 9.6p3: A bit-field shall not be a static member.
2061 // "static member 'A' cannot be a bit-field"
2062 Diag(Loc, diag::err_static_not_bitfield)
2063 << Name << BitWidth->getSourceRange();
2064 } else if (isa<TypedefDecl>(Member)) {
2065 // "typedef member 'x' cannot be a bit-field"
2066 Diag(Loc, diag::err_typedef_not_bitfield)
2067 << Name << BitWidth->getSourceRange();
2068 } else {
2069 // A function typedef ("typedef int f(); f a;").
2070 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
2071 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +00002072 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +00002073 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +00002074 }
Mike Stump11289f42009-09-09 15:08:12 +00002075
Chris Lattnerd26760a2009-03-05 23:01:03 +00002076 BitWidth = 0;
2077 Member->setInvalidDecl();
2078 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +00002079
2080 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +00002081
Larisse Voufo39a1e502013-08-06 01:03:05 +00002082 // If we have declared a member function template or static data member
2083 // template, set the access of the templated declaration as well.
Douglas Gregor3447e762009-08-20 22:52:58 +00002084 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
2085 FunTmpl->getTemplatedDecl()->setAccess(AS);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002086 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
2087 VarTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +00002088 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002089
Richard Smith18f07db2012-08-06 03:25:17 +00002090 if (VS.isOverrideSpecified())
Aaron Ballman36a53502014-01-16 13:03:14 +00002091 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
Richard Smith18f07db2012-08-06 03:25:17 +00002092 if (VS.isFinalSpecified())
David Majnemera5433082013-10-18 00:33:31 +00002093 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
2094 VS.isFinalSpelledSealed()));
Anders Carlssonfd835532011-01-20 05:57:14 +00002095
Douglas Gregorf2f08062011-03-08 17:10:18 +00002096 if (VS.getLastLocation().isValid()) {
2097 // Update the end location of a method that has a virt-specifiers.
2098 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
2099 MD->setRangeEnd(VS.getLastLocation());
2100 }
Richard Smith18f07db2012-08-06 03:25:17 +00002101
Anders Carlssonc87f8612011-01-20 06:29:02 +00002102 CheckOverrideControl(Member);
Anders Carlssonfd835532011-01-20 05:57:14 +00002103
Douglas Gregor92751d42008-11-17 22:58:34 +00002104 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002105
Daniel Jasper0baec5492012-06-06 08:32:04 +00002106 if (isInstField) {
2107 FieldDecl *FD = cast<FieldDecl>(Member);
2108 FieldCollector->Add(FD);
2109
2110 if (Diags.getDiagnosticLevel(diag::warn_unused_private_field,
2111 FD->getLocation())
2112 != DiagnosticsEngine::Ignored) {
2113 // Remember all explicit private FieldDecls that have a name, no side
2114 // effects and are not part of a dependent type declaration.
2115 if (!FD->isImplicit() && FD->getDeclName() &&
2116 FD->getAccess() == AS_private &&
Daniel Jasper429c1342012-06-13 18:31:09 +00002117 !FD->hasAttr<UnusedAttr>() &&
Richard Smith0a8cfc72012-08-07 21:30:42 +00002118 !FD->getParent()->isDependentContext() &&
Daniel Jasper0baec5492012-06-06 08:32:04 +00002119 !InitializationHasSideEffects(*FD))
2120 UnusedPrivateFields.insert(FD);
2121 }
2122 }
2123
John McCall48871652010-08-21 09:40:31 +00002124 return Member;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002125}
2126
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002127namespace {
2128 class UninitializedFieldVisitor
2129 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2130 Sema &S;
Richard Trieuef64e942013-10-25 00:56:00 +00002131 // List of Decls to generate a warning on. Also remove Decls that become
2132 // initialized.
Richard Trieu406e65c2013-09-20 03:03:06 +00002133 llvm::SmallPtrSet<ValueDecl*, 4> &Decls;
Richard Trieu406e65c2013-09-20 03:03:06 +00002134 // If non-null, add a note to the warning pointing back to the constructor.
2135 const CXXConstructorDecl *Constructor;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002136 public:
2137 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
Richard Trieuef64e942013-10-25 00:56:00 +00002138 UninitializedFieldVisitor(Sema &S,
Richard Trieu406e65c2013-09-20 03:03:06 +00002139 llvm::SmallPtrSet<ValueDecl*, 4> &Decls,
Richard Trieu406e65c2013-09-20 03:03:06 +00002140 const CXXConstructorDecl *Constructor)
Richard Trieuef64e942013-10-25 00:56:00 +00002141 : Inherited(S.Context), S(S), Decls(Decls),
2142 Constructor(Constructor) { }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002143
Richard Trieufd687772013-09-16 20:46:50 +00002144 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly) {
Richard Trieu1bc22c12013-09-13 03:20:53 +00002145 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
2146 return;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002147
Richard Trieu1bc22c12013-09-13 03:20:53 +00002148 // FieldME is the inner-most MemberExpr that is not an anonymous struct
2149 // or union.
2150 MemberExpr *FieldME = ME;
2151
2152 Expr *Base = ME;
2153 while (isa<MemberExpr>(Base)) {
2154 ME = cast<MemberExpr>(Base);
2155
2156 if (isa<VarDecl>(ME->getMemberDecl()))
2157 return;
2158
2159 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2160 if (!FD->isAnonymousStructOrUnion())
2161 FieldME = ME;
2162
2163 Base = ME->getBase();
2164 }
2165
Richard Trieufd687772013-09-16 20:46:50 +00002166 if (!isa<CXXThisExpr>(Base))
2167 return;
2168
Richard Trieu406e65c2013-09-20 03:03:06 +00002169 ValueDecl* FoundVD = FieldME->getMemberDecl();
2170
Richard Trieuef64e942013-10-25 00:56:00 +00002171 if (!Decls.count(FoundVD))
Richard Trieu406e65c2013-09-20 03:03:06 +00002172 return;
2173
Richard Trieuef64e942013-10-25 00:56:00 +00002174 const bool IsReference = FoundVD->getType()->isReferenceType();
Richard Trieu406e65c2013-09-20 03:03:06 +00002175
Richard Trieuef64e942013-10-25 00:56:00 +00002176 // Prevent double warnings on use of unbounded references.
2177 if (IsReference != CheckReferenceOnly)
2178 return;
2179
2180 unsigned diag = IsReference
2181 ? diag::warn_reference_field_is_uninit
2182 : diag::warn_field_is_uninit;
2183 S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
2184 if (Constructor)
2185 S.Diag(Constructor->getLocation(),
2186 diag::note_uninit_in_this_constructor)
2187 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
2188
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002189 }
2190
2191 void HandleValue(Expr *E) {
2192 E = E->IgnoreParens();
2193
2194 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
Richard Trieufd687772013-09-16 20:46:50 +00002195 HandleMemberExpr(ME, false /*CheckReferenceOnly*/);
Nick Lewyckyc363afb2012-11-15 08:19:20 +00002196 return;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002197 }
2198
2199 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2200 HandleValue(CO->getTrueExpr());
2201 HandleValue(CO->getFalseExpr());
2202 return;
2203 }
2204
2205 if (BinaryConditionalOperator *BCO =
2206 dyn_cast<BinaryConditionalOperator>(E)) {
2207 HandleValue(BCO->getCommon());
2208 HandleValue(BCO->getFalseExpr());
2209 return;
2210 }
2211
2212 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2213 switch (BO->getOpcode()) {
2214 default:
2215 return;
2216 case(BO_PtrMemD):
2217 case(BO_PtrMemI):
2218 HandleValue(BO->getLHS());
2219 return;
2220 case(BO_Comma):
2221 HandleValue(BO->getRHS());
2222 return;
2223 }
2224 }
2225 }
2226
Richard Trieu1bc22c12013-09-13 03:20:53 +00002227 void VisitMemberExpr(MemberExpr *ME) {
Richard Trieuef64e942013-10-25 00:56:00 +00002228 // All uses of unbounded reference fields will warn.
Richard Trieufd687772013-09-16 20:46:50 +00002229 HandleMemberExpr(ME, true /*CheckReferenceOnly*/);
Richard Trieu1bc22c12013-09-13 03:20:53 +00002230
2231 Inherited::VisitMemberExpr(ME);
2232 }
2233
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002234 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
2235 if (E->getCastKind() == CK_LValueToRValue)
2236 HandleValue(E->getSubExpr());
2237
2238 Inherited::VisitImplicitCastExpr(E);
2239 }
2240
Richard Trieu1bc22c12013-09-13 03:20:53 +00002241 void VisitCXXConstructExpr(CXXConstructExpr *E) {
Richard Trieu406e65c2013-09-20 03:03:06 +00002242 if (E->getConstructor()->isCopyConstructor())
Richard Trieu1bc22c12013-09-13 03:20:53 +00002243 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(E->getArg(0)))
2244 if (ICE->getCastKind() == CK_NoOp)
2245 if (MemberExpr *ME = dyn_cast<MemberExpr>(ICE->getSubExpr()))
Richard Trieufd687772013-09-16 20:46:50 +00002246 HandleMemberExpr(ME, false /*CheckReferenceOnly*/);
Richard Trieu1bc22c12013-09-13 03:20:53 +00002247
2248 Inherited::VisitCXXConstructExpr(E);
2249 }
2250
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002251 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2252 Expr *Callee = E->getCallee();
2253 if (isa<MemberExpr>(Callee))
2254 HandleValue(Callee);
2255
2256 Inherited::VisitCXXMemberCallExpr(E);
2257 }
Richard Trieu406e65c2013-09-20 03:03:06 +00002258
2259 void VisitBinaryOperator(BinaryOperator *E) {
2260 // If a field assignment is detected, remove the field from the
2261 // uninitiailized field set.
2262 if (E->getOpcode() == BO_Assign)
2263 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
2264 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
Richard Trieuef64e942013-10-25 00:56:00 +00002265 if (!FD->getType()->isReferenceType())
2266 Decls.erase(FD);
Richard Trieu406e65c2013-09-20 03:03:06 +00002267
2268 Inherited::VisitBinaryOperator(E);
2269 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002270 };
Richard Trieu406e65c2013-09-20 03:03:06 +00002271 static void CheckInitExprContainsUninitializedFields(
Richard Trieuef64e942013-10-25 00:56:00 +00002272 Sema &S, Expr *E, llvm::SmallPtrSet<ValueDecl*, 4> &Decls,
2273 const CXXConstructorDecl *Constructor) {
2274 if (Decls.size() == 0)
Richard Trieu406e65c2013-09-20 03:03:06 +00002275 return;
2276
Richard Trieuef64e942013-10-25 00:56:00 +00002277 if (!E)
2278 return;
2279
2280 if (CXXDefaultInitExpr *Default = dyn_cast<CXXDefaultInitExpr>(E)) {
2281 E = Default->getExpr();
2282 if (!E)
2283 return;
2284 // In class initializers will point to the constructor.
2285 UninitializedFieldVisitor(S, Decls, Constructor).Visit(E);
2286 } else {
2287 UninitializedFieldVisitor(S, Decls, 0).Visit(E);
2288 }
2289 }
2290
2291 // Diagnose value-uses of fields to initialize themselves, e.g.
2292 // foo(foo)
2293 // where foo is not also a parameter to the constructor.
2294 // Also diagnose across field uninitialized use such as
2295 // x(y), y(x)
2296 // TODO: implement -Wuninitialized and fold this into that framework.
2297 static void DiagnoseUninitializedFields(
2298 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
2299
2300 if (SemaRef.getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit,
2301 Constructor->getLocation())
2302 == DiagnosticsEngine::Ignored) {
2303 return;
2304 }
2305
2306 if (Constructor->isInvalidDecl())
2307 return;
2308
2309 const CXXRecordDecl *RD = Constructor->getParent();
2310
2311 // Holds fields that are uninitialized.
2312 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
2313
2314 // At the beginning, all fields are uninitialized.
Aaron Ballman629afae2014-03-07 19:56:05 +00002315 for (auto *I : RD->decls()) {
2316 if (auto *FD = dyn_cast<FieldDecl>(I)) {
Richard Trieuef64e942013-10-25 00:56:00 +00002317 UninitializedFields.insert(FD);
Aaron Ballman629afae2014-03-07 19:56:05 +00002318 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
Richard Trieuef64e942013-10-25 00:56:00 +00002319 UninitializedFields.insert(IFD->getAnonField());
2320 }
2321 }
2322
Aaron Ballman0ad78302014-03-13 17:34:31 +00002323 for (const auto *FieldInit : Constructor->inits()) {
2324 Expr *InitExpr = FieldInit->getInit();
Richard Trieuef64e942013-10-25 00:56:00 +00002325
2326 CheckInitExprContainsUninitializedFields(
2327 SemaRef, InitExpr, UninitializedFields, Constructor);
2328
Aaron Ballman0ad78302014-03-13 17:34:31 +00002329 if (FieldDecl *Field = FieldInit->getAnyMember())
Richard Trieuef64e942013-10-25 00:56:00 +00002330 UninitializedFields.erase(Field);
2331 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002332 }
2333} // namespace
2334
Richard Smith74108172014-01-17 03:11:34 +00002335/// \brief Enter a new C++ default initializer scope. After calling this, the
2336/// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
2337/// parsing or instantiating the initializer failed.
2338void Sema::ActOnStartCXXInClassMemberInitializer() {
2339 // Create a synthetic function scope to represent the call to the constructor
2340 // that notionally surrounds a use of this initializer.
2341 PushFunctionScope();
2342}
2343
2344/// \brief This is invoked after parsing an in-class initializer for a
2345/// non-static C++ class member, and after instantiating an in-class initializer
2346/// in a class template. Such actions are deferred until the class is complete.
2347void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
2348 SourceLocation InitLoc,
2349 Expr *InitExpr) {
2350 // Pop the notional constructor scope we created earlier.
2351 PopFunctionScopeInfo(0, D);
2352
Richard Smith938f40b2011-06-11 17:19:42 +00002353 FieldDecl *FD = cast<FieldDecl>(D);
Richard Smith2b013182012-06-10 03:12:00 +00002354 assert(FD->getInClassInitStyle() != ICIS_NoInit &&
2355 "must set init style when field is created");
Richard Smith938f40b2011-06-11 17:19:42 +00002356
2357 if (!InitExpr) {
2358 FD->setInvalidDecl();
2359 FD->removeInClassInitializer();
2360 return;
2361 }
2362
Peter Collingbourne9f58d7b2011-10-23 18:59:44 +00002363 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
2364 FD->setInvalidDecl();
2365 FD->removeInClassInitializer();
2366 return;
2367 }
2368
Richard Smith938f40b2011-06-11 17:19:42 +00002369 ExprResult Init = InitExpr;
Richard Smithd59b8322012-12-19 01:39:02 +00002370 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
Sebastian Redleef474c2012-02-22 10:50:08 +00002371 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
Richard Smith2b013182012-06-10 03:12:00 +00002372 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
Sebastian Redleef474c2012-02-22 10:50:08 +00002373 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
Richard Smith2b013182012-06-10 03:12:00 +00002374 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002375 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2376 Init = Seq.Perform(*this, Entity, Kind, InitExpr);
Richard Smith938f40b2011-06-11 17:19:42 +00002377 if (Init.isInvalid()) {
2378 FD->setInvalidDecl();
2379 return;
2380 }
Richard Smith938f40b2011-06-11 17:19:42 +00002381 }
2382
Richard Smith945f8d32013-01-14 22:39:08 +00002383 // C++11 [class.base.init]p7:
Richard Smith938f40b2011-06-11 17:19:42 +00002384 // The initialization of each base and member constitutes a
2385 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00002386 Init = ActOnFinishFullExpr(Init.take(), InitLoc);
Richard Smith938f40b2011-06-11 17:19:42 +00002387 if (Init.isInvalid()) {
2388 FD->setInvalidDecl();
2389 return;
2390 }
2391
2392 InitExpr = Init.release();
2393
2394 FD->setInClassInitializer(InitExpr);
2395}
2396
Douglas Gregor15e77a22009-12-31 09:10:24 +00002397/// \brief Find the direct and/or virtual base specifiers that
2398/// correspond to the given base type, for use in base initialization
2399/// within a constructor.
2400static bool FindBaseInitializer(Sema &SemaRef,
2401 CXXRecordDecl *ClassDecl,
2402 QualType BaseType,
2403 const CXXBaseSpecifier *&DirectBaseSpec,
2404 const CXXBaseSpecifier *&VirtualBaseSpec) {
2405 // First, check for a direct base class.
2406 DirectBaseSpec = 0;
Aaron Ballman574705e2014-03-13 15:41:46 +00002407 for (const auto &Base : ClassDecl->bases()) {
2408 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00002409 // We found a direct base of this type. That's what we're
2410 // initializing.
Aaron Ballman574705e2014-03-13 15:41:46 +00002411 DirectBaseSpec = &Base;
Douglas Gregor15e77a22009-12-31 09:10:24 +00002412 break;
2413 }
2414 }
2415
2416 // Check for a virtual base class.
2417 // FIXME: We might be able to short-circuit this if we know in advance that
2418 // there are no virtual bases.
2419 VirtualBaseSpec = 0;
2420 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2421 // We haven't found a base yet; search the class hierarchy for a
2422 // virtual base class.
2423 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2424 /*DetectVirtual=*/false);
2425 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2426 BaseType, Paths)) {
2427 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2428 Path != Paths.end(); ++Path) {
2429 if (Path->back().Base->isVirtual()) {
2430 VirtualBaseSpec = Path->back().Base;
2431 break;
2432 }
2433 }
2434 }
2435 }
2436
2437 return DirectBaseSpec || VirtualBaseSpec;
2438}
2439
Sebastian Redla74948d2011-09-24 17:48:25 +00002440/// \brief Handle a C++ member initializer using braced-init-list syntax.
2441MemInitResult
2442Sema::ActOnMemInitializer(Decl *ConstructorD,
2443 Scope *S,
2444 CXXScopeSpec &SS,
2445 IdentifierInfo *MemberOrBase,
2446 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00002447 const DeclSpec &DS,
Sebastian Redla74948d2011-09-24 17:48:25 +00002448 SourceLocation IdLoc,
2449 Expr *InitList,
2450 SourceLocation EllipsisLoc) {
2451 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redla9351792012-02-11 23:51:47 +00002452 DS, IdLoc, InitList,
David Blaikie186a8892012-01-24 06:03:59 +00002453 EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002454}
2455
2456/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallfaf5fb42010-08-26 23:41:50 +00002457MemInitResult
John McCall48871652010-08-21 09:40:31 +00002458Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +00002459 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00002460 CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +00002461 IdentifierInfo *MemberOrBase,
John McCallba7bf592010-08-24 05:47:05 +00002462 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00002463 const DeclSpec &DS,
Douglas Gregore8381c02008-11-05 04:29:56 +00002464 SourceLocation IdLoc,
2465 SourceLocation LParenLoc,
Dmitri Gribenko139474d2013-05-09 23:51:52 +00002466 ArrayRef<Expr *> Args,
Douglas Gregor44e7df62011-01-04 00:32:56 +00002467 SourceLocation RParenLoc,
2468 SourceLocation EllipsisLoc) {
Benjamin Kramerc215e762012-08-24 11:54:20 +00002469 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
Dmitri Gribenko139474d2013-05-09 23:51:52 +00002470 Args, RParenLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002471 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redla9351792012-02-11 23:51:47 +00002472 DS, IdLoc, List, EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002473}
2474
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002475namespace {
2476
Kaelyn Uhrain8811b392012-01-11 21:17:51 +00002477// Callback to only accept typo corrections that can be a valid C++ member
2478// intializer: either a non-static field member or a base class.
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002479class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002480public:
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002481 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2482 : ClassDecl(ClassDecl) {}
2483
Craig Toppera798a9d2014-03-02 09:32:10 +00002484 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002485 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2486 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2487 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002488 return isa<TypeDecl>(ND);
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002489 }
2490 return false;
2491 }
2492
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002493private:
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002494 CXXRecordDecl *ClassDecl;
2495};
2496
2497}
2498
Sebastian Redla74948d2011-09-24 17:48:25 +00002499/// \brief Handle a C++ member initializer.
2500MemInitResult
2501Sema::BuildMemInitializer(Decl *ConstructorD,
2502 Scope *S,
2503 CXXScopeSpec &SS,
2504 IdentifierInfo *MemberOrBase,
2505 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00002506 const DeclSpec &DS,
Sebastian Redla74948d2011-09-24 17:48:25 +00002507 SourceLocation IdLoc,
Sebastian Redla9351792012-02-11 23:51:47 +00002508 Expr *Init,
Sebastian Redla74948d2011-09-24 17:48:25 +00002509 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002510 if (!ConstructorD)
2511 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002512
Douglas Gregorc8c277a2009-08-24 11:57:43 +00002513 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +00002514
2515 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002516 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregore8381c02008-11-05 04:29:56 +00002517 if (!Constructor) {
2518 // The user wrote a constructor initializer on a function that is
2519 // not a C++ constructor. Ignore the error for now, because we may
2520 // have more member initializers coming; we'll diagnose it just
2521 // once in ActOnMemInitializers.
2522 return true;
2523 }
2524
2525 CXXRecordDecl *ClassDecl = Constructor->getParent();
2526
2527 // C++ [class.base.init]p2:
2528 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky9331ed82010-11-20 01:29:55 +00002529 // constructor's class and, if not found in that scope, are looked
2530 // up in the scope containing the constructor's definition.
2531 // [Note: if the constructor's class contains a member with the
2532 // same name as a direct or virtual base class of the class, a
2533 // mem-initializer-id naming the member or base class and composed
2534 // of a single identifier refers to the class member. A
Douglas Gregore8381c02008-11-05 04:29:56 +00002535 // mem-initializer-id for the hidden base class may be specified
2536 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00002537 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00002538 // Look for a member, first.
Mike Stump11289f42009-09-09 15:08:12 +00002539 DeclContext::lookup_result Result
Fariborz Jahanian302bb662009-06-30 23:26:25 +00002540 = ClassDecl->lookup(MemberOrBase);
David Blaikieff7d47a2012-12-19 00:45:41 +00002541 if (!Result.empty()) {
Peter Collingbourne05156e32011-10-23 18:59:37 +00002542 ValueDecl *Member;
David Blaikieff7d47a2012-12-19 00:45:41 +00002543 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2544 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
Douglas Gregor44e7df62011-01-04 00:32:56 +00002545 if (EllipsisLoc.isValid())
2546 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redla9351792012-02-11 23:51:47 +00002547 << MemberOrBase
2548 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redla74948d2011-09-24 17:48:25 +00002549
Sebastian Redla9351792012-02-11 23:51:47 +00002550 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00002551 }
Francois Pichetd583da02010-12-04 09:14:42 +00002552 }
Douglas Gregore8381c02008-11-05 04:29:56 +00002553 }
Douglas Gregore8381c02008-11-05 04:29:56 +00002554 // It didn't name a member, so see if it names a class.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00002555 QualType BaseType;
John McCallbcd03502009-12-07 02:54:59 +00002556 TypeSourceInfo *TInfo = 0;
John McCallb5a0d312009-12-21 10:41:20 +00002557
2558 if (TemplateTypeTy) {
John McCallbcd03502009-12-07 02:54:59 +00002559 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikie186a8892012-01-24 06:03:59 +00002560 } else if (DS.getTypeSpecType() == TST_decltype) {
2561 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCallb5a0d312009-12-21 10:41:20 +00002562 } else {
2563 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2564 LookupParsedName(R, S, &SS);
2565
2566 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2567 if (!TyD) {
2568 if (R.isAmbiguous()) return true;
2569
John McCallda6841b2010-04-09 19:01:14 +00002570 // We don't want access-control diagnostics here.
2571 R.suppressDiagnostics();
2572
Douglas Gregora3b624a2010-01-19 06:46:48 +00002573 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2574 bool NotUnknownSpecialization = false;
2575 DeclContext *DC = computeDeclContext(SS, false);
2576 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2577 NotUnknownSpecialization = !Record->hasAnyDependentBases();
2578
2579 if (!NotUnknownSpecialization) {
2580 // When the scope specifier can refer to a member of an unknown
2581 // specialization, we take it as a type name.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00002582 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2583 SS.getWithLocInContext(Context),
2584 *MemberOrBase, IdLoc);
Douglas Gregor281c4862010-03-07 23:26:22 +00002585 if (BaseType.isNull())
2586 return true;
2587
Douglas Gregora3b624a2010-01-19 06:46:48 +00002588 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00002589 R.setLookupName(MemberOrBase);
Douglas Gregora3b624a2010-01-19 06:46:48 +00002590 }
2591 }
2592
Douglas Gregor15e77a22009-12-31 09:10:24 +00002593 // If no results were found, try to correct typos.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002594 TypoCorrection Corr;
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002595 MemInitializerValidatorCCC Validator(ClassDecl);
Douglas Gregora3b624a2010-01-19 06:46:48 +00002596 if (R.empty() && BaseType.isNull() &&
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002597 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00002598 Validator, ClassDecl))) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002599 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002600 // We have found a non-static data member with a similar
2601 // name to what was typed; complain and initialize that
2602 // member.
Richard Smithf9b15102013-08-17 00:46:16 +00002603 diagnoseTypo(Corr,
2604 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2605 << MemberOrBase << true);
Sebastian Redla9351792012-02-11 23:51:47 +00002606 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002607 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00002608 const CXXBaseSpecifier *DirectBaseSpec;
2609 const CXXBaseSpecifier *VirtualBaseSpec;
2610 if (FindBaseInitializer(*this, ClassDecl,
2611 Context.getTypeDeclType(Type),
2612 DirectBaseSpec, VirtualBaseSpec)) {
2613 // We have found a direct or virtual base class with a
2614 // similar name to what was typed; complain and initialize
2615 // that base class.
Richard Smithf9b15102013-08-17 00:46:16 +00002616 diagnoseTypo(Corr,
2617 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2618 << MemberOrBase << false,
2619 PDiag() /*Suppress note, we provide our own.*/);
Douglas Gregor43a08572010-01-07 00:26:25 +00002620
Richard Smithf9b15102013-08-17 00:46:16 +00002621 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
2622 : VirtualBaseSpec;
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002623 Diag(BaseSpec->getLocStart(),
Douglas Gregor43a08572010-01-07 00:26:25 +00002624 diag::note_base_class_specified_here)
2625 << BaseSpec->getType()
2626 << BaseSpec->getSourceRange();
2627
Douglas Gregor15e77a22009-12-31 09:10:24 +00002628 TyD = Type;
2629 }
2630 }
2631 }
2632
Douglas Gregora3b624a2010-01-19 06:46:48 +00002633 if (!TyD && BaseType.isNull()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00002634 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redla9351792012-02-11 23:51:47 +00002635 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregor15e77a22009-12-31 09:10:24 +00002636 return true;
2637 }
John McCallb5a0d312009-12-21 10:41:20 +00002638 }
2639
Douglas Gregora3b624a2010-01-19 06:46:48 +00002640 if (BaseType.isNull()) {
2641 BaseType = Context.getTypeDeclType(TyD);
Aaron Ballman4a979672014-01-03 13:56:08 +00002642 if (SS.isSet())
Douglas Gregora3b624a2010-01-19 06:46:48 +00002643 // FIXME: preserve source range information
Aaron Ballman4a979672014-01-03 13:56:08 +00002644 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
2645 BaseType);
John McCallb5a0d312009-12-21 10:41:20 +00002646 }
2647 }
Mike Stump11289f42009-09-09 15:08:12 +00002648
John McCallbcd03502009-12-07 02:54:59 +00002649 if (!TInfo)
2650 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00002651
Sebastian Redla9351792012-02-11 23:51:47 +00002652 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00002653}
2654
Chandler Carruth599deef2011-09-03 01:14:15 +00002655/// Checks a member initializer expression for cases where reference (or
2656/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth599deef2011-09-03 01:14:15 +00002657static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2658 Expr *Init,
2659 SourceLocation IdLoc) {
2660 QualType MemberTy = Member->getType();
2661
2662 // We only handle pointers and references currently.
2663 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2664 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2665 return;
2666
2667 const bool IsPointer = MemberTy->isPointerType();
2668 if (IsPointer) {
2669 if (const UnaryOperator *Op
2670 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2671 // The only case we're worried about with pointers requires taking the
2672 // address.
2673 if (Op->getOpcode() != UO_AddrOf)
2674 return;
2675
2676 Init = Op->getSubExpr();
2677 } else {
2678 // We only handle address-of expression initializers for pointers.
2679 return;
2680 }
2681 }
2682
Richard Smithe3b28bc2013-06-12 21:51:50 +00002683 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
Chandler Carruthd551d4e2011-09-03 02:21:57 +00002684 // We only warn when referring to a non-reference parameter declaration.
2685 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2686 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth599deef2011-09-03 01:14:15 +00002687 return;
2688
2689 S.Diag(Init->getExprLoc(),
2690 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2691 : diag::warn_bind_ref_member_to_parameter)
2692 << Member << Parameter << Init->getSourceRange();
Chandler Carruthd551d4e2011-09-03 02:21:57 +00002693 } else {
2694 // Other initializers are fine.
2695 return;
Chandler Carruth599deef2011-09-03 01:14:15 +00002696 }
Chandler Carruthd551d4e2011-09-03 02:21:57 +00002697
2698 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2699 << (unsigned)IsPointer;
Chandler Carruth599deef2011-09-03 01:14:15 +00002700}
2701
John McCallfaf5fb42010-08-26 23:41:50 +00002702MemInitResult
Sebastian Redla9351792012-02-11 23:51:47 +00002703Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redla74948d2011-09-24 17:48:25 +00002704 SourceLocation IdLoc) {
Chandler Carruthd44c3102010-12-06 09:23:57 +00002705 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2706 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2707 assert((DirectMember || IndirectMember) &&
Francois Pichetd583da02010-12-04 09:14:42 +00002708 "Member must be a FieldDecl or IndirectFieldDecl");
2709
Sebastian Redla9351792012-02-11 23:51:47 +00002710 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbourne9f58d7b2011-10-23 18:59:44 +00002711 return true;
2712
Douglas Gregor266bb5f2010-11-05 22:21:31 +00002713 if (Member->isInvalidDecl())
2714 return true;
Chandler Carruthd44c3102010-12-06 09:23:57 +00002715
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002716 MultiExprArg Args;
Sebastian Redla9351792012-02-11 23:51:47 +00002717 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002718 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Richard Smithd59b8322012-12-19 01:39:02 +00002719 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002720 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Richard Smithd59b8322012-12-19 01:39:02 +00002721 } else {
2722 // Template instantiation doesn't reconstruct ParenListExprs for us.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002723 Args = Init;
Sebastian Redla9351792012-02-11 23:51:47 +00002724 }
Daniel Jasper0baec5492012-06-06 08:32:04 +00002725
Sebastian Redla9351792012-02-11 23:51:47 +00002726 SourceRange InitRange = Init->getSourceRange();
Eli Friedman8e1433b2009-07-29 19:44:27 +00002727
Sebastian Redla9351792012-02-11 23:51:47 +00002728 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002729 // Can't check initialization for a member of dependent type or when
2730 // any of the arguments are type-dependent expressions.
John McCall31168b02011-06-15 23:02:42 +00002731 DiscardCleanupsInEvaluationContext();
Chandler Carruthd44c3102010-12-06 09:23:57 +00002732 } else {
Sebastian Redl0501c632012-02-12 16:37:36 +00002733 bool InitList = false;
2734 if (isa<InitListExpr>(Init)) {
2735 InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002736 Args = Init;
Sebastian Redl0501c632012-02-12 16:37:36 +00002737 }
2738
Chandler Carruthd44c3102010-12-06 09:23:57 +00002739 // Initialize the member.
2740 InitializedEntity MemberEntity =
2741 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2742 : InitializedEntity::InitializeMember(IndirectMember, 0);
2743 InitializationKind Kind =
Sebastian Redl0501c632012-02-12 16:37:36 +00002744 InitList ? InitializationKind::CreateDirectList(IdLoc)
2745 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2746 InitRange.getEnd());
John McCallacf0ee52010-10-08 02:01:28 +00002747
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002748 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
2749 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 0);
Chandler Carruthd44c3102010-12-06 09:23:57 +00002750 if (MemberInit.isInvalid())
2751 return true;
2752
Richard Smith736a9472013-06-12 20:42:33 +00002753 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
2754
Richard Smith945f8d32013-01-14 22:39:08 +00002755 // C++11 [class.base.init]p7:
Chandler Carruthd44c3102010-12-06 09:23:57 +00002756 // The initialization of each base and member constitutes a
2757 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00002758 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
Chandler Carruthd44c3102010-12-06 09:23:57 +00002759 if (MemberInit.isInvalid())
2760 return true;
2761
Richard Smithd59b8322012-12-19 01:39:02 +00002762 Init = MemberInit.get();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002763 }
2764
Chandler Carruthd44c3102010-12-06 09:23:57 +00002765 if (DirectMember) {
Sebastian Redla9351792012-02-11 23:51:47 +00002766 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2767 InitRange.getBegin(), Init,
2768 InitRange.getEnd());
Chandler Carruthd44c3102010-12-06 09:23:57 +00002769 } else {
Sebastian Redla9351792012-02-11 23:51:47 +00002770 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2771 InitRange.getBegin(), Init,
2772 InitRange.getEnd());
Chandler Carruthd44c3102010-12-06 09:23:57 +00002773 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00002774}
2775
John McCallfaf5fb42010-08-26 23:41:50 +00002776MemInitResult
Sebastian Redla9351792012-02-11 23:51:47 +00002777Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Alexis Huntc5575cc2011-02-26 19:13:13 +00002778 CXXRecordDecl *ClassDecl) {
Douglas Gregord73f3dd2011-11-01 01:16:03 +00002779 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002780 if (!LangOpts.CPlusPlus11)
Douglas Gregord73f3dd2011-11-01 01:16:03 +00002781 return Diag(NameLoc, diag::err_delegating_ctor)
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002782 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregord73f3dd2011-11-01 01:16:03 +00002783 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redl9cb4be22011-03-12 13:53:51 +00002784
Sebastian Redl0501c632012-02-12 16:37:36 +00002785 bool InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002786 MultiExprArg Args = Init;
Sebastian Redl0501c632012-02-12 16:37:36 +00002787 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2788 InitList = false;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002789 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redl0501c632012-02-12 16:37:36 +00002790 }
2791
Sebastian Redla9351792012-02-11 23:51:47 +00002792 SourceRange InitRange = Init->getSourceRange();
Alexis Huntc5575cc2011-02-26 19:13:13 +00002793 // Initialize the object.
2794 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2795 QualType(ClassDecl->getTypeForDecl(), 0));
2796 InitializationKind Kind =
Sebastian Redl0501c632012-02-12 16:37:36 +00002797 InitList ? InitializationKind::CreateDirectList(NameLoc)
2798 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2799 InitRange.getEnd());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002800 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
Sebastian Redla9351792012-02-11 23:51:47 +00002801 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002802 Args, 0);
Alexis Huntc5575cc2011-02-26 19:13:13 +00002803 if (DelegationInit.isInvalid())
2804 return true;
2805
Matt Beaumont-Gay3e59fac2011-11-01 18:10:22 +00002806 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2807 "Delegating constructor with no target?");
Alexis Huntc5575cc2011-02-26 19:13:13 +00002808
Richard Smith945f8d32013-01-14 22:39:08 +00002809 // C++11 [class.base.init]p7:
Alexis Huntc5575cc2011-02-26 19:13:13 +00002810 // The initialization of each base and member constitutes a
2811 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00002812 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
2813 InitRange.getBegin());
Alexis Huntc5575cc2011-02-26 19:13:13 +00002814 if (DelegationInit.isInvalid())
2815 return true;
2816
Eli Friedmana9e9ebc2012-05-19 23:35:23 +00002817 // If we are in a dependent context, template instantiation will
2818 // perform this type-checking again. Just save the arguments that we
2819 // received in a ParenListExpr.
2820 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2821 // of the information that we have about the base
2822 // initializer. However, deconstructing the ASTs is a dicey process,
2823 // and this approach is far more likely to get the corner cases right.
2824 if (CurContext->isDependentContext())
2825 DelegationInit = Owned(Init);
2826
Sebastian Redla9351792012-02-11 23:51:47 +00002827 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Alexis Huntc5575cc2011-02-26 19:13:13 +00002828 DelegationInit.takeAs<Expr>(),
Sebastian Redla9351792012-02-11 23:51:47 +00002829 InitRange.getEnd());
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002830}
2831
2832MemInitResult
John McCallbcd03502009-12-07 02:54:59 +00002833Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redla9351792012-02-11 23:51:47 +00002834 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor44e7df62011-01-04 00:32:56 +00002835 SourceLocation EllipsisLoc) {
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002836 SourceLocation BaseLoc
2837 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redla74948d2011-09-24 17:48:25 +00002838
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002839 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2840 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2841 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2842
2843 // C++ [class.base.init]p2:
2844 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky9331ed82010-11-20 01:29:55 +00002845 // member of the constructor's class or a direct or virtual base
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002846 // of that class, the mem-initializer is ill-formed. A
2847 // mem-initializer-list can initialize a base class using any
2848 // name that denotes that base class type.
Sebastian Redla9351792012-02-11 23:51:47 +00002849 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002850
Sebastian Redla9351792012-02-11 23:51:47 +00002851 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor44e7df62011-01-04 00:32:56 +00002852 if (EllipsisLoc.isValid()) {
2853 // This is a pack expansion.
2854 if (!BaseType->containsUnexpandedParameterPack()) {
2855 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redla9351792012-02-11 23:51:47 +00002856 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redla74948d2011-09-24 17:48:25 +00002857
Douglas Gregor44e7df62011-01-04 00:32:56 +00002858 EllipsisLoc = SourceLocation();
2859 }
2860 } else {
2861 // Check for any unexpanded parameter packs.
2862 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2863 return true;
Sebastian Redla74948d2011-09-24 17:48:25 +00002864
Sebastian Redla9351792012-02-11 23:51:47 +00002865 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redla74948d2011-09-24 17:48:25 +00002866 return true;
Douglas Gregor44e7df62011-01-04 00:32:56 +00002867 }
Sebastian Redla74948d2011-09-24 17:48:25 +00002868
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002869 // Check for direct and virtual base classes.
2870 const CXXBaseSpecifier *DirectBaseSpec = 0;
2871 const CXXBaseSpecifier *VirtualBaseSpec = 0;
2872 if (!Dependent) {
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002873 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2874 BaseType))
Sebastian Redla9351792012-02-11 23:51:47 +00002875 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002876
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002877 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2878 VirtualBaseSpec);
2879
2880 // C++ [base.class.init]p2:
2881 // Unless the mem-initializer-id names a nonstatic data member of the
2882 // constructor's class or a direct or virtual base of that class, the
2883 // mem-initializer is ill-formed.
2884 if (!DirectBaseSpec && !VirtualBaseSpec) {
2885 // If the class has any dependent bases, then it's possible that
2886 // one of those types will resolve to the same type as
2887 // BaseType. Therefore, just treat this as a dependent base
2888 // class initialization. FIXME: Should we try to check the
2889 // initialization anyway? It seems odd.
2890 if (ClassDecl->hasAnyDependentBases())
2891 Dependent = true;
2892 else
2893 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2894 << BaseType << Context.getTypeDeclType(ClassDecl)
2895 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2896 }
2897 }
2898
2899 if (Dependent) {
John McCall31168b02011-06-15 23:02:42 +00002900 DiscardCleanupsInEvaluationContext();
Mike Stump11289f42009-09-09 15:08:12 +00002901
Sebastian Redla74948d2011-09-24 17:48:25 +00002902 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2903 /*IsVirtual=*/false,
Sebastian Redla9351792012-02-11 23:51:47 +00002904 InitRange.getBegin(), Init,
2905 InitRange.getEnd(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00002906 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002907
2908 // C++ [base.class.init]p2:
2909 // If a mem-initializer-id is ambiguous because it designates both
2910 // a direct non-virtual base class and an inherited virtual base
2911 // class, the mem-initializer is ill-formed.
2912 if (DirectBaseSpec && VirtualBaseSpec)
2913 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00002914 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002915
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002916 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002917 if (!BaseSpec)
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002918 BaseSpec = VirtualBaseSpec;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002919
2920 // Initialize the base.
Sebastian Redl0501c632012-02-12 16:37:36 +00002921 bool InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002922 MultiExprArg Args = Init;
Sebastian Redla9351792012-02-11 23:51:47 +00002923 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl0501c632012-02-12 16:37:36 +00002924 InitList = false;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002925 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redla9351792012-02-11 23:51:47 +00002926 }
Sebastian Redl0501c632012-02-12 16:37:36 +00002927
2928 InitializedEntity BaseEntity =
2929 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2930 InitializationKind Kind =
2931 InitList ? InitializationKind::CreateDirectList(BaseLoc)
2932 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2933 InitRange.getEnd());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002934 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
2935 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, 0);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002936 if (BaseInit.isInvalid())
2937 return true;
John McCallacf0ee52010-10-08 02:01:28 +00002938
Richard Smith945f8d32013-01-14 22:39:08 +00002939 // C++11 [class.base.init]p7:
2940 // The initialization of each base and member constitutes a
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002941 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00002942 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002943 if (BaseInit.isInvalid())
2944 return true;
2945
2946 // If we are in a dependent context, template instantiation will
2947 // perform this type-checking again. Just save the arguments that we
2948 // received in a ParenListExpr.
2949 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2950 // of the information that we have about the base
2951 // initializer. However, deconstructing the ASTs is a dicey process,
2952 // and this approach is far more likely to get the corner cases right.
Sebastian Redla74948d2011-09-24 17:48:25 +00002953 if (CurContext->isDependentContext())
Sebastian Redla9351792012-02-11 23:51:47 +00002954 BaseInit = Owned(Init);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002955
Alexis Hunt1d792652011-01-08 20:30:50 +00002956 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redla74948d2011-09-24 17:48:25 +00002957 BaseSpec->isVirtual(),
Sebastian Redla9351792012-02-11 23:51:47 +00002958 InitRange.getBegin(),
Sebastian Redla74948d2011-09-24 17:48:25 +00002959 BaseInit.takeAs<Expr>(),
Sebastian Redla9351792012-02-11 23:51:47 +00002960 InitRange.getEnd(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00002961}
2962
Sebastian Redl22653ba2011-08-30 19:58:05 +00002963// Create a static_cast\<T&&>(expr).
Richard Smithc2bc61b2013-03-18 21:12:30 +00002964static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
2965 if (T.isNull()) T = E->getType();
2966 QualType TargetType = SemaRef.BuildReferenceType(
2967 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
Sebastian Redl22653ba2011-08-30 19:58:05 +00002968 SourceLocation ExprLoc = E->getLocStart();
2969 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2970 TargetType, ExprLoc);
2971
2972 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2973 SourceRange(ExprLoc, ExprLoc),
2974 E->getSourceRange()).take();
2975}
2976
Anders Carlsson1b00e242010-04-23 03:10:23 +00002977/// ImplicitInitializerKind - How an implicit base or member initializer should
2978/// initialize its base or member.
2979enum ImplicitInitializerKind {
2980 IIK_Default,
2981 IIK_Copy,
Richard Smithc2bc61b2013-03-18 21:12:30 +00002982 IIK_Move,
2983 IIK_Inherit
Anders Carlsson1b00e242010-04-23 03:10:23 +00002984};
2985
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002986static bool
Anders Carlsson3c1db572010-04-23 02:15:47 +00002987BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00002988 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson43c64af2010-04-21 19:52:01 +00002989 CXXBaseSpecifier *BaseSpec,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002990 bool IsInheritedVirtualBase,
Alexis Hunt1d792652011-01-08 20:30:50 +00002991 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002992 InitializedEntity InitEntity
Anders Carlsson43c64af2010-04-21 19:52:01 +00002993 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2994 IsInheritedVirtualBase);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002995
John McCalldadc5752010-08-24 06:29:42 +00002996 ExprResult BaseInit;
Anders Carlsson1b00e242010-04-23 03:10:23 +00002997
2998 switch (ImplicitInitKind) {
Richard Smithc2bc61b2013-03-18 21:12:30 +00002999 case IIK_Inherit: {
3000 const CXXRecordDecl *Inherited =
3001 Constructor->getInheritedConstructor()->getParent();
3002 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
3003 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
3004 // C++11 [class.inhctor]p8:
3005 // Each expression in the expression-list is of the form
3006 // static_cast<T&&>(p), where p is the name of the corresponding
3007 // constructor parameter and T is the declared type of p.
3008 SmallVector<Expr*, 16> Args;
3009 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
3010 ParmVarDecl *PD = Constructor->getParamDecl(I);
3011 ExprResult ArgExpr =
3012 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
3013 VK_LValue, SourceLocation());
3014 if (ArgExpr.isInvalid())
3015 return true;
3016 Args.push_back(CastForMoving(SemaRef, ArgExpr.take(), PD->getType()));
3017 }
3018
3019 InitializationKind InitKind = InitializationKind::CreateDirect(
3020 Constructor->getLocation(), SourceLocation(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003021 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args);
Richard Smithc2bc61b2013-03-18 21:12:30 +00003022 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
3023 break;
3024 }
3025 }
3026 // Fall through.
Anders Carlsson1b00e242010-04-23 03:10:23 +00003027 case IIK_Default: {
3028 InitializationKind InitKind
3029 = InitializationKind::CreateDefault(Constructor->getLocation());
Dmitri Gribenko78852e92013-05-05 20:40:26 +00003030 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3031 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
Anders Carlsson1b00e242010-04-23 03:10:23 +00003032 break;
3033 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003034
Sebastian Redl22653ba2011-08-30 19:58:05 +00003035 case IIK_Move:
Anders Carlsson1b00e242010-04-23 03:10:23 +00003036 case IIK_Copy: {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003037 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson1b00e242010-04-23 03:10:23 +00003038 ParmVarDecl *Param = Constructor->getParamDecl(0);
3039 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedman2dfa7932012-01-16 21:00:51 +00003040
Anders Carlsson1b00e242010-04-23 03:10:23 +00003041 Expr *CopyCtorArg =
Abramo Bagnara7945c982012-01-27 09:46:47 +00003042 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCall113bee02012-03-10 09:33:50 +00003043 SourceLocation(), Param, false,
John McCall7decc9e2010-11-18 06:31:45 +00003044 Constructor->getLocation(), ParamType,
3045 VK_LValue, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +00003046
Eli Friedmanfa0df832012-02-02 03:46:19 +00003047 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
3048
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00003049 // Cast to the base class to avoid ambiguities.
Anders Carlsson79111502010-05-01 16:39:01 +00003050 QualType ArgTy =
3051 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
3052 ParamType.getQualifiers());
John McCallcf142162010-08-07 06:22:56 +00003053
Sebastian Redl22653ba2011-08-30 19:58:05 +00003054 if (Moving) {
3055 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
3056 }
3057
John McCallcf142162010-08-07 06:22:56 +00003058 CXXCastPath BasePath;
3059 BasePath.push_back(BaseSpec);
John Wiegley01296292011-04-08 18:41:53 +00003060 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
3061 CK_UncheckedDerivedToBase,
Sebastian Redle9c4e842011-09-04 18:14:28 +00003062 Moving ? VK_XValue : VK_LValue,
Sebastian Redl22653ba2011-08-30 19:58:05 +00003063 &BasePath).take();
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00003064
Anders Carlsson1b00e242010-04-23 03:10:23 +00003065 InitializationKind InitKind
3066 = InitializationKind::CreateDirect(Constructor->getLocation(),
3067 SourceLocation(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003068 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
3069 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
Anders Carlsson1b00e242010-04-23 03:10:23 +00003070 break;
3071 }
Anders Carlsson1b00e242010-04-23 03:10:23 +00003072 }
John McCallb268a282010-08-23 23:25:46 +00003073
Douglas Gregora40433a2010-12-07 00:41:46 +00003074 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003075 if (BaseInit.isInvalid())
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003076 return true;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003077
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003078 CXXBaseInit =
Alexis Hunt1d792652011-01-08 20:30:50 +00003079 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003080 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
3081 SourceLocation()),
3082 BaseSpec->isVirtual(),
3083 SourceLocation(),
3084 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00003085 SourceLocation(),
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003086 SourceLocation());
3087
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003088 return false;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003089}
3090
Sebastian Redl22653ba2011-08-30 19:58:05 +00003091static bool RefersToRValueRef(Expr *MemRef) {
3092 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
3093 return Referenced->getType()->isRValueReferenceType();
3094}
3095
Anders Carlsson3c1db572010-04-23 02:15:47 +00003096static bool
3097BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00003098 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor493627b2011-08-10 15:22:55 +00003099 FieldDecl *Field, IndirectFieldDecl *Indirect,
Alexis Hunt1d792652011-01-08 20:30:50 +00003100 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00003101 if (Field->isInvalidDecl())
3102 return true;
3103
Chandler Carruth9c9286b2010-06-29 23:50:44 +00003104 SourceLocation Loc = Constructor->getLocation();
3105
Sebastian Redl22653ba2011-08-30 19:58:05 +00003106 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
3107 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson423f5d82010-04-23 16:04:08 +00003108 ParmVarDecl *Param = Constructor->getParamDecl(0);
3109 QualType ParamType = Param->getType().getNonReferenceType();
John McCall1b1a1db2011-06-17 00:18:42 +00003110
3111 // Suppress copying zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +00003112 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
3113 return false;
Douglas Gregor10f939c2011-11-02 23:04:16 +00003114
Anders Carlsson423f5d82010-04-23 16:04:08 +00003115 Expr *MemberExprBase =
Abramo Bagnara7945c982012-01-27 09:46:47 +00003116 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCall113bee02012-03-10 09:33:50 +00003117 SourceLocation(), Param, false,
John McCall7decc9e2010-11-18 06:31:45 +00003118 Loc, ParamType, VK_LValue, 0);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003119
Eli Friedmanfa0df832012-02-02 03:46:19 +00003120 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
3121
Sebastian Redl22653ba2011-08-30 19:58:05 +00003122 if (Moving) {
3123 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
3124 }
3125
Douglas Gregor94f9a482010-05-05 05:51:00 +00003126 // Build a reference to this field within the parameter.
3127 CXXScopeSpec SS;
3128 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
3129 Sema::LookupMemberName);
Sebastian Redl22653ba2011-08-30 19:58:05 +00003130 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
3131 : cast<ValueDecl>(Field), AS_public);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003132 MemberLookup.resolveKind();
Sebastian Redle9c4e842011-09-04 18:14:28 +00003133 ExprResult CtorArg
John McCallb268a282010-08-23 23:25:46 +00003134 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregor94f9a482010-05-05 05:51:00 +00003135 ParamType, Loc,
3136 /*IsArrow=*/false,
3137 SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00003138 /*TemplateKWLoc=*/SourceLocation(),
Douglas Gregor94f9a482010-05-05 05:51:00 +00003139 /*FirstQualifierInScope=*/0,
3140 MemberLookup,
3141 /*TemplateArgs=*/0);
Sebastian Redle9c4e842011-09-04 18:14:28 +00003142 if (CtorArg.isInvalid())
Anders Carlsson423f5d82010-04-23 16:04:08 +00003143 return true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00003144
3145 // C++11 [class.copy]p15:
3146 // - if a member m has rvalue reference type T&&, it is direct-initialized
3147 // with static_cast<T&&>(x.m);
Sebastian Redle9c4e842011-09-04 18:14:28 +00003148 if (RefersToRValueRef(CtorArg.get())) {
3149 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl22653ba2011-08-30 19:58:05 +00003150 }
3151
Douglas Gregor94f9a482010-05-05 05:51:00 +00003152 // When the field we are copying is an array, create index variables for
3153 // each dimension of the array. We use these index variables to subscript
3154 // the source array, and other clients (e.g., CodeGen) will perform the
3155 // necessary iteration with these index variables.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003156 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003157 QualType BaseType = Field->getType();
3158 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl22653ba2011-08-30 19:58:05 +00003159 bool InitializingArray = false;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003160 while (const ConstantArrayType *Array
3161 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003162 InitializingArray = true;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003163 // Create the iteration variable for this array index.
3164 IdentifierInfo *IterationVarName = 0;
3165 {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003166 SmallString<8> Str;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003167 llvm::raw_svector_ostream OS(Str);
3168 OS << "__i" << IndexVariables.size();
3169 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
3170 }
3171 VarDecl *IterationVar
Abramo Bagnaradff19302011-03-08 08:55:46 +00003172 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregor94f9a482010-05-05 05:51:00 +00003173 IterationVarName, SizeType,
3174 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003175 SC_None);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003176 IndexVariables.push_back(IterationVar);
3177
3178 // Create a reference to the iteration variable.
John McCalldadc5752010-08-24 06:29:42 +00003179 ExprResult IterationVarRef
Eli Friedman844f9452012-01-23 02:35:22 +00003180 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003181 assert(!IterationVarRef.isInvalid() &&
3182 "Reference to invented variable cannot fail!");
Eli Friedman844f9452012-01-23 02:35:22 +00003183 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
3184 assert(!IterationVarRef.isInvalid() &&
3185 "Conversion of invented variable cannot fail!");
Sebastian Redle9c4e842011-09-04 18:14:28 +00003186
Douglas Gregor94f9a482010-05-05 05:51:00 +00003187 // Subscript the array with this iteration variable.
Sebastian Redle9c4e842011-09-04 18:14:28 +00003188 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCallb268a282010-08-23 23:25:46 +00003189 IterationVarRef.take(),
Sebastian Redle9c4e842011-09-04 18:14:28 +00003190 Loc);
3191 if (CtorArg.isInvalid())
Douglas Gregor94f9a482010-05-05 05:51:00 +00003192 return true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00003193
Douglas Gregor94f9a482010-05-05 05:51:00 +00003194 BaseType = Array->getElementType();
3195 }
Sebastian Redl22653ba2011-08-30 19:58:05 +00003196
3197 // The array subscript expression is an lvalue, which is wrong for moving.
3198 if (Moving && InitializingArray)
Sebastian Redle9c4e842011-09-04 18:14:28 +00003199 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl22653ba2011-08-30 19:58:05 +00003200
Douglas Gregor94f9a482010-05-05 05:51:00 +00003201 // Construct the entity that we will be initializing. For an array, this
3202 // will be first element in the array, which may require several levels
3203 // of array-subscript entities.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003204 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003205 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor493627b2011-08-10 15:22:55 +00003206 if (Indirect)
3207 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
3208 else
3209 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregor94f9a482010-05-05 05:51:00 +00003210 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
3211 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
3212 0,
3213 Entities.back()));
3214
3215 // Direct-initialize to use the copy constructor.
3216 InitializationKind InitKind =
3217 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
3218
Sebastian Redle9c4e842011-09-04 18:14:28 +00003219 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003220 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, CtorArgE);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003221
John McCalldadc5752010-08-24 06:29:42 +00003222 ExprResult MemberInit
Douglas Gregor94f9a482010-05-05 05:51:00 +00003223 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redle9c4e842011-09-04 18:14:28 +00003224 MultiExprArg(&CtorArgE, 1));
Douglas Gregora40433a2010-12-07 00:41:46 +00003225 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003226 if (MemberInit.isInvalid())
3227 return true;
3228
Douglas Gregor493627b2011-08-10 15:22:55 +00003229 if (Indirect) {
3230 assert(IndexVariables.size() == 0 &&
3231 "Indirect field improperly initialized");
3232 CXXMemberInit
3233 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3234 Loc, Loc,
3235 MemberInit.takeAs<Expr>(),
3236 Loc);
3237 } else
3238 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
3239 Loc, MemberInit.takeAs<Expr>(),
3240 Loc,
3241 IndexVariables.data(),
3242 IndexVariables.size());
Anders Carlsson1b00e242010-04-23 03:10:23 +00003243 return false;
3244 }
3245
Richard Smithc2bc61b2013-03-18 21:12:30 +00003246 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
3247 "Unhandled implicit init kind!");
Anders Carlsson423f5d82010-04-23 16:04:08 +00003248
Anders Carlsson3c1db572010-04-23 02:15:47 +00003249 QualType FieldBaseElementType =
3250 SemaRef.Context.getBaseElementType(Field->getType());
3251
Anders Carlsson3c1db572010-04-23 02:15:47 +00003252 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor493627b2011-08-10 15:22:55 +00003253 InitializedEntity InitEntity
3254 = Indirect? InitializedEntity::InitializeMember(Indirect)
3255 : InitializedEntity::InitializeMember(Field);
Anders Carlsson423f5d82010-04-23 16:04:08 +00003256 InitializationKind InitKind =
Chandler Carruth9c9286b2010-06-29 23:50:44 +00003257 InitializationKind::CreateDefault(Loc);
Dmitri Gribenko78852e92013-05-05 20:40:26 +00003258
3259 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3260 ExprResult MemberInit =
3261 InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
John McCallb268a282010-08-23 23:25:46 +00003262
Douglas Gregora40433a2010-12-07 00:41:46 +00003263 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlsson3c1db572010-04-23 02:15:47 +00003264 if (MemberInit.isInvalid())
3265 return true;
3266
Douglas Gregor493627b2011-08-10 15:22:55 +00003267 if (Indirect)
3268 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3269 Indirect, Loc,
3270 Loc,
3271 MemberInit.get(),
3272 Loc);
3273 else
3274 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3275 Field, Loc, Loc,
3276 MemberInit.get(),
3277 Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00003278 return false;
3279 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003280
Alexis Hunt8b455182011-05-17 00:19:05 +00003281 if (!Field->getParent()->isUnion()) {
3282 if (FieldBaseElementType->isReferenceType()) {
3283 SemaRef.Diag(Constructor->getLocation(),
3284 diag::err_uninitialized_member_in_ctor)
3285 << (int)Constructor->isImplicit()
3286 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3287 << 0 << Field->getDeclName();
3288 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3289 return true;
3290 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003291
Alexis Hunt8b455182011-05-17 00:19:05 +00003292 if (FieldBaseElementType.isConstQualified()) {
3293 SemaRef.Diag(Constructor->getLocation(),
3294 diag::err_uninitialized_member_in_ctor)
3295 << (int)Constructor->isImplicit()
3296 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3297 << 1 << Field->getDeclName();
3298 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3299 return true;
3300 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003301 }
Anders Carlsson3c1db572010-04-23 02:15:47 +00003302
David Blaikiebbafb8a2012-03-11 07:00:24 +00003303 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00003304 FieldBaseElementType->isObjCRetainableType() &&
3305 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3306 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
Douglas Gregor6fa69422012-07-23 04:23:39 +00003307 // ARC:
John McCall31168b02011-06-15 23:02:42 +00003308 // Default-initialize Objective-C pointers to NULL.
3309 CXXMemberInit
3310 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3311 Loc, Loc,
3312 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3313 Loc);
3314 return false;
3315 }
3316
Anders Carlsson3c1db572010-04-23 02:15:47 +00003317 // Nothing to initialize.
3318 CXXMemberInit = 0;
3319 return false;
3320}
John McCallbc83b3f2010-05-20 23:23:51 +00003321
3322namespace {
3323struct BaseAndFieldInfo {
3324 Sema &S;
3325 CXXConstructorDecl *Ctor;
3326 bool AnyErrorsInInits;
3327 ImplicitInitializerKind IIK;
Alexis Hunt1d792652011-01-08 20:30:50 +00003328 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003329 SmallVector<CXXCtorInitializer*, 8> AllToInit;
Richard Smithab44d5b2013-12-10 08:25:00 +00003330 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
John McCallbc83b3f2010-05-20 23:23:51 +00003331
3332 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3333 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003334 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3335 if (Generated && Ctor->isCopyConstructor())
John McCallbc83b3f2010-05-20 23:23:51 +00003336 IIK = IIK_Copy;
Sebastian Redl22653ba2011-08-30 19:58:05 +00003337 else if (Generated && Ctor->isMoveConstructor())
3338 IIK = IIK_Move;
Richard Smithc2bc61b2013-03-18 21:12:30 +00003339 else if (Ctor->getInheritedConstructor())
3340 IIK = IIK_Inherit;
John McCallbc83b3f2010-05-20 23:23:51 +00003341 else
3342 IIK = IIK_Default;
3343 }
Douglas Gregor7db3e952011-11-28 20:03:15 +00003344
3345 bool isImplicitCopyOrMove() const {
3346 switch (IIK) {
3347 case IIK_Copy:
3348 case IIK_Move:
3349 return true;
3350
3351 case IIK_Default:
Richard Smithc2bc61b2013-03-18 21:12:30 +00003352 case IIK_Inherit:
Douglas Gregor7db3e952011-11-28 20:03:15 +00003353 return false;
3354 }
David Blaikiee4d798f2012-01-20 21:50:17 +00003355
3356 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregor7db3e952011-11-28 20:03:15 +00003357 }
Richard Smith0a8cfc72012-08-07 21:30:42 +00003358
3359 bool addFieldInitializer(CXXCtorInitializer *Init) {
3360 AllToInit.push_back(Init);
3361
3362 // Check whether this initializer makes the field "used".
Richard Smith852c9db2013-04-20 22:23:05 +00003363 if (Init->getInit()->HasSideEffects(S.Context))
Richard Smith0a8cfc72012-08-07 21:30:42 +00003364 S.UnusedPrivateFields.remove(Init->getAnyMember());
3365
3366 return false;
3367 }
John McCallbc83b3f2010-05-20 23:23:51 +00003368
Richard Smithab44d5b2013-12-10 08:25:00 +00003369 bool isInactiveUnionMember(FieldDecl *Field) {
3370 RecordDecl *Record = Field->getParent();
3371 if (!Record->isUnion())
3372 return false;
3373
Richard Smith8d183852013-12-10 20:56:03 +00003374 if (FieldDecl *Active =
3375 ActiveUnionMember.lookup(Record->getCanonicalDecl()))
Richard Smithab44d5b2013-12-10 08:25:00 +00003376 return Active != Field->getCanonicalDecl();
3377
3378 // In an implicit copy or move constructor, ignore any in-class initializer.
3379 if (isImplicitCopyOrMove())
3380 return true;
3381
3382 // If there's no explicit initialization, the field is active only if it
3383 // has an in-class initializer...
3384 if (Field->hasInClassInitializer())
3385 return false;
3386 // ... or it's an anonymous struct or union whose class has an in-class
3387 // initializer.
3388 if (!Field->isAnonymousStructOrUnion())
3389 return true;
3390 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
3391 return !FieldRD->hasInClassInitializer();
3392 }
3393
3394 /// \brief Determine whether the given field is, or is within, a union member
3395 /// that is inactive (because there was an initializer given for a different
3396 /// member of the union, or because the union was not initialized at all).
3397 bool isWithinInactiveUnionMember(FieldDecl *Field,
3398 IndirectFieldDecl *Indirect) {
3399 if (!Indirect)
3400 return isInactiveUnionMember(Field);
3401
Aaron Ballman29c94602014-03-07 18:36:15 +00003402 for (auto *C : Indirect->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00003403 FieldDecl *Field = dyn_cast<FieldDecl>(C);
Richard Smithab44d5b2013-12-10 08:25:00 +00003404 if (Field && isInactiveUnionMember(Field))
Richard Smithc94ec842011-09-19 13:34:43 +00003405 return true;
Richard Smithab44d5b2013-12-10 08:25:00 +00003406 }
3407 return false;
3408 }
3409};
Richard Smithc94ec842011-09-19 13:34:43 +00003410}
3411
Douglas Gregor10f939c2011-11-02 23:04:16 +00003412/// \brief Determine whether the given type is an incomplete or zero-lenfgth
3413/// array type.
3414static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3415 if (T->isIncompleteArrayType())
3416 return true;
3417
3418 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3419 if (!ArrayT->getSize())
3420 return true;
3421
3422 T = ArrayT->getElementType();
3423 }
3424
3425 return false;
3426}
3427
Richard Smith938f40b2011-06-11 17:19:42 +00003428static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor493627b2011-08-10 15:22:55 +00003429 FieldDecl *Field,
3430 IndirectFieldDecl *Indirect = 0) {
Eli Friedmanb13e64e2013-06-28 21:07:41 +00003431 if (Field->isInvalidDecl())
3432 return false;
John McCallbc83b3f2010-05-20 23:23:51 +00003433
Chandler Carruth139e9622010-06-30 02:59:29 +00003434 // Overwhelmingly common case: we have a direct initializer for this field.
Richard Smith0a8cfc72012-08-07 21:30:42 +00003435 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field))
3436 return Info.addFieldInitializer(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00003437
Richard Smithab44d5b2013-12-10 08:25:00 +00003438 // C++11 [class.base.init]p8:
3439 // if the entity is a non-static data member that has a
3440 // brace-or-equal-initializer and either
3441 // -- the constructor's class is a union and no other variant member of that
3442 // union is designated by a mem-initializer-id or
3443 // -- the constructor's class is not a union, and, if the entity is a member
3444 // of an anonymous union, no other member of that union is designated by
3445 // a mem-initializer-id,
3446 // the entity is initialized as specified in [dcl.init].
3447 //
3448 // We also apply the same rules to handle anonymous structs within anonymous
3449 // unions.
3450 if (Info.isWithinInactiveUnionMember(Field, Indirect))
3451 return false;
3452
Douglas Gregor7db3e952011-11-28 20:03:15 +00003453 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Richard Smith852c9db2013-04-20 22:23:05 +00003454 Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context,
3455 Info.Ctor->getLocation(), Field);
Douglas Gregor493627b2011-08-10 15:22:55 +00003456 CXXCtorInitializer *Init;
3457 if (Indirect)
3458 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3459 SourceLocation(),
Richard Smith852c9db2013-04-20 22:23:05 +00003460 SourceLocation(), DIE,
Douglas Gregor493627b2011-08-10 15:22:55 +00003461 SourceLocation());
3462 else
3463 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3464 SourceLocation(),
Richard Smith852c9db2013-04-20 22:23:05 +00003465 SourceLocation(), DIE,
Douglas Gregor493627b2011-08-10 15:22:55 +00003466 SourceLocation());
Richard Smith0a8cfc72012-08-07 21:30:42 +00003467 return Info.addFieldInitializer(Init);
Richard Smith938f40b2011-06-11 17:19:42 +00003468 }
3469
Douglas Gregor10f939c2011-11-02 23:04:16 +00003470 // Don't initialize incomplete or zero-length arrays.
3471 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3472 return false;
3473
John McCallbc83b3f2010-05-20 23:23:51 +00003474 // Don't try to build an implicit initializer if there were semantic
3475 // errors in any of the initializers (and therefore we might be
3476 // missing some that the user actually wrote).
Eli Friedmanb13e64e2013-06-28 21:07:41 +00003477 if (Info.AnyErrorsInInits)
John McCallbc83b3f2010-05-20 23:23:51 +00003478 return false;
3479
Alexis Hunt1d792652011-01-08 20:30:50 +00003480 CXXCtorInitializer *Init = 0;
Douglas Gregor493627b2011-08-10 15:22:55 +00003481 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3482 Indirect, Init))
John McCallbc83b3f2010-05-20 23:23:51 +00003483 return true;
John McCallbc83b3f2010-05-20 23:23:51 +00003484
Richard Smith0a8cfc72012-08-07 21:30:42 +00003485 if (!Init)
3486 return false;
Francois Pichetd583da02010-12-04 09:14:42 +00003487
Richard Smith0a8cfc72012-08-07 21:30:42 +00003488 return Info.addFieldInitializer(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00003489}
Alexis Hunt61bc1732011-05-01 07:04:31 +00003490
3491bool
3492Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3493 CXXCtorInitializer *Initializer) {
Alexis Hunt6118d662011-05-04 05:57:24 +00003494 assert(Initializer->isDelegatingInitializer());
Alexis Hunt5583d562011-05-03 20:43:02 +00003495 Constructor->setNumCtorInitializers(1);
3496 CXXCtorInitializer **initializer =
3497 new (Context) CXXCtorInitializer*[1];
3498 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3499 Constructor->setCtorInitializers(initializer);
3500
Alexis Hunt9d47faf2011-05-03 23:05:34 +00003501 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00003502 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Alexis Hunt9d47faf2011-05-03 23:05:34 +00003503 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3504 }
3505
Alexis Hunte2622992011-05-05 00:05:47 +00003506 DelegatingCtorDecls.push_back(Constructor);
Alexis Hunt6118d662011-05-04 05:57:24 +00003507
Alexis Hunt61bc1732011-05-01 07:04:31 +00003508 return false;
3509}
Douglas Gregor493627b2011-08-10 15:22:55 +00003510
David Blaikie3fc2f912013-01-17 05:26:25 +00003511bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3512 ArrayRef<CXXCtorInitializer *> Initializers) {
Douglas Gregor52235292011-09-22 23:04:35 +00003513 if (Constructor->isDependentContext()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003514 // Just store the initializers as written, they will be checked during
3515 // instantiation.
David Blaikie3fc2f912013-01-17 05:26:25 +00003516 if (!Initializers.empty()) {
3517 Constructor->setNumCtorInitializers(Initializers.size());
Alexis Hunt1d792652011-01-08 20:30:50 +00003518 CXXCtorInitializer **baseOrMemberInitializers =
David Blaikie3fc2f912013-01-17 05:26:25 +00003519 new (Context) CXXCtorInitializer*[Initializers.size()];
3520 memcpy(baseOrMemberInitializers, Initializers.data(),
3521 Initializers.size() * sizeof(CXXCtorInitializer*));
Alexis Hunt1d792652011-01-08 20:30:50 +00003522 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssondb0a9652010-04-02 06:26:44 +00003523 }
Richard Smith60f2e1e2012-09-25 00:23:05 +00003524
3525 // Let template instantiation know whether we had errors.
3526 if (AnyErrors)
3527 Constructor->setInvalidDecl();
3528
Anders Carlssondb0a9652010-04-02 06:26:44 +00003529 return false;
3530 }
3531
John McCallbc83b3f2010-05-20 23:23:51 +00003532 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlsson1b00e242010-04-23 03:10:23 +00003533
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003534 // We need to build the initializer AST according to order of construction
3535 // and not what user specified in the Initializers list.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003536 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregorc14922f2010-03-26 22:43:07 +00003537 if (!ClassDecl)
3538 return true;
3539
Eli Friedman9cf6b592009-11-09 19:20:36 +00003540 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00003541
David Blaikie3fc2f912013-01-17 05:26:25 +00003542 for (unsigned i = 0; i < Initializers.size(); i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003543 CXXCtorInitializer *Member = Initializers[i];
Richard Smithbc46e432013-07-22 02:56:56 +00003544
Anders Carlssondb0a9652010-04-02 06:26:44 +00003545 if (Member->isBaseInitializer())
John McCallbc83b3f2010-05-20 23:23:51 +00003546 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Richard Smithab44d5b2013-12-10 08:25:00 +00003547 else {
Francois Pichetd583da02010-12-04 09:14:42 +00003548 Info.AllBaseFields[Member->getAnyMember()] = Member;
Richard Smithab44d5b2013-12-10 08:25:00 +00003549
3550 if (IndirectFieldDecl *F = Member->getIndirectMember()) {
Aaron Ballman29c94602014-03-07 18:36:15 +00003551 for (auto *C : F->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00003552 FieldDecl *FD = dyn_cast<FieldDecl>(C);
Richard Smithab44d5b2013-12-10 08:25:00 +00003553 if (FD && FD->getParent()->isUnion())
3554 Info.ActiveUnionMember.insert(std::make_pair(
3555 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3556 }
3557 } else if (FieldDecl *FD = Member->getMember()) {
3558 if (FD->getParent()->isUnion())
3559 Info.ActiveUnionMember.insert(std::make_pair(
3560 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3561 }
3562 }
Anders Carlssondb0a9652010-04-02 06:26:44 +00003563 }
3564
Anders Carlsson43c64af2010-04-21 19:52:01 +00003565 // Keep track of the direct virtual bases.
3566 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
Aaron Ballman574705e2014-03-13 15:41:46 +00003567 for (auto &I : ClassDecl->bases()) {
3568 if (I.isVirtual())
3569 DirectVBases.insert(&I);
Anders Carlsson43c64af2010-04-21 19:52:01 +00003570 }
3571
Anders Carlssondb0a9652010-04-02 06:26:44 +00003572 // Push virtual bases before others.
Aaron Ballman445a9392014-03-13 16:15:17 +00003573 for (auto &VBase : ClassDecl->vbases()) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003574 if (CXXCtorInitializer *Value
Aaron Ballman445a9392014-03-13 16:15:17 +00003575 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
Richard Smithbc46e432013-07-22 02:56:56 +00003576 // [class.base.init]p7, per DR257:
3577 // A mem-initializer where the mem-initializer-id names a virtual base
3578 // class is ignored during execution of a constructor of any class that
3579 // is not the most derived class.
3580 if (ClassDecl->isAbstract()) {
3581 // FIXME: Provide a fixit to remove the base specifier. This requires
3582 // tracking the location of the associated comma for a base specifier.
3583 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
Aaron Ballman445a9392014-03-13 16:15:17 +00003584 << VBase.getType() << ClassDecl;
Richard Smithbc46e432013-07-22 02:56:56 +00003585 DiagnoseAbstractType(ClassDecl);
3586 }
3587
John McCallbc83b3f2010-05-20 23:23:51 +00003588 Info.AllToInit.push_back(Value);
Richard Smithbc46e432013-07-22 02:56:56 +00003589 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
3590 // [class.base.init]p8, per DR257:
3591 // If a given [...] base class is not named by a mem-initializer-id
3592 // [...] and the entity is not a virtual base class of an abstract
3593 // class, then [...] the entity is default-initialized.
Aaron Ballman445a9392014-03-13 16:15:17 +00003594 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
Alexis Hunt1d792652011-01-08 20:30:50 +00003595 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00003596 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Aaron Ballman445a9392014-03-13 16:15:17 +00003597 &VBase, IsInheritedVirtualBase,
Anders Carlsson1b00e242010-04-23 03:10:23 +00003598 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003599 HadError = true;
3600 continue;
3601 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003602
John McCallbc83b3f2010-05-20 23:23:51 +00003603 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003604 }
3605 }
Mike Stump11289f42009-09-09 15:08:12 +00003606
John McCallbc83b3f2010-05-20 23:23:51 +00003607 // Non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00003608 for (auto &Base : ClassDecl->bases()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003609 // Virtuals are in the virtual base list and already constructed.
Aaron Ballman574705e2014-03-13 15:41:46 +00003610 if (Base.isVirtual())
Anders Carlssondb0a9652010-04-02 06:26:44 +00003611 continue;
Mike Stump11289f42009-09-09 15:08:12 +00003612
Alexis Hunt1d792652011-01-08 20:30:50 +00003613 if (CXXCtorInitializer *Value
Aaron Ballman574705e2014-03-13 15:41:46 +00003614 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
John McCallbc83b3f2010-05-20 23:23:51 +00003615 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00003616 } else if (!AnyErrors) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003617 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00003618 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Aaron Ballman574705e2014-03-13 15:41:46 +00003619 &Base, /*IsInheritedVirtualBase=*/false,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003620 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003621 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003622 continue;
Anders Carlssondb0a9652010-04-02 06:26:44 +00003623 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00003624
John McCallbc83b3f2010-05-20 23:23:51 +00003625 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003626 }
3627 }
Mike Stump11289f42009-09-09 15:08:12 +00003628
John McCallbc83b3f2010-05-20 23:23:51 +00003629 // Fields.
Aaron Ballman629afae2014-03-07 19:56:05 +00003630 for (auto *Mem : ClassDecl->decls()) {
3631 if (auto *F = dyn_cast<FieldDecl>(Mem)) {
Douglas Gregor556e5862011-10-10 17:22:13 +00003632 // C++ [class.bit]p2:
3633 // A declaration for a bit-field that omits the identifier declares an
3634 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
3635 // initialized.
3636 if (F->isUnnamedBitfield())
3637 continue;
Douglas Gregor10f939c2011-11-02 23:04:16 +00003638
Sebastian Redl22653ba2011-08-30 19:58:05 +00003639 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor493627b2011-08-10 15:22:55 +00003640 // handle anonymous struct/union fields based on their individual
3641 // indirect fields.
Richard Smithc2bc61b2013-03-18 21:12:30 +00003642 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
Douglas Gregor493627b2011-08-10 15:22:55 +00003643 continue;
3644
3645 if (CollectFieldInitializer(*this, Info, F))
3646 HadError = true;
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00003647 continue;
3648 }
Douglas Gregor493627b2011-08-10 15:22:55 +00003649
3650 // Beyond this point, we only consider default initialization.
Richard Smithc2bc61b2013-03-18 21:12:30 +00003651 if (Info.isImplicitCopyOrMove())
Douglas Gregor493627b2011-08-10 15:22:55 +00003652 continue;
3653
Aaron Ballman629afae2014-03-07 19:56:05 +00003654 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
Douglas Gregor493627b2011-08-10 15:22:55 +00003655 if (F->getType()->isIncompleteArrayType()) {
3656 assert(ClassDecl->hasFlexibleArrayMember() &&
3657 "Incomplete array type is not valid");
3658 continue;
3659 }
3660
Douglas Gregor493627b2011-08-10 15:22:55 +00003661 // Initialize each field of an anonymous struct individually.
3662 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3663 HadError = true;
3664
3665 continue;
3666 }
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00003667 }
Mike Stump11289f42009-09-09 15:08:12 +00003668
David Blaikie3fc2f912013-01-17 05:26:25 +00003669 unsigned NumInitializers = Info.AllToInit.size();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003670 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003671 Constructor->setNumCtorInitializers(NumInitializers);
3672 CXXCtorInitializer **baseOrMemberInitializers =
3673 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallbc83b3f2010-05-20 23:23:51 +00003674 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Alexis Hunt1d792652011-01-08 20:30:50 +00003675 NumInitializers * sizeof(CXXCtorInitializer*));
3676 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola13327bb2010-03-13 18:12:56 +00003677
John McCalla6309952010-03-16 21:39:52 +00003678 // Constructors implicitly reference the base and member
3679 // destructors.
3680 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3681 Constructor->getParent());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003682 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00003683
3684 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003685}
3686
David Blaikieb61b8152013-01-17 08:49:22 +00003687static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003688 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
David Blaikieb61b8152013-01-17 08:49:22 +00003689 const RecordDecl *RD = RT->getDecl();
3690 if (RD->isAnonymousStructOrUnion()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00003691 for (auto *Field : RD->fields())
3692 PopulateKeysForFields(Field, IdealInits);
David Blaikieb61b8152013-01-17 08:49:22 +00003693 return;
3694 }
Eli Friedman952c15d2009-07-21 19:28:10 +00003695 }
David Blaikieb61b8152013-01-17 08:49:22 +00003696 IdealInits.push_back(Field);
Eli Friedman952c15d2009-07-21 19:28:10 +00003697}
3698
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003699static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
3700 return Context.getCanonicalType(BaseType).getTypePtr();
Anders Carlssonbcec05c2009-09-01 06:22:14 +00003701}
3702
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003703static const void *GetKeyForMember(ASTContext &Context,
3704 CXXCtorInitializer *Member) {
Francois Pichetd583da02010-12-04 09:14:42 +00003705 if (!Member->isAnyMemberInitializer())
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003706 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlssona942dcd2010-03-30 15:39:27 +00003707
David Blaikieb61b8152013-01-17 08:49:22 +00003708 return Member->getAnyMember();
Eli Friedman952c15d2009-07-21 19:28:10 +00003709}
3710
David Blaikie3fc2f912013-01-17 05:26:25 +00003711static void DiagnoseBaseOrMemInitializerOrder(
3712 Sema &SemaRef, const CXXConstructorDecl *Constructor,
3713 ArrayRef<CXXCtorInitializer *> Inits) {
John McCallbb7b6582010-04-10 07:37:23 +00003714 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00003715 return;
Mike Stump11289f42009-09-09 15:08:12 +00003716
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00003717 // Don't check initializers order unless the warning is enabled at the
3718 // location of at least one initializer.
3719 bool ShouldCheckOrder = false;
David Blaikie3fc2f912013-01-17 05:26:25 +00003720 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003721 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00003722 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3723 Init->getSourceLocation())
David Blaikie9c902b52011-09-25 23:23:43 +00003724 != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00003725 ShouldCheckOrder = true;
3726 break;
3727 }
3728 }
3729 if (!ShouldCheckOrder)
Anders Carlssone0eebb32009-08-27 05:45:01 +00003730 return;
Anders Carlssone857b292010-04-02 03:37:03 +00003731
John McCallbb7b6582010-04-10 07:37:23 +00003732 // Build the list of bases and members in the order that they'll
3733 // actually be initialized. The explicit initializers should be in
3734 // this same order but may be missing things.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003735 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump11289f42009-09-09 15:08:12 +00003736
Anders Carlsson96b8fc62010-04-02 03:38:04 +00003737 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3738
John McCallbb7b6582010-04-10 07:37:23 +00003739 // 1. Virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +00003740 for (const auto &VBase : ClassDecl->vbases())
3741 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
Mike Stump11289f42009-09-09 15:08:12 +00003742
John McCallbb7b6582010-04-10 07:37:23 +00003743 // 2. Non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00003744 for (const auto &Base : ClassDecl->bases()) {
3745 if (Base.isVirtual())
Anders Carlssone0eebb32009-08-27 05:45:01 +00003746 continue;
Aaron Ballman574705e2014-03-13 15:41:46 +00003747 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00003748 }
Mike Stump11289f42009-09-09 15:08:12 +00003749
John McCallbb7b6582010-04-10 07:37:23 +00003750 // 3. Direct fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00003751 for (auto *Field : ClassDecl->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +00003752 if (Field->isUnnamedBitfield())
3753 continue;
3754
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00003755 PopulateKeysForFields(Field, IdealInitKeys);
Douglas Gregor556e5862011-10-10 17:22:13 +00003756 }
3757
John McCallbb7b6582010-04-10 07:37:23 +00003758 unsigned NumIdealInits = IdealInitKeys.size();
3759 unsigned IdealIndex = 0;
Eli Friedman952c15d2009-07-21 19:28:10 +00003760
Alexis Hunt1d792652011-01-08 20:30:50 +00003761 CXXCtorInitializer *PrevInit = 0;
David Blaikie3fc2f912013-01-17 05:26:25 +00003762 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003763 CXXCtorInitializer *Init = Inits[InitIndex];
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003764 const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCallbb7b6582010-04-10 07:37:23 +00003765
3766 // Scan forward to try to find this initializer in the idealized
3767 // initializers list.
3768 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3769 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00003770 break;
John McCallbb7b6582010-04-10 07:37:23 +00003771
3772 // If we didn't find this initializer, it must be because we
3773 // scanned past it on a previous iteration. That can only
3774 // happen if we're out of order; emit a warning.
Douglas Gregoraabdfcb2010-05-20 23:49:34 +00003775 if (IdealIndex == NumIdealInits && PrevInit) {
John McCallbb7b6582010-04-10 07:37:23 +00003776 Sema::SemaDiagnosticBuilder D =
3777 SemaRef.Diag(PrevInit->getSourceLocation(),
3778 diag::warn_initializer_out_of_order);
3779
Francois Pichetd583da02010-12-04 09:14:42 +00003780 if (PrevInit->isAnyMemberInitializer())
3781 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00003782 else
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003783 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCallbb7b6582010-04-10 07:37:23 +00003784
Francois Pichetd583da02010-12-04 09:14:42 +00003785 if (Init->isAnyMemberInitializer())
3786 D << 0 << Init->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00003787 else
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003788 D << 1 << Init->getTypeSourceInfo()->getType();
John McCallbb7b6582010-04-10 07:37:23 +00003789
3790 // Move back to the initializer's location in the ideal list.
3791 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3792 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00003793 break;
John McCallbb7b6582010-04-10 07:37:23 +00003794
3795 assert(IdealIndex != NumIdealInits &&
3796 "initializer not found in initializer list");
Fariborz Jahanian341583c2009-07-09 19:59:47 +00003797 }
John McCallbb7b6582010-04-10 07:37:23 +00003798
3799 PrevInit = Init;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00003800 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00003801}
3802
John McCall23eebd92010-04-10 09:28:51 +00003803namespace {
3804bool CheckRedundantInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00003805 CXXCtorInitializer *Init,
3806 CXXCtorInitializer *&PrevInit) {
John McCall23eebd92010-04-10 09:28:51 +00003807 if (!PrevInit) {
3808 PrevInit = Init;
3809 return false;
3810 }
3811
Douglas Gregorea306a12013-03-25 23:28:23 +00003812 if (FieldDecl *Field = Init->getAnyMember())
John McCall23eebd92010-04-10 09:28:51 +00003813 S.Diag(Init->getSourceLocation(),
3814 diag::err_multiple_mem_initialization)
3815 << Field->getDeclName()
3816 << Init->getSourceRange();
3817 else {
John McCall424cec92011-01-19 06:33:43 +00003818 const Type *BaseClass = Init->getBaseClass();
John McCall23eebd92010-04-10 09:28:51 +00003819 assert(BaseClass && "neither field nor base");
3820 S.Diag(Init->getSourceLocation(),
3821 diag::err_multiple_base_initialization)
3822 << QualType(BaseClass, 0)
3823 << Init->getSourceRange();
3824 }
3825 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3826 << 0 << PrevInit->getSourceRange();
3827
3828 return true;
3829}
3830
Alexis Hunt1d792652011-01-08 20:30:50 +00003831typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall23eebd92010-04-10 09:28:51 +00003832typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3833
3834bool CheckRedundantUnionInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00003835 CXXCtorInitializer *Init,
John McCall23eebd92010-04-10 09:28:51 +00003836 RedundantUnionMap &Unions) {
Francois Pichetd583da02010-12-04 09:14:42 +00003837 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00003838 RecordDecl *Parent = Field->getParent();
John McCall23eebd92010-04-10 09:28:51 +00003839 NamedDecl *Child = Field;
David Blaikie0f65d592011-11-17 06:01:57 +00003840
3841 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall23eebd92010-04-10 09:28:51 +00003842 if (Parent->isUnion()) {
3843 UnionEntry &En = Unions[Parent];
3844 if (En.first && En.first != Child) {
3845 S.Diag(Init->getSourceLocation(),
3846 diag::err_multiple_mem_union_initialization)
3847 << Field->getDeclName()
3848 << Init->getSourceRange();
3849 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3850 << 0 << En.second->getSourceRange();
3851 return true;
David Blaikie256ee192011-11-12 20:54:14 +00003852 }
3853 if (!En.first) {
John McCall23eebd92010-04-10 09:28:51 +00003854 En.first = Child;
3855 En.second = Init;
3856 }
David Blaikie0f65d592011-11-17 06:01:57 +00003857 if (!Parent->isAnonymousStructOrUnion())
3858 return false;
John McCall23eebd92010-04-10 09:28:51 +00003859 }
3860
3861 Child = Parent;
3862 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie0f65d592011-11-17 06:01:57 +00003863 }
John McCall23eebd92010-04-10 09:28:51 +00003864
3865 return false;
3866}
3867}
3868
Anders Carlssone857b292010-04-02 03:37:03 +00003869/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCall48871652010-08-21 09:40:31 +00003870void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlssone857b292010-04-02 03:37:03 +00003871 SourceLocation ColonLoc,
David Blaikie3fc2f912013-01-17 05:26:25 +00003872 ArrayRef<CXXCtorInitializer*> MemInits,
Anders Carlssone857b292010-04-02 03:37:03 +00003873 bool AnyErrors) {
3874 if (!ConstructorDecl)
3875 return;
3876
3877 AdjustDeclIfTemplate(ConstructorDecl);
3878
3879 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00003880 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlssone857b292010-04-02 03:37:03 +00003881
3882 if (!Constructor) {
3883 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3884 return;
3885 }
3886
John McCall23eebd92010-04-10 09:28:51 +00003887 // Mapping for the duplicate initializers check.
3888 // For member initializers, this is keyed with a FieldDecl*.
3889 // For base initializers, this is keyed with a Type*.
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003890 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
John McCall23eebd92010-04-10 09:28:51 +00003891
3892 // Mapping for the inconsistent anonymous-union initializers check.
3893 RedundantUnionMap MemberUnions;
3894
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003895 bool HadError = false;
David Blaikie3fc2f912013-01-17 05:26:25 +00003896 for (unsigned i = 0; i < MemInits.size(); i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003897 CXXCtorInitializer *Init = MemInits[i];
Anders Carlssone857b292010-04-02 03:37:03 +00003898
Abramo Bagnara341d7832010-05-26 18:09:23 +00003899 // Set the source order index.
3900 Init->setSourceOrder(i);
3901
Francois Pichetd583da02010-12-04 09:14:42 +00003902 if (Init->isAnyMemberInitializer()) {
3903 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00003904 if (CheckRedundantInit(*this, Init, Members[Field]) ||
3905 CheckRedundantUnionInit(*this, Init, MemberUnions))
3906 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00003907 } else if (Init->isBaseInitializer()) {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003908 const void *Key =
3909 GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
John McCall23eebd92010-04-10 09:28:51 +00003910 if (CheckRedundantInit(*this, Init, Members[Key]))
3911 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00003912 } else {
3913 assert(Init->isDelegatingInitializer());
3914 // This must be the only initializer
David Blaikie3fc2f912013-01-17 05:26:25 +00003915 if (MemInits.size() != 1) {
Richard Smith21f06f02012-09-14 18:21:10 +00003916 Diag(Init->getSourceLocation(),
Alexis Huntc5575cc2011-02-26 19:13:13 +00003917 diag::err_delegating_initializer_alone)
Richard Smith21f06f02012-09-14 18:21:10 +00003918 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
Alexis Hunt61bc1732011-05-01 07:04:31 +00003919 // We will treat this as being the only initializer.
Alexis Huntc5575cc2011-02-26 19:13:13 +00003920 }
Alexis Hunt6118d662011-05-04 05:57:24 +00003921 SetDelegatingInitializer(Constructor, MemInits[i]);
Alexis Hunt61bc1732011-05-01 07:04:31 +00003922 // Return immediately as the initializer is set.
3923 return;
Anders Carlssone857b292010-04-02 03:37:03 +00003924 }
Anders Carlssone857b292010-04-02 03:37:03 +00003925 }
3926
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003927 if (HadError)
3928 return;
3929
David Blaikie3fc2f912013-01-17 05:26:25 +00003930 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
Anders Carlsson4c8cb012010-04-02 03:43:34 +00003931
David Blaikie3fc2f912013-01-17 05:26:25 +00003932 SetCtorInitializers(Constructor, AnyErrors, MemInits);
Richard Trieu3a446ff2013-09-16 21:54:53 +00003933
Richard Trieuef64e942013-10-25 00:56:00 +00003934 DiagnoseUninitializedFields(*this, Constructor);
Anders Carlssone857b292010-04-02 03:37:03 +00003935}
3936
Fariborz Jahanian37d06562009-09-03 23:18:17 +00003937void
John McCalla6309952010-03-16 21:39:52 +00003938Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3939 CXXRecordDecl *ClassDecl) {
Richard Smith20104042011-09-18 12:11:43 +00003940 // Ignore dependent contexts. Also ignore unions, since their members never
3941 // have destructors implicitly called.
3942 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlssondee9a302009-11-17 04:44:12 +00003943 return;
John McCall1064d7e2010-03-16 05:22:47 +00003944
3945 // FIXME: all the access-control diagnostics are positioned on the
3946 // field/base declaration. That's probably good; that said, the
3947 // user might reasonably want to know why the destructor is being
3948 // emitted, and we currently don't say.
Anders Carlssondee9a302009-11-17 04:44:12 +00003949
Anders Carlssondee9a302009-11-17 04:44:12 +00003950 // Non-static data members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00003951 for (auto *Field : ClassDecl->fields()) {
Fariborz Jahanian16f94c62010-05-17 18:15:18 +00003952 if (Field->isInvalidDecl())
3953 continue;
Douglas Gregor10f939c2011-11-02 23:04:16 +00003954
3955 // Don't destroy incomplete or zero-length arrays.
3956 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3957 continue;
3958
Anders Carlssondee9a302009-11-17 04:44:12 +00003959 QualType FieldType = Context.getBaseElementType(Field->getType());
3960
3961 const RecordType* RT = FieldType->getAs<RecordType>();
3962 if (!RT)
3963 continue;
3964
3965 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00003966 if (FieldClassDecl->isInvalidDecl())
3967 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00003968 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlssondee9a302009-11-17 04:44:12 +00003969 continue;
Richard Smith921bd202012-02-26 09:11:52 +00003970 // The destructor for an implicit anonymous union member is never invoked.
3971 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3972 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00003973
Douglas Gregore71edda2010-07-01 22:47:18 +00003974 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00003975 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00003976 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00003977 PDiag(diag::err_access_dtor_field)
John McCall1064d7e2010-03-16 05:22:47 +00003978 << Field->getDeclName()
3979 << FieldType);
3980
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003981 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00003982 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlssondee9a302009-11-17 04:44:12 +00003983 }
3984
John McCall1064d7e2010-03-16 05:22:47 +00003985 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3986
Anders Carlssondee9a302009-11-17 04:44:12 +00003987 // Bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00003988 for (const auto &Base : ClassDecl->bases()) {
John McCall1064d7e2010-03-16 05:22:47 +00003989 // Bases are always records in a well-formed non-dependent class.
Aaron Ballman574705e2014-03-13 15:41:46 +00003990 const RecordType *RT = Base.getType()->getAs<RecordType>();
John McCall1064d7e2010-03-16 05:22:47 +00003991
3992 // Remember direct virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00003993 if (Base.isVirtual())
John McCall1064d7e2010-03-16 05:22:47 +00003994 DirectVirtualBases.insert(RT);
Anders Carlssondee9a302009-11-17 04:44:12 +00003995
John McCall1064d7e2010-03-16 05:22:47 +00003996 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00003997 // If our base class is invalid, we probably can't get its dtor anyway.
3998 if (BaseClassDecl->isInvalidDecl())
3999 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00004000 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlssondee9a302009-11-17 04:44:12 +00004001 continue;
John McCall1064d7e2010-03-16 05:22:47 +00004002
Douglas Gregore71edda2010-07-01 22:47:18 +00004003 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004004 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00004005
4006 // FIXME: caret should be on the start of the class name
Aaron Ballman574705e2014-03-13 15:41:46 +00004007 CheckDestructorAccess(Base.getLocStart(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00004008 PDiag(diag::err_access_dtor_base)
Aaron Ballman574705e2014-03-13 15:41:46 +00004009 << Base.getType()
4010 << Base.getSourceRange(),
John McCall5dadb652012-04-07 03:04:20 +00004011 Context.getTypeDeclType(ClassDecl));
Anders Carlssondee9a302009-11-17 04:44:12 +00004012
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004013 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00004014 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlssondee9a302009-11-17 04:44:12 +00004015 }
4016
4017 // Virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +00004018 for (const auto &VBase : ClassDecl->vbases()) {
John McCall1064d7e2010-03-16 05:22:47 +00004019 // Bases are always records in a well-formed non-dependent class.
Aaron Ballman445a9392014-03-13 16:15:17 +00004020 const RecordType *RT = VBase.getType()->castAs<RecordType>();
John McCall1064d7e2010-03-16 05:22:47 +00004021
4022 // Ignore direct virtual bases.
4023 if (DirectVirtualBases.count(RT))
4024 continue;
4025
John McCall1064d7e2010-03-16 05:22:47 +00004026 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004027 // If our base class is invalid, we probably can't get its dtor anyway.
4028 if (BaseClassDecl->isInvalidDecl())
4029 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00004030 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian37d06562009-09-03 23:18:17 +00004031 continue;
John McCall1064d7e2010-03-16 05:22:47 +00004032
Douglas Gregore71edda2010-07-01 22:47:18 +00004033 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004034 assert(Dtor && "No dtor found for BaseClassDecl!");
David Majnemer626032f2013-06-22 06:43:58 +00004035 if (CheckDestructorAccess(
4036 ClassDecl->getLocation(), Dtor,
4037 PDiag(diag::err_access_dtor_vbase)
Aaron Ballman445a9392014-03-13 16:15:17 +00004038 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
David Majnemer626032f2013-06-22 06:43:58 +00004039 Context.getTypeDeclType(ClassDecl)) ==
4040 AR_accessible) {
4041 CheckDerivedToBaseConversion(
Aaron Ballman445a9392014-03-13 16:15:17 +00004042 Context.getTypeDeclType(ClassDecl), VBase.getType(),
David Majnemer626032f2013-06-22 06:43:58 +00004043 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
4044 SourceRange(), DeclarationName(), 0);
4045 }
John McCall1064d7e2010-03-16 05:22:47 +00004046
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004047 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00004048 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian37d06562009-09-03 23:18:17 +00004049 }
4050}
4051
John McCall48871652010-08-21 09:40:31 +00004052void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00004053 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00004054 return;
Mike Stump11289f42009-09-09 15:08:12 +00004055
Mike Stump11289f42009-09-09 15:08:12 +00004056 if (CXXConstructorDecl *Constructor
Richard Trieuef64e942013-10-25 00:56:00 +00004057 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
David Blaikie3fc2f912013-01-17 05:26:25 +00004058 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
Richard Trieuef64e942013-10-25 00:56:00 +00004059 DiagnoseUninitializedFields(*this, Constructor);
4060 }
Fariborz Jahanian49c81792009-07-14 18:24:21 +00004061}
4062
Mike Stump11289f42009-09-09 15:08:12 +00004063bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00004064 unsigned DiagID, AbstractDiagSelID SelID) {
Douglas Gregorae298422012-05-04 17:09:59 +00004065 class NonAbstractTypeDiagnoser : public TypeDiagnoser {
4066 unsigned DiagID;
4067 AbstractDiagSelID SelID;
4068
4069 public:
4070 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
4071 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004072
Craig Toppera798a9d2014-03-02 09:32:10 +00004073 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00004074 if (Suppressed) return;
Douglas Gregorae298422012-05-04 17:09:59 +00004075 if (SelID == -1)
4076 S.Diag(Loc, DiagID) << T;
4077 else
4078 S.Diag(Loc, DiagID) << SelID << T;
4079 }
4080 } Diagnoser(DiagID, SelID);
4081
4082 return RequireNonAbstractType(Loc, T, Diagnoser);
Mike Stump11289f42009-09-09 15:08:12 +00004083}
4084
Anders Carlssoneabf7702009-08-27 00:13:57 +00004085bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Douglas Gregorae298422012-05-04 17:09:59 +00004086 TypeDiagnoser &Diagnoser) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00004087 if (!getLangOpts().CPlusPlus)
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004088 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004089
Anders Carlssoneb0c5322009-03-23 19:10:31 +00004090 if (const ArrayType *AT = Context.getAsArrayType(T))
Douglas Gregorae298422012-05-04 17:09:59 +00004091 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Mike Stump11289f42009-09-09 15:08:12 +00004092
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004093 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004094 // Find the innermost pointer type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004095 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004096 PT = T;
Mike Stump11289f42009-09-09 15:08:12 +00004097
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004098 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Douglas Gregorae298422012-05-04 17:09:59 +00004099 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004100 }
Mike Stump11289f42009-09-09 15:08:12 +00004101
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004102 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004103 if (!RT)
4104 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004105
John McCall67da35c2010-02-04 22:26:26 +00004106 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004107
John McCall02db245d2010-08-18 09:41:07 +00004108 // We can't answer whether something is abstract until it has a
4109 // definition. If it's currently being defined, we'll walk back
4110 // over all the declarations when we have a full definition.
4111 const CXXRecordDecl *Def = RD->getDefinition();
4112 if (!Def || Def->isBeingDefined())
John McCall67da35c2010-02-04 22:26:26 +00004113 return false;
4114
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004115 if (!RD->isAbstract())
4116 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004117
Douglas Gregorae298422012-05-04 17:09:59 +00004118 Diagnoser.diagnose(*this, Loc, T);
John McCall02db245d2010-08-18 09:41:07 +00004119 DiagnoseAbstractType(RD);
Mike Stump11289f42009-09-09 15:08:12 +00004120
John McCall02db245d2010-08-18 09:41:07 +00004121 return true;
4122}
4123
4124void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
4125 // Check if we've already emitted the list of pure virtual functions
4126 // for this class.
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004127 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall02db245d2010-08-18 09:41:07 +00004128 return;
Mike Stump11289f42009-09-09 15:08:12 +00004129
Richard Smithbc46e432013-07-22 02:56:56 +00004130 // If the diagnostic is suppressed, don't emit the notes. We're only
4131 // going to emit them once, so try to attach them to a diagnostic we're
4132 // actually going to show.
4133 if (Diags.isLastDiagnosticIgnored())
4134 return;
4135
Douglas Gregor4165bd62010-03-23 23:47:56 +00004136 CXXFinalOverriderMap FinalOverriders;
4137 RD->getFinalOverriders(FinalOverriders);
Mike Stump11289f42009-09-09 15:08:12 +00004138
Anders Carlssona2f74f32010-06-03 01:00:02 +00004139 // Keep a set of seen pure methods so we won't diagnose the same method
4140 // more than once.
4141 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
4142
Douglas Gregor4165bd62010-03-23 23:47:56 +00004143 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
4144 MEnd = FinalOverriders.end();
4145 M != MEnd;
4146 ++M) {
4147 for (OverridingMethods::iterator SO = M->second.begin(),
4148 SOEnd = M->second.end();
4149 SO != SOEnd; ++SO) {
4150 // C++ [class.abstract]p4:
4151 // A class is abstract if it contains or inherits at least one
4152 // pure virtual function for which the final overrider is pure
4153 // virtual.
Mike Stump11289f42009-09-09 15:08:12 +00004154
Douglas Gregor4165bd62010-03-23 23:47:56 +00004155 //
4156 if (SO->second.size() != 1)
4157 continue;
4158
4159 if (!SO->second.front().Method->isPure())
4160 continue;
4161
Anders Carlssona2f74f32010-06-03 01:00:02 +00004162 if (!SeenPureMethods.insert(SO->second.front().Method))
4163 continue;
4164
Douglas Gregor4165bd62010-03-23 23:47:56 +00004165 Diag(SO->second.front().Method->getLocation(),
4166 diag::note_pure_virtual_function)
Chandler Carruth98e3c562011-02-18 23:59:51 +00004167 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor4165bd62010-03-23 23:47:56 +00004168 }
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004169 }
4170
4171 if (!PureVirtualClassDiagSet)
4172 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
4173 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004174}
4175
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004176namespace {
John McCall02db245d2010-08-18 09:41:07 +00004177struct AbstractUsageInfo {
4178 Sema &S;
4179 CXXRecordDecl *Record;
4180 CanQualType AbstractType;
4181 bool Invalid;
Mike Stump11289f42009-09-09 15:08:12 +00004182
John McCall02db245d2010-08-18 09:41:07 +00004183 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
4184 : S(S), Record(Record),
4185 AbstractType(S.Context.getCanonicalType(
4186 S.Context.getTypeDeclType(Record))),
4187 Invalid(false) {}
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004188
John McCall02db245d2010-08-18 09:41:07 +00004189 void DiagnoseAbstractType() {
4190 if (Invalid) return;
4191 S.DiagnoseAbstractType(Record);
4192 Invalid = true;
4193 }
Anders Carlssonb57738b2009-03-24 17:23:42 +00004194
John McCall02db245d2010-08-18 09:41:07 +00004195 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
4196};
4197
4198struct CheckAbstractUsage {
4199 AbstractUsageInfo &Info;
4200 const NamedDecl *Ctx;
4201
4202 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
4203 : Info(Info), Ctx(Ctx) {}
4204
4205 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4206 switch (TL.getTypeLocClass()) {
4207#define ABSTRACT_TYPELOC(CLASS, PARENT)
4208#define TYPELOC(CLASS, PARENT) \
David Blaikie6adc78e2013-02-18 22:06:02 +00004209 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
John McCall02db245d2010-08-18 09:41:07 +00004210#include "clang/AST/TypeLocNodes.def"
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004211 }
John McCall02db245d2010-08-18 09:41:07 +00004212 }
Mike Stump11289f42009-09-09 15:08:12 +00004213
John McCall02db245d2010-08-18 09:41:07 +00004214 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
Alp Toker42a16a62014-01-25 23:51:36 +00004215 Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004216 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
4217 if (!TL.getParam(I))
Douglas Gregor385d3fd2011-02-22 23:21:06 +00004218 continue;
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004219
4220 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
John McCall02db245d2010-08-18 09:41:07 +00004221 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssonb57738b2009-03-24 17:23:42 +00004222 }
John McCall02db245d2010-08-18 09:41:07 +00004223 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004224
John McCall02db245d2010-08-18 09:41:07 +00004225 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4226 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
4227 }
Mike Stump11289f42009-09-09 15:08:12 +00004228
John McCall02db245d2010-08-18 09:41:07 +00004229 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4230 // Visit the type parameters from a permissive context.
4231 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
4232 TemplateArgumentLoc TAL = TL.getArgLoc(I);
4233 if (TAL.getArgument().getKind() == TemplateArgument::Type)
4234 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
4235 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
4236 // TODO: other template argument types?
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004237 }
John McCall02db245d2010-08-18 09:41:07 +00004238 }
Mike Stump11289f42009-09-09 15:08:12 +00004239
John McCall02db245d2010-08-18 09:41:07 +00004240 // Visit pointee types from a permissive context.
4241#define CheckPolymorphic(Type) \
4242 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
4243 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
4244 }
4245 CheckPolymorphic(PointerTypeLoc)
4246 CheckPolymorphic(ReferenceTypeLoc)
4247 CheckPolymorphic(MemberPointerTypeLoc)
4248 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedman0dfb8892011-10-06 23:00:33 +00004249 CheckPolymorphic(AtomicTypeLoc)
Mike Stump11289f42009-09-09 15:08:12 +00004250
John McCall02db245d2010-08-18 09:41:07 +00004251 /// Handle all the types we haven't given a more specific
4252 /// implementation for above.
4253 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4254 // Every other kind of type that we haven't called out already
4255 // that has an inner type is either (1) sugar or (2) contains that
4256 // inner type in some way as a subobject.
4257 if (TypeLoc Next = TL.getNextTypeLoc())
4258 return Visit(Next, Sel);
4259
4260 // If there's no inner type and we're in a permissive context,
4261 // don't diagnose.
4262 if (Sel == Sema::AbstractNone) return;
4263
4264 // Check whether the type matches the abstract type.
4265 QualType T = TL.getType();
4266 if (T->isArrayType()) {
4267 Sel = Sema::AbstractArrayType;
4268 T = Info.S.Context.getBaseElementType(T);
Anders Carlssonb57738b2009-03-24 17:23:42 +00004269 }
John McCall02db245d2010-08-18 09:41:07 +00004270 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
4271 if (CT != Info.AbstractType) return;
4272
4273 // It matched; do some magic.
4274 if (Sel == Sema::AbstractArrayType) {
4275 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
4276 << T << TL.getSourceRange();
4277 } else {
4278 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
4279 << Sel << T << TL.getSourceRange();
4280 }
4281 Info.DiagnoseAbstractType();
4282 }
4283};
4284
4285void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
4286 Sema::AbstractDiagSelID Sel) {
4287 CheckAbstractUsage(*this, D).Visit(TL, Sel);
4288}
4289
4290}
4291
4292/// Check for invalid uses of an abstract type in a method declaration.
4293static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4294 CXXMethodDecl *MD) {
4295 // No need to do the check on definitions, which require that
4296 // the return/param types be complete.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00004297 if (MD->doesThisDeclarationHaveABody())
John McCall02db245d2010-08-18 09:41:07 +00004298 return;
4299
4300 // For safety's sake, just ignore it if we don't have type source
4301 // information. This should never happen for non-implicit methods,
4302 // but...
4303 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
4304 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
4305}
4306
4307/// Check for invalid uses of an abstract type within a class definition.
4308static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4309 CXXRecordDecl *RD) {
Aaron Ballman629afae2014-03-07 19:56:05 +00004310 for (auto *D : RD->decls()) {
John McCall02db245d2010-08-18 09:41:07 +00004311 if (D->isImplicit()) continue;
4312
4313 // Methods and method templates.
4314 if (isa<CXXMethodDecl>(D)) {
4315 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
4316 } else if (isa<FunctionTemplateDecl>(D)) {
4317 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
4318 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
4319
4320 // Fields and static variables.
4321 } else if (isa<FieldDecl>(D)) {
4322 FieldDecl *FD = cast<FieldDecl>(D);
4323 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
4324 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
4325 } else if (isa<VarDecl>(D)) {
4326 VarDecl *VD = cast<VarDecl>(D);
4327 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
4328 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
4329
4330 // Nested classes and class templates.
4331 } else if (isa<CXXRecordDecl>(D)) {
4332 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
4333 } else if (isa<ClassTemplateDecl>(D)) {
4334 CheckAbstractClassUsage(Info,
4335 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
4336 }
4337 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004338}
4339
Douglas Gregorc99f1552009-12-03 18:33:45 +00004340/// \brief Perform semantic checks on a class definition that has been
4341/// completing, introducing implicitly-declared members, checking for
4342/// abstract types, etc.
Douglas Gregor0be31a22010-07-02 17:43:08 +00004343void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +00004344 if (!Record)
Douglas Gregorc99f1552009-12-03 18:33:45 +00004345 return;
4346
John McCall02db245d2010-08-18 09:41:07 +00004347 if (Record->isAbstract() && !Record->isInvalidDecl()) {
4348 AbstractUsageInfo Info(*this, Record);
4349 CheckAbstractClassUsage(Info, Record);
4350 }
Douglas Gregor454a5b62010-04-15 00:00:53 +00004351
4352 // If this is not an aggregate type and has no user-declared constructor,
4353 // complain about any non-static data members of reference or const scalar
4354 // type, since they will never get initializers.
4355 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregorfbf19a02012-02-09 02:20:38 +00004356 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
4357 !Record->isLambda()) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00004358 bool Complained = false;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004359 for (const auto *F : Record->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +00004360 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith938f40b2011-06-11 17:19:42 +00004361 continue;
4362
Douglas Gregor454a5b62010-04-15 00:00:53 +00004363 if (F->getType()->isReferenceType() ||
Benjamin Kramer659d7fc2010-04-16 17:43:15 +00004364 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00004365 if (!Complained) {
4366 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
4367 << Record->getTagKind() << Record;
4368 Complained = true;
4369 }
4370
4371 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4372 << F->getType()->isReferenceType()
4373 << F->getDeclName();
4374 }
4375 }
4376 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00004377
Anders Carlssone771e762011-01-25 18:08:22 +00004378 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor88d292c2010-05-13 16:44:06 +00004379 DynamicClasses.push_back(Record);
Douglas Gregor36c22a22010-10-15 13:21:21 +00004380
4381 if (Record->getIdentifier()) {
4382 // C++ [class.mem]p13:
4383 // If T is the name of a class, then each of the following shall have a
4384 // name different from T:
4385 // - every member of every anonymous union that is a member of class T.
4386 //
4387 // C++ [class.mem]p14:
4388 // In addition, if class T has a user-declared constructor (12.1), every
4389 // non-static data member of class T shall have a name different from T.
David Blaikieff7d47a2012-12-19 00:45:41 +00004390 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4391 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4392 ++I) {
4393 NamedDecl *D = *I;
Francois Pichet783dd6e2010-11-21 06:08:52 +00004394 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4395 isa<IndirectFieldDecl>(D)) {
4396 Diag(D->getLocation(), diag::err_member_name_of_class)
4397 << D->getDeclName();
Douglas Gregor36c22a22010-10-15 13:21:21 +00004398 break;
4399 }
Francois Pichet783dd6e2010-11-21 06:08:52 +00004400 }
Douglas Gregor36c22a22010-10-15 13:21:21 +00004401 }
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004402
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00004403 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregor0cf82f62011-02-19 19:14:36 +00004404 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004405 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00004406 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004407 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4408 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4409 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004410
David Majnemera5433082013-10-18 00:33:31 +00004411 if (Record->isAbstract()) {
4412 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
4413 Diag(Record->getLocation(), diag::warn_abstract_final_class)
4414 << FA->isSpelledAsSealed();
4415 DiagnoseAbstractType(Record);
4416 }
David Blaikie348df502012-09-21 03:21:07 +00004417 }
4418
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004419 if (!Record->isDependentType()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00004420 for (auto *M : Record->methods()) {
Richard Smithbd305122012-12-11 01:14:52 +00004421 // See if a method overloads virtual methods in a base
4422 // class without overriding any.
David Blaikie2d7c57e2012-04-30 02:36:29 +00004423 if (!M->isStatic())
Aaron Ballman2b124d12014-03-13 16:36:16 +00004424 DiagnoseHiddenVirtualMethods(M);
Richard Smithbd305122012-12-11 01:14:52 +00004425
4426 // Check whether the explicitly-defaulted special members are valid.
4427 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
Aaron Ballman2b124d12014-03-13 16:36:16 +00004428 CheckExplicitlyDefaultedSpecialMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00004429
4430 // For an explicitly defaulted or deleted special member, we defer
4431 // determining triviality until the class is complete. That time is now!
4432 if (!M->isImplicit() && !M->isUserProvided()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00004433 CXXSpecialMember CSM = getSpecialMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00004434 if (CSM != CXXInvalid) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00004435 M->setTrivial(SpecialMemberIsTrivial(M, CSM));
Richard Smithbd305122012-12-11 01:14:52 +00004436
4437 // Inform the class that we've finished declaring this member.
Aaron Ballman2b124d12014-03-13 16:36:16 +00004438 Record->finishedDefaultedOrDeletedMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00004439 }
4440 }
4441 }
4442 }
4443
4444 // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member
4445 // function that is not a constructor declares that member function to be
4446 // const. [...] The class of which that function is a member shall be
4447 // a literal type.
4448 //
4449 // If the class has virtual bases, any constexpr members will already have
4450 // been diagnosed by the checks performed on the member declaration, so
4451 // suppress this (less useful) diagnostic.
4452 //
4453 // We delay this until we know whether an explicitly-defaulted (or deleted)
4454 // destructor for the class is trivial.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004455 if (LangOpts.CPlusPlus11 && !Record->isDependentType() &&
Richard Smithbd305122012-12-11 01:14:52 +00004456 !Record->isLiteral() && !Record->getNumVBases()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00004457 for (const auto *M : Record->methods()) {
4458 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(M)) {
Richard Smithbd305122012-12-11 01:14:52 +00004459 switch (Record->getTemplateSpecializationKind()) {
4460 case TSK_ImplicitInstantiation:
4461 case TSK_ExplicitInstantiationDeclaration:
4462 case TSK_ExplicitInstantiationDefinition:
4463 // If a template instantiates to a non-literal type, but its members
4464 // instantiate to constexpr functions, the template is technically
4465 // ill-formed, but we allow it for sanity.
4466 continue;
4467
4468 case TSK_Undeclared:
4469 case TSK_ExplicitSpecialization:
4470 RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
4471 diag::err_constexpr_method_non_literal);
4472 break;
4473 }
4474
4475 // Only produce one error per class.
4476 break;
4477 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004478 }
4479 }
Sebastian Redl08905022011-02-05 19:23:19 +00004480
John McCall95833f32014-02-27 20:30:49 +00004481 // ms_struct is a request to use the same ABI rules as MSVC. Check
4482 // whether this class uses any C++ features that are implemented
4483 // completely differently in MSVC, and if so, emit a diagnostic.
4484 // That diagnostic defaults to an error, but we allow projects to
4485 // map it down to a warning (or ignore it). It's a fairly common
4486 // practice among users of the ms_struct pragma to mass-annotate
4487 // headers, sweeping up a bunch of types that the project doesn't
4488 // really rely on MSVC-compatible layout for. We must therefore
4489 // support "ms_struct except for C++ stuff" as a secondary ABI.
4490 if (Record->isMsStruct(Context) &&
4491 (Record->isPolymorphic() || Record->getNumBases())) {
4492 Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
Warren Hunt8f8bad72013-10-11 20:19:00 +00004493 }
4494
Richard Smithc2bc61b2013-03-18 21:12:30 +00004495 // Declare inheriting constructors. We do this eagerly here because:
4496 // - The standard requires an eager diagnostic for conflicting inheriting
Sebastian Redl08905022011-02-05 19:23:19 +00004497 // constructors from different classes.
4498 // - The lazy declaration of the other implicit constructors is so as to not
4499 // waste space and performance on classes that are not meant to be
4500 // instantiated (e.g. meta-functions). This doesn't apply to classes that
Richard Smithc2bc61b2013-03-18 21:12:30 +00004501 // have inheriting constructors.
4502 DeclareInheritingConstructors(Record);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00004503}
4504
Richard Smith41c35d62013-11-27 03:39:20 +00004505/// Look up the special member function that would be called by a special
4506/// member function for a subobject of class type.
4507///
4508/// \param Class The class type of the subobject.
4509/// \param CSM The kind of special member function.
4510/// \param FieldQuals If the subobject is a field, its cv-qualifiers.
4511/// \param ConstRHS True if this is a copy operation with a const object
4512/// on its RHS, that is, if the argument to the outer special member
4513/// function is 'const' and this is not a field marked 'mutable'.
4514static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember(
4515 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
4516 unsigned FieldQuals, bool ConstRHS) {
4517 unsigned LHSQuals = 0;
4518 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
4519 LHSQuals = FieldQuals;
4520
4521 unsigned RHSQuals = FieldQuals;
4522 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4523 RHSQuals = 0;
4524 else if (ConstRHS)
4525 RHSQuals |= Qualifiers::Const;
4526
4527 return S.LookupSpecialMember(Class, CSM,
4528 RHSQuals & Qualifiers::Const,
4529 RHSQuals & Qualifiers::Volatile,
4530 false,
4531 LHSQuals & Qualifiers::Const,
4532 LHSQuals & Qualifiers::Volatile);
4533}
4534
Richard Smithb5800092012-06-10 05:43:50 +00004535/// Is the special member function which would be selected to perform the
4536/// specified operation on the specified class type a constexpr constructor?
4537static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4538 Sema::CXXSpecialMember CSM,
Richard Smith41c35d62013-11-27 03:39:20 +00004539 unsigned Quals, bool ConstRHS) {
Richard Smithb5800092012-06-10 05:43:50 +00004540 Sema::SpecialMemberOverloadResult *SMOR =
Richard Smith41c35d62013-11-27 03:39:20 +00004541 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
Richard Smithb5800092012-06-10 05:43:50 +00004542 if (!SMOR || !SMOR->getMethod())
4543 // A constructor we wouldn't select can't be "involved in initializing"
4544 // anything.
4545 return true;
4546 return SMOR->getMethod()->isConstexpr();
4547}
4548
4549/// Determine whether the specified special member function would be constexpr
4550/// if it were implicitly defined.
4551static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4552 Sema::CXXSpecialMember CSM,
4553 bool ConstArg) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004554 if (!S.getLangOpts().CPlusPlus11)
Richard Smithb5800092012-06-10 05:43:50 +00004555 return false;
4556
4557 // C++11 [dcl.constexpr]p4:
4558 // In the definition of a constexpr constructor [...]
Richard Smith99005e62013-05-07 03:19:20 +00004559 bool Ctor = true;
Richard Smithb5800092012-06-10 05:43:50 +00004560 switch (CSM) {
4561 case Sema::CXXDefaultConstructor:
Richard Smith4086a132012-06-10 07:07:24 +00004562 // Since default constructor lookup is essentially trivial (and cannot
4563 // involve, for instance, template instantiation), we compute whether a
4564 // defaulted default constructor is constexpr directly within CXXRecordDecl.
4565 //
4566 // This is important for performance; we need to know whether the default
4567 // constructor is constexpr to determine whether the type is a literal type.
4568 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4569
Richard Smithb5800092012-06-10 05:43:50 +00004570 case Sema::CXXCopyConstructor:
4571 case Sema::CXXMoveConstructor:
Richard Smith4086a132012-06-10 07:07:24 +00004572 // For copy or move constructors, we need to perform overload resolution.
Richard Smithb5800092012-06-10 05:43:50 +00004573 break;
4574
4575 case Sema::CXXCopyAssignment:
4576 case Sema::CXXMoveAssignment:
Richard Smith99005e62013-05-07 03:19:20 +00004577 if (!S.getLangOpts().CPlusPlus1y)
4578 return false;
4579 // In C++1y, we need to perform overload resolution.
4580 Ctor = false;
4581 break;
4582
Richard Smithb5800092012-06-10 05:43:50 +00004583 case Sema::CXXDestructor:
4584 case Sema::CXXInvalid:
4585 return false;
4586 }
4587
4588 // -- if the class is a non-empty union, or for each non-empty anonymous
4589 // union member of a non-union class, exactly one non-static data member
4590 // shall be initialized; [DR1359]
Richard Smith4086a132012-06-10 07:07:24 +00004591 //
4592 // If we squint, this is guaranteed, since exactly one non-static data member
4593 // will be initialized (if the constructor isn't deleted), we just don't know
4594 // which one.
Richard Smith99005e62013-05-07 03:19:20 +00004595 if (Ctor && ClassDecl->isUnion())
Richard Smith4086a132012-06-10 07:07:24 +00004596 return true;
Richard Smithb5800092012-06-10 05:43:50 +00004597
4598 // -- the class shall not have any virtual base classes;
Richard Smith99005e62013-05-07 03:19:20 +00004599 if (Ctor && ClassDecl->getNumVBases())
4600 return false;
4601
4602 // C++1y [class.copy]p26:
4603 // -- [the class] is a literal type, and
4604 if (!Ctor && !ClassDecl->isLiteral())
Richard Smithb5800092012-06-10 05:43:50 +00004605 return false;
4606
4607 // -- every constructor involved in initializing [...] base class
4608 // sub-objects shall be a constexpr constructor;
Richard Smith99005e62013-05-07 03:19:20 +00004609 // -- the assignment operator selected to copy/move each direct base
4610 // class is a constexpr function, and
Aaron Ballman574705e2014-03-13 15:41:46 +00004611 for (const auto &B : ClassDecl->bases()) {
4612 const RecordType *BaseType = B.getType()->getAs<RecordType>();
Richard Smithb5800092012-06-10 05:43:50 +00004613 if (!BaseType) continue;
4614
4615 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith41c35d62013-11-27 03:39:20 +00004616 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg))
Richard Smithb5800092012-06-10 05:43:50 +00004617 return false;
4618 }
4619
4620 // -- every constructor involved in initializing non-static data members
4621 // [...] shall be a constexpr constructor;
4622 // -- every non-static data member and base class sub-object shall be
4623 // initialized
Richard Smith41c35d62013-11-27 03:39:20 +00004624 // -- for each non-static data member of X that is of class type (or array
Richard Smith99005e62013-05-07 03:19:20 +00004625 // thereof), the assignment operator selected to copy/move that member is
4626 // a constexpr function
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004627 for (const auto *F : ClassDecl->fields()) {
Richard Smithb5800092012-06-10 05:43:50 +00004628 if (F->isInvalidDecl())
4629 continue;
Richard Smith41c35d62013-11-27 03:39:20 +00004630 QualType BaseType = S.Context.getBaseElementType(F->getType());
4631 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
Richard Smithb5800092012-06-10 05:43:50 +00004632 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith41c35d62013-11-27 03:39:20 +00004633 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
4634 BaseType.getCVRQualifiers(),
4635 ConstArg && !F->isMutable()))
Richard Smithb5800092012-06-10 05:43:50 +00004636 return false;
Richard Smithb5800092012-06-10 05:43:50 +00004637 }
4638 }
4639
4640 // All OK, it's constexpr!
4641 return true;
4642}
4643
Richard Smithd3b5c9082012-07-27 04:22:15 +00004644static Sema::ImplicitExceptionSpecification
4645computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
4646 switch (S.getSpecialMember(MD)) {
4647 case Sema::CXXDefaultConstructor:
4648 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
4649 case Sema::CXXCopyConstructor:
4650 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
4651 case Sema::CXXCopyAssignment:
4652 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4653 case Sema::CXXMoveConstructor:
4654 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
4655 case Sema::CXXMoveAssignment:
4656 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
4657 case Sema::CXXDestructor:
4658 return S.ComputeDefaultedDtorExceptionSpec(MD);
4659 case Sema::CXXInvalid:
4660 break;
4661 }
Richard Smithc2bc61b2013-03-18 21:12:30 +00004662 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
4663 "only special members have implicit exception specs");
4664 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
Richard Smithd3b5c9082012-07-27 04:22:15 +00004665}
4666
Richard Smith7f782272012-07-30 23:48:14 +00004667static void
4668updateExceptionSpec(Sema &S, FunctionDecl *FD, const FunctionProtoType *FPT,
4669 const Sema::ImplicitExceptionSpecification &ExceptSpec) {
4670 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
4671 ExceptSpec.getEPI(EPI);
Alp Toker314cc812014-01-25 16:55:45 +00004672 FD->setType(S.Context.getFunctionType(FPT->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00004673 FPT->getParamTypes(), EPI));
Richard Smith7f782272012-07-30 23:48:14 +00004674}
4675
Reid Kleckner78af0702013-08-27 23:08:25 +00004676static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
4677 CXXMethodDecl *MD) {
4678 FunctionProtoType::ExtProtoInfo EPI;
4679
4680 // Build an exception specification pointing back at this member.
4681 EPI.ExceptionSpecType = EST_Unevaluated;
4682 EPI.ExceptionSpecDecl = MD;
4683
4684 // Set the calling convention to the default for C++ instance methods.
4685 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
4686 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
4687 /*IsCXXMethod=*/true));
4688 return EPI;
4689}
4690
Richard Smithd3b5c9082012-07-27 04:22:15 +00004691void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4692 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4693 if (FPT->getExceptionSpecType() != EST_Unevaluated)
4694 return;
4695
Richard Smith7f782272012-07-30 23:48:14 +00004696 // Evaluate the exception specification.
4697 ImplicitExceptionSpecification ExceptSpec =
4698 computeImplicitExceptionSpec(*this, Loc, MD);
4699
4700 // Update the type of the special member to use it.
4701 updateExceptionSpec(*this, MD, FPT, ExceptSpec);
4702
4703 // A user-provided destructor can be defined outside the class. When that
4704 // happens, be sure to update the exception specification on both
4705 // declarations.
4706 const FunctionProtoType *CanonicalFPT =
4707 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4708 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
4709 updateExceptionSpec(*this, MD->getCanonicalDecl(),
4710 CanonicalFPT, ExceptSpec);
Richard Smithd3b5c9082012-07-27 04:22:15 +00004711}
4712
Richard Smithb9e90b12012-05-15 04:39:51 +00004713void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4714 CXXRecordDecl *RD = MD->getParent();
4715 CXXSpecialMember CSM = getSpecialMember(MD);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00004716
Richard Smithb9e90b12012-05-15 04:39:51 +00004717 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4718 "not an explicitly-defaulted special member");
Alexis Hunt913820d2011-05-13 06:10:58 +00004719
4720 // Whether this was the first-declared instance of the constructor.
Richard Smithb9e90b12012-05-15 04:39:51 +00004721 // This affects whether we implicitly add an exception spec and constexpr.
Alexis Huntc9a55732011-05-14 05:23:28 +00004722 bool First = MD == MD->getCanonicalDecl();
4723
4724 bool HadError = false;
Richard Smithb9e90b12012-05-15 04:39:51 +00004725
4726 // C++11 [dcl.fct.def.default]p1:
4727 // A function that is explicitly defaulted shall
4728 // -- be a special member function (checked elsewhere),
4729 // -- have the same type (except for ref-qualifiers, and except that a
4730 // copy operation can take a non-const reference) as an implicit
4731 // declaration, and
4732 // -- not have default arguments.
4733 unsigned ExpectedParams = 1;
4734 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4735 ExpectedParams = 0;
4736 if (MD->getNumParams() != ExpectedParams) {
4737 // This also checks for default arguments: a copy or move constructor with a
4738 // default argument is classified as a default constructor, and assignment
4739 // operations and destructors can't have default arguments.
4740 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4741 << CSM << MD->getSourceRange();
Alexis Huntc9a55732011-05-14 05:23:28 +00004742 HadError = true;
Richard Smith50d705b2012-12-07 02:10:28 +00004743 } else if (MD->isVariadic()) {
4744 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
4745 << CSM << MD->getSourceRange();
4746 HadError = true;
Alexis Huntc9a55732011-05-14 05:23:28 +00004747 }
4748
Richard Smithb9e90b12012-05-15 04:39:51 +00004749 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
Alexis Huntc9a55732011-05-14 05:23:28 +00004750
Richard Smithb5800092012-06-10 05:43:50 +00004751 bool CanHaveConstParam = false;
Richard Smith92f241f2012-12-08 02:53:02 +00004752 if (CSM == CXXCopyConstructor)
Richard Smith1c33fe82012-11-28 06:23:12 +00004753 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
Richard Smith92f241f2012-12-08 02:53:02 +00004754 else if (CSM == CXXCopyAssignment)
Richard Smith1c33fe82012-11-28 06:23:12 +00004755 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
Alexis Huntc9a55732011-05-14 05:23:28 +00004756
Richard Smithb9e90b12012-05-15 04:39:51 +00004757 QualType ReturnType = Context.VoidTy;
4758 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4759 // Check for return type matching.
Alp Toker314cc812014-01-25 16:55:45 +00004760 ReturnType = Type->getReturnType();
Richard Smithb9e90b12012-05-15 04:39:51 +00004761 QualType ExpectedReturnType =
4762 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4763 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4764 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4765 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4766 HadError = true;
4767 }
4768
4769 // A defaulted special member cannot have cv-qualifiers.
4770 if (Type->getTypeQuals()) {
4771 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
Richard Smith99005e62013-05-07 03:19:20 +00004772 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus1y;
Richard Smithb9e90b12012-05-15 04:39:51 +00004773 HadError = true;
4774 }
4775 }
4776
4777 // Check for parameter type matching.
Alp Toker9cacbab2014-01-20 20:26:09 +00004778 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
Richard Smithb5800092012-06-10 05:43:50 +00004779 bool HasConstParam = false;
Richard Smithb9e90b12012-05-15 04:39:51 +00004780 if (ExpectedParams && ArgType->isReferenceType()) {
4781 // Argument must be reference to possibly-const T.
4782 QualType ReferentType = ArgType->getPointeeType();
Richard Smithb5800092012-06-10 05:43:50 +00004783 HasConstParam = ReferentType.isConstQualified();
Richard Smithb9e90b12012-05-15 04:39:51 +00004784
4785 if (ReferentType.isVolatileQualified()) {
4786 Diag(MD->getLocation(),
4787 diag::err_defaulted_special_member_volatile_param) << CSM;
4788 HadError = true;
4789 }
4790
Richard Smithb5800092012-06-10 05:43:50 +00004791 if (HasConstParam && !CanHaveConstParam) {
Richard Smithb9e90b12012-05-15 04:39:51 +00004792 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4793 Diag(MD->getLocation(),
4794 diag::err_defaulted_special_member_copy_const_param)
4795 << (CSM == CXXCopyAssignment);
4796 // FIXME: Explain why this special member can't be const.
4797 } else {
4798 Diag(MD->getLocation(),
4799 diag::err_defaulted_special_member_move_const_param)
4800 << (CSM == CXXMoveAssignment);
4801 }
4802 HadError = true;
4803 }
Richard Smithb9e90b12012-05-15 04:39:51 +00004804 } else if (ExpectedParams) {
4805 // A copy assignment operator can take its argument by value, but a
4806 // defaulted one cannot.
4807 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Alexis Hunt604aeb32011-05-17 20:44:43 +00004808 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Alexis Huntc9a55732011-05-14 05:23:28 +00004809 HadError = true;
4810 }
Alexis Hunt604aeb32011-05-17 20:44:43 +00004811
Richard Smithcc36f692011-12-22 02:22:31 +00004812 // C++11 [dcl.fct.def.default]p2:
4813 // An explicitly-defaulted function may be declared constexpr only if it
4814 // would have been implicitly declared as constexpr,
Richard Smithb9e90b12012-05-15 04:39:51 +00004815 // Do not apply this rule to members of class templates, since core issue 1358
4816 // makes such functions always instantiate to constexpr functions. For
Richard Smith99005e62013-05-07 03:19:20 +00004817 // functions which cannot be constexpr (for non-constructors in C++11 and for
4818 // destructors in C++1y), this is checked elsewhere.
Richard Smithb5800092012-06-10 05:43:50 +00004819 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4820 HasConstParam);
Richard Smith99005e62013-05-07 03:19:20 +00004821 if ((getLangOpts().CPlusPlus1y ? !isa<CXXDestructorDecl>(MD)
4822 : isa<CXXConstructorDecl>(MD)) &&
4823 MD->isConstexpr() && !Constexpr &&
Richard Smithb9e90b12012-05-15 04:39:51 +00004824 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4825 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
Richard Smith99005e62013-05-07 03:19:20 +00004826 // FIXME: Explain why the special member can't be constexpr.
Richard Smithb9e90b12012-05-15 04:39:51 +00004827 HadError = true;
Richard Smithcc36f692011-12-22 02:22:31 +00004828 }
Richard Smithbd305122012-12-11 01:14:52 +00004829
Richard Smithcc36f692011-12-22 02:22:31 +00004830 // and may have an explicit exception-specification only if it is compatible
4831 // with the exception-specification on the implicit declaration.
Richard Smithbd305122012-12-11 01:14:52 +00004832 if (Type->hasExceptionSpec()) {
4833 // Delay the check if this is the first declaration of the special member,
4834 // since we may not have parsed some necessary in-class initializers yet.
Richard Smith3901dfe2013-03-27 00:22:47 +00004835 if (First) {
4836 // If the exception specification needs to be instantiated, do so now,
4837 // before we clobber it with an EST_Unevaluated specification below.
4838 if (Type->getExceptionSpecType() == EST_Uninstantiated) {
4839 InstantiateExceptionSpec(MD->getLocStart(), MD);
4840 Type = MD->getType()->getAs<FunctionProtoType>();
4841 }
Richard Smithbd305122012-12-11 01:14:52 +00004842 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
Richard Smith3901dfe2013-03-27 00:22:47 +00004843 } else
Richard Smithbd305122012-12-11 01:14:52 +00004844 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
4845 }
Richard Smithcc36f692011-12-22 02:22:31 +00004846
4847 // If a function is explicitly defaulted on its first declaration,
4848 if (First) {
4849 // -- it is implicitly considered to be constexpr if the implicit
4850 // definition would be,
Richard Smithb9e90b12012-05-15 04:39:51 +00004851 MD->setConstexpr(Constexpr);
Richard Smithcc36f692011-12-22 02:22:31 +00004852
Richard Smithb9e90b12012-05-15 04:39:51 +00004853 // -- it is implicitly considered to have the same exception-specification
4854 // as if it had been implicitly declared,
Richard Smithbd305122012-12-11 01:14:52 +00004855 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
4856 EPI.ExceptionSpecType = EST_Unevaluated;
4857 EPI.ExceptionSpecDecl = MD;
Jordan Rose5c382722013-03-08 21:51:21 +00004858 MD->setType(Context.getFunctionType(ReturnType,
4859 ArrayRef<QualType>(&ArgType,
4860 ExpectedParams),
4861 EPI));
Sebastian Redl22653ba2011-08-30 19:58:05 +00004862 }
4863
Richard Smithb9e90b12012-05-15 04:39:51 +00004864 if (ShouldDeleteSpecialMember(MD, CSM)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00004865 if (First) {
Richard Smithb4d2a152013-04-02 19:38:47 +00004866 SetDeclDeleted(MD, MD->getLocation());
Sebastian Redl22653ba2011-08-30 19:58:05 +00004867 } else {
Richard Smithb9e90b12012-05-15 04:39:51 +00004868 // C++11 [dcl.fct.def.default]p4:
4869 // [For a] user-provided explicitly-defaulted function [...] if such a
4870 // function is implicitly defined as deleted, the program is ill-formed.
4871 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
Richard Smith566184a2014-01-22 20:09:10 +00004872 ShouldDeleteSpecialMember(MD, CSM, /*Diagnose*/true);
Richard Smithb9e90b12012-05-15 04:39:51 +00004873 HadError = true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00004874 }
4875 }
Sebastian Redl22653ba2011-08-30 19:58:05 +00004876
Richard Smithb9e90b12012-05-15 04:39:51 +00004877 if (HadError)
4878 MD->setInvalidDecl();
Alexis Huntf91729462011-05-12 22:46:25 +00004879}
4880
Richard Smithbd305122012-12-11 01:14:52 +00004881/// Check whether the exception specification provided for an
4882/// explicitly-defaulted special member matches the exception specification
4883/// that would have been generated for an implicit special member, per
4884/// C++11 [dcl.fct.def.default]p2.
4885void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
4886 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
4887 // Compute the implicit exception specification.
Reid Kleckner78af0702013-08-27 23:08:25 +00004888 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
4889 /*IsCXXMethod=*/true);
4890 FunctionProtoType::ExtProtoInfo EPI(CC);
Richard Smithbd305122012-12-11 01:14:52 +00004891 computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI);
4892 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00004893 Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithbd305122012-12-11 01:14:52 +00004894
4895 // Ensure that it matches.
4896 CheckEquivalentExceptionSpec(
4897 PDiag(diag::err_incorrect_defaulted_exception_spec)
4898 << getSpecialMember(MD), PDiag(),
4899 ImplicitType, SourceLocation(),
4900 SpecifiedType, MD->getLocation());
4901}
4902
Alp Tokerae3a9442013-10-18 05:54:19 +00004903void Sema::CheckDelayedMemberExceptionSpecs() {
4904 SmallVector<std::pair<const CXXDestructorDecl *, const CXXDestructorDecl *>,
4905 2> Checks;
4906 SmallVector<std::pair<CXXMethodDecl *, const FunctionProtoType *>, 2> Specs;
Richard Smithbd305122012-12-11 01:14:52 +00004907
Alp Tokerae3a9442013-10-18 05:54:19 +00004908 std::swap(Checks, DelayedDestructorExceptionSpecChecks);
4909 std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
4910
4911 // Perform any deferred checking of exception specifications for virtual
4912 // destructors.
4913 for (unsigned i = 0, e = Checks.size(); i != e; ++i) {
4914 const CXXDestructorDecl *Dtor = Checks[i].first;
4915 assert(!Dtor->getParent()->isDependentType() &&
4916 "Should not ever add destructors of templates into the list.");
4917 CheckOverridingFunctionExceptionSpec(Dtor, Checks[i].second);
4918 }
4919
4920 // Check that any explicitly-defaulted methods have exception specifications
4921 // compatible with their implicit exception specifications.
4922 for (unsigned I = 0, N = Specs.size(); I != N; ++I)
4923 CheckExplicitlyDefaultedMemberExceptionSpec(Specs[I].first,
4924 Specs[I].second);
Richard Smithbd305122012-12-11 01:14:52 +00004925}
4926
Richard Smithd951a1d2012-02-18 02:02:13 +00004927namespace {
4928struct SpecialMemberDeletionInfo {
4929 Sema &S;
4930 CXXMethodDecl *MD;
4931 Sema::CXXSpecialMember CSM;
Richard Smith852265f2012-03-30 20:53:28 +00004932 bool Diagnose;
Richard Smithd951a1d2012-02-18 02:02:13 +00004933
4934 // Properties of the special member, computed for convenience.
Richard Smith41c35d62013-11-27 03:39:20 +00004935 bool IsConstructor, IsAssignment, IsMove, ConstArg;
Richard Smithd951a1d2012-02-18 02:02:13 +00004936 SourceLocation Loc;
4937
4938 bool AllFieldsAreConst;
4939
4940 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith852265f2012-03-30 20:53:28 +00004941 Sema::CXXSpecialMember CSM, bool Diagnose)
4942 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
Richard Smithd951a1d2012-02-18 02:02:13 +00004943 IsConstructor(false), IsAssignment(false), IsMove(false),
Richard Smith41c35d62013-11-27 03:39:20 +00004944 ConstArg(false), Loc(MD->getLocation()),
Richard Smithd951a1d2012-02-18 02:02:13 +00004945 AllFieldsAreConst(true) {
4946 switch (CSM) {
4947 case Sema::CXXDefaultConstructor:
4948 case Sema::CXXCopyConstructor:
4949 IsConstructor = true;
4950 break;
4951 case Sema::CXXMoveConstructor:
4952 IsConstructor = true;
4953 IsMove = true;
4954 break;
4955 case Sema::CXXCopyAssignment:
4956 IsAssignment = true;
4957 break;
4958 case Sema::CXXMoveAssignment:
4959 IsAssignment = true;
4960 IsMove = true;
4961 break;
4962 case Sema::CXXDestructor:
4963 break;
4964 case Sema::CXXInvalid:
4965 llvm_unreachable("invalid special member kind");
4966 }
4967
4968 if (MD->getNumParams()) {
Richard Smith41c35d62013-11-27 03:39:20 +00004969 if (const ReferenceType *RT =
4970 MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
4971 ConstArg = RT->getPointeeType().isConstQualified();
Richard Smithd951a1d2012-02-18 02:02:13 +00004972 }
4973 }
4974
4975 bool inUnion() const { return MD->getParent()->isUnion(); }
4976
4977 /// Look up the corresponding special member in the given class.
Richard Smithaf136f82012-07-18 03:51:16 +00004978 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
Richard Smith41c35d62013-11-27 03:39:20 +00004979 unsigned Quals, bool IsMutable) {
4980 return lookupCallFromSpecialMember(S, Class, CSM, Quals,
4981 ConstArg && !IsMutable);
Richard Smithd951a1d2012-02-18 02:02:13 +00004982 }
4983
Richard Smith852265f2012-03-30 20:53:28 +00004984 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
Richard Smith921bd202012-02-26 09:11:52 +00004985
Richard Smith852265f2012-03-30 20:53:28 +00004986 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smithd951a1d2012-02-18 02:02:13 +00004987 bool shouldDeleteForField(FieldDecl *FD);
4988 bool shouldDeleteForAllConstMembers();
Richard Smith852265f2012-03-30 20:53:28 +00004989
Richard Smithaf136f82012-07-18 03:51:16 +00004990 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
4991 unsigned Quals);
Richard Smith852265f2012-03-30 20:53:28 +00004992 bool shouldDeleteForSubobjectCall(Subobject Subobj,
4993 Sema::SpecialMemberOverloadResult *SMOR,
4994 bool IsDtorCallInCtor);
John McCalld4274212012-04-09 20:53:23 +00004995
4996 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smithd951a1d2012-02-18 02:02:13 +00004997};
4998}
4999
John McCalld4274212012-04-09 20:53:23 +00005000/// Is the given special member inaccessible when used on the given
5001/// sub-object.
5002bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
5003 CXXMethodDecl *target) {
5004 /// If we're operating on a base class, the object type is the
5005 /// type of this special member.
5006 QualType objectTy;
Dmitri Gribenko76bb5cabfa2012-09-10 21:20:09 +00005007 AccessSpecifier access = target->getAccess();
John McCalld4274212012-04-09 20:53:23 +00005008 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
5009 objectTy = S.Context.getTypeDeclType(MD->getParent());
5010 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
5011
5012 // If we're operating on a field, the object type is the type of the field.
5013 } else {
5014 objectTy = S.Context.getTypeDeclType(target->getParent());
5015 }
5016
5017 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
5018}
5019
Richard Smith852265f2012-03-30 20:53:28 +00005020/// Check whether we should delete a special member due to the implicit
5021/// definition containing a call to a special member of a subobject.
5022bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
5023 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
5024 bool IsDtorCallInCtor) {
5025 CXXMethodDecl *Decl = SMOR->getMethod();
5026 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
5027
5028 int DiagKind = -1;
5029
5030 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
5031 DiagKind = !Decl ? 0 : 1;
5032 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5033 DiagKind = 2;
John McCalld4274212012-04-09 20:53:23 +00005034 else if (!isAccessible(Subobj, Decl))
Richard Smith852265f2012-03-30 20:53:28 +00005035 DiagKind = 3;
5036 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
5037 !Decl->isTrivial()) {
5038 // A member of a union must have a trivial corresponding special member.
5039 // As a weird special case, a destructor call from a union's constructor
5040 // must be accessible and non-deleted, but need not be trivial. Such a
5041 // destructor is never actually called, but is semantically checked as
5042 // if it were.
5043 DiagKind = 4;
5044 }
5045
5046 if (DiagKind == -1)
5047 return false;
5048
5049 if (Diagnose) {
5050 if (Field) {
5051 S.Diag(Field->getLocation(),
5052 diag::note_deleted_special_member_class_subobject)
5053 << CSM << MD->getParent() << /*IsField*/true
5054 << Field << DiagKind << IsDtorCallInCtor;
5055 } else {
5056 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
5057 S.Diag(Base->getLocStart(),
5058 diag::note_deleted_special_member_class_subobject)
5059 << CSM << MD->getParent() << /*IsField*/false
5060 << Base->getType() << DiagKind << IsDtorCallInCtor;
5061 }
5062
5063 if (DiagKind == 1)
5064 S.NoteDeletedFunction(Decl);
5065 // FIXME: Explain inaccessibility if DiagKind == 3.
5066 }
5067
5068 return true;
5069}
5070
Richard Smith921bd202012-02-26 09:11:52 +00005071/// Check whether we should delete a special member function due to having a
Richard Smithaf136f82012-07-18 03:51:16 +00005072/// direct or virtual base class or non-static data member of class type M.
Richard Smith921bd202012-02-26 09:11:52 +00005073bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smithaf136f82012-07-18 03:51:16 +00005074 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
Richard Smith852265f2012-03-30 20:53:28 +00005075 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Richard Smith41c35d62013-11-27 03:39:20 +00005076 bool IsMutable = Field && Field->isMutable();
Richard Smithd951a1d2012-02-18 02:02:13 +00005077
5078 // C++11 [class.ctor]p5:
Richard Smith5704fe82012-03-29 19:00:10 +00005079 // -- any direct or virtual base class, or non-static data member with no
5080 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smithd951a1d2012-02-18 02:02:13 +00005081 // either M has no default constructor or overload resolution as applied
5082 // to M's default constructor results in an ambiguity or in a function
5083 // that is deleted or inaccessible
5084 // C++11 [class.copy]p11, C++11 [class.copy]p23:
5085 // -- a direct or virtual base class B that cannot be copied/moved because
5086 // overload resolution, as applied to B's corresponding special member,
5087 // results in an ambiguity or a function that is deleted or inaccessible
5088 // from the defaulted special member
Richard Smith852265f2012-03-30 20:53:28 +00005089 // C++11 [class.dtor]p5:
5090 // -- any direct or virtual base class [...] has a type with a destructor
5091 // that is deleted or inaccessible
5092 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005093 Field && Field->hasInClassInitializer()) &&
Richard Smith41c35d62013-11-27 03:39:20 +00005094 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
5095 false))
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005096 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00005097
Richard Smith852265f2012-03-30 20:53:28 +00005098 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
5099 // -- any direct or virtual base class or non-static data member has a
5100 // type with a destructor that is deleted or inaccessible
5101 if (IsConstructor) {
5102 Sema::SpecialMemberOverloadResult *SMOR =
5103 S.LookupSpecialMember(Class, Sema::CXXDestructor,
5104 false, false, false, false, false);
5105 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
5106 return true;
5107 }
5108
Richard Smith921bd202012-02-26 09:11:52 +00005109 return false;
5110}
5111
5112/// Check whether we should delete a special member function due to the class
5113/// having a particular direct or virtual base class.
Richard Smith852265f2012-03-30 20:53:28 +00005114bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005115 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
Richard Smithaf136f82012-07-18 03:51:16 +00005116 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
Richard Smithd951a1d2012-02-18 02:02:13 +00005117}
5118
5119/// Check whether we should delete a special member function due to the class
5120/// having a particular non-static data member.
5121bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
5122 QualType FieldType = S.Context.getBaseElementType(FD->getType());
5123 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
5124
5125 if (CSM == Sema::CXXDefaultConstructor) {
5126 // For a default constructor, all references must be initialized in-class
5127 // and, if a union, it must have a non-const member.
Richard Smith852265f2012-03-30 20:53:28 +00005128 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
5129 if (Diagnose)
5130 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
5131 << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smithd951a1d2012-02-18 02:02:13 +00005132 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005133 }
Richard Smith619ecdc2012-02-27 06:07:25 +00005134 // C++11 [class.ctor]p5: any non-variant non-static data member of
5135 // const-qualified type (or array thereof) with no
5136 // brace-or-equal-initializer does not have a user-provided default
5137 // constructor.
5138 if (!inUnion() && FieldType.isConstQualified() &&
5139 !FD->hasInClassInitializer() &&
Richard Smith852265f2012-03-30 20:53:28 +00005140 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
5141 if (Diagnose)
5142 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smithc5f98f32012-04-29 06:32:34 +00005143 << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith619ecdc2012-02-27 06:07:25 +00005144 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005145 }
5146
5147 if (inUnion() && !FieldType.isConstQualified())
5148 AllFieldsAreConst = false;
Richard Smithd951a1d2012-02-18 02:02:13 +00005149 } else if (CSM == Sema::CXXCopyConstructor) {
5150 // For a copy constructor, data members must not be of rvalue reference
5151 // type.
Richard Smith852265f2012-03-30 20:53:28 +00005152 if (FieldType->isRValueReferenceType()) {
5153 if (Diagnose)
5154 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
5155 << MD->getParent() << FD << FieldType;
Richard Smithd951a1d2012-02-18 02:02:13 +00005156 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005157 }
Richard Smithd951a1d2012-02-18 02:02:13 +00005158 } else if (IsAssignment) {
5159 // For an assignment operator, data members must not be of reference type.
Richard Smith852265f2012-03-30 20:53:28 +00005160 if (FieldType->isReferenceType()) {
5161 if (Diagnose)
5162 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
5163 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smithd951a1d2012-02-18 02:02:13 +00005164 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005165 }
5166 if (!FieldRecord && FieldType.isConstQualified()) {
5167 // C++11 [class.copy]p23:
5168 // -- a non-static data member of const non-class type (or array thereof)
5169 if (Diagnose)
5170 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smithc5f98f32012-04-29 06:32:34 +00005171 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith852265f2012-03-30 20:53:28 +00005172 return true;
5173 }
Richard Smithd951a1d2012-02-18 02:02:13 +00005174 }
5175
5176 if (FieldRecord) {
Richard Smithd951a1d2012-02-18 02:02:13 +00005177 // Some additional restrictions exist on the variant members.
5178 if (!inUnion() && FieldRecord->isUnion() &&
5179 FieldRecord->isAnonymousStructOrUnion()) {
5180 bool AllVariantFieldsAreConst = true;
5181
Richard Smith5704fe82012-03-29 19:00:10 +00005182 // FIXME: Handle anonymous unions declared within anonymous unions.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005183 for (auto *UI : FieldRecord->fields()) {
Richard Smithd951a1d2012-02-18 02:02:13 +00005184 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smithd951a1d2012-02-18 02:02:13 +00005185
5186 if (!UnionFieldType.isConstQualified())
5187 AllVariantFieldsAreConst = false;
5188
Richard Smith921bd202012-02-26 09:11:52 +00005189 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
5190 if (UnionFieldRecord &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005191 shouldDeleteForClassSubobject(UnionFieldRecord, UI,
Richard Smithaf136f82012-07-18 03:51:16 +00005192 UnionFieldType.getCVRQualifiers()))
Richard Smith921bd202012-02-26 09:11:52 +00005193 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00005194 }
5195
5196 // At least one member in each anonymous union must be non-const
Douglas Gregor232ee492012-02-24 21:25:53 +00005197 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005198 !FieldRecord->field_empty()) {
Richard Smith852265f2012-03-30 20:53:28 +00005199 if (Diagnose)
5200 S.Diag(FieldRecord->getLocation(),
5201 diag::note_deleted_default_ctor_all_const)
5202 << MD->getParent() << /*anonymous union*/1;
Richard Smithd951a1d2012-02-18 02:02:13 +00005203 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005204 }
Richard Smithd951a1d2012-02-18 02:02:13 +00005205
Richard Smith5704fe82012-03-29 19:00:10 +00005206 // Don't check the implicit member of the anonymous union type.
Richard Smithd951a1d2012-02-18 02:02:13 +00005207 // This is technically non-conformant, but sanity demands it.
5208 return false;
5209 }
5210
Richard Smithaf136f82012-07-18 03:51:16 +00005211 if (shouldDeleteForClassSubobject(FieldRecord, FD,
5212 FieldType.getCVRQualifiers()))
Richard Smith5704fe82012-03-29 19:00:10 +00005213 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00005214 }
5215
5216 return false;
5217}
5218
5219/// C++11 [class.ctor] p5:
5220/// A defaulted default constructor for a class X is defined as deleted if
5221/// X is a union and all of its variant members are of const-qualified type.
5222bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor232ee492012-02-24 21:25:53 +00005223 // This is a silly definition, because it gives an empty union a deleted
5224 // default constructor. Don't do that.
Richard Smith852265f2012-03-30 20:53:28 +00005225 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005226 !MD->getParent()->field_empty()) {
Richard Smith852265f2012-03-30 20:53:28 +00005227 if (Diagnose)
5228 S.Diag(MD->getParent()->getLocation(),
5229 diag::note_deleted_default_ctor_all_const)
5230 << MD->getParent() << /*not anonymous union*/0;
5231 return true;
5232 }
5233 return false;
Richard Smithd951a1d2012-02-18 02:02:13 +00005234}
5235
5236/// Determine whether a defaulted special member function should be defined as
5237/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
5238/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith852265f2012-03-30 20:53:28 +00005239bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
5240 bool Diagnose) {
Richard Smithf716bb82012-08-06 02:25:10 +00005241 if (MD->isInvalidDecl())
5242 return false;
Alexis Huntd6da8762011-10-10 06:18:57 +00005243 CXXRecordDecl *RD = MD->getParent();
Alexis Huntea6f0322011-05-11 22:34:38 +00005244 assert(!RD->isDependentType() && "do deletion after instantiation");
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005245 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
Alexis Huntea6f0322011-05-11 22:34:38 +00005246 return false;
5247
Richard Smithd951a1d2012-02-18 02:02:13 +00005248 // C++11 [expr.lambda.prim]p19:
5249 // The closure type associated with a lambda-expression has a
5250 // deleted (8.4.3) default constructor and a deleted copy
5251 // assignment operator.
5252 if (RD->isLambda() &&
Richard Smith852265f2012-03-30 20:53:28 +00005253 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
5254 if (Diagnose)
5255 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smithd951a1d2012-02-18 02:02:13 +00005256 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005257 }
5258
Richard Smith6f1e2c62012-04-02 20:59:25 +00005259 // For an anonymous struct or union, the copy and assignment special members
5260 // will never be used, so skip the check. For an anonymous union declared at
5261 // namespace scope, the constructor and destructor are used.
5262 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
5263 RD->isAnonymousStructOrUnion())
5264 return false;
5265
Richard Smith852265f2012-03-30 20:53:28 +00005266 // C++11 [class.copy]p7, p18:
5267 // If the class definition declares a move constructor or move assignment
5268 // operator, an implicitly declared copy constructor or copy assignment
5269 // operator is defined as deleted.
5270 if (MD->isImplicit() &&
5271 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
5272 CXXMethodDecl *UserDeclaredMove = 0;
5273
5274 // In Microsoft mode, a user-declared move only causes the deletion of the
5275 // corresponding copy operation, not both copy operations.
5276 if (RD->hasUserDeclaredMoveConstructor() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00005277 (!getLangOpts().MSVCCompat || CSM == CXXCopyConstructor)) {
Richard Smith852265f2012-03-30 20:53:28 +00005278 if (!Diagnose) return true;
Richard Smith1a2532b2012-12-08 04:10:18 +00005279
5280 // Find any user-declared move constructor.
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005281 for (auto *I : RD->ctors()) {
Richard Smith1a2532b2012-12-08 04:10:18 +00005282 if (I->isMoveConstructor()) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005283 UserDeclaredMove = I;
Richard Smith1a2532b2012-12-08 04:10:18 +00005284 break;
5285 }
5286 }
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005287 assert(UserDeclaredMove);
Richard Smith852265f2012-03-30 20:53:28 +00005288 } else if (RD->hasUserDeclaredMoveAssignment() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00005289 (!getLangOpts().MSVCCompat || CSM == CXXCopyAssignment)) {
Richard Smith852265f2012-03-30 20:53:28 +00005290 if (!Diagnose) return true;
Richard Smith1a2532b2012-12-08 04:10:18 +00005291
5292 // Find any user-declared move assignment operator.
Aaron Ballman2b124d12014-03-13 16:36:16 +00005293 for (auto *I : RD->methods()) {
Richard Smith1a2532b2012-12-08 04:10:18 +00005294 if (I->isMoveAssignmentOperator()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00005295 UserDeclaredMove = I;
Richard Smith1a2532b2012-12-08 04:10:18 +00005296 break;
5297 }
5298 }
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005299 assert(UserDeclaredMove);
Richard Smith852265f2012-03-30 20:53:28 +00005300 }
5301
5302 if (UserDeclaredMove) {
5303 Diag(UserDeclaredMove->getLocation(),
5304 diag::note_deleted_copy_user_declared_move)
Richard Smithf989e512012-04-02 21:07:48 +00005305 << (CSM == CXXCopyAssignment) << RD
Richard Smith852265f2012-03-30 20:53:28 +00005306 << UserDeclaredMove->isMoveAssignmentOperator();
5307 return true;
5308 }
5309 }
Alexis Huntd6da8762011-10-10 06:18:57 +00005310
Richard Smith6f1e2c62012-04-02 20:59:25 +00005311 // Do access control from the special member function
5312 ContextRAII MethodContext(*this, MD);
5313
Richard Smith921bd202012-02-26 09:11:52 +00005314 // C++11 [class.dtor]p5:
5315 // -- for a virtual destructor, lookup of the non-array deallocation function
5316 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith852265f2012-03-30 20:53:28 +00005317 if (CSM == CXXDestructor && MD->isVirtual()) {
Richard Smith921bd202012-02-26 09:11:52 +00005318 FunctionDecl *OperatorDelete = 0;
5319 DeclarationName Name =
5320 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5321 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smith852265f2012-03-30 20:53:28 +00005322 OperatorDelete, false)) {
5323 if (Diagnose)
5324 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith921bd202012-02-26 09:11:52 +00005325 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005326 }
Richard Smith921bd202012-02-26 09:11:52 +00005327 }
5328
Richard Smith852265f2012-03-30 20:53:28 +00005329 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
Alexis Huntea6f0322011-05-11 22:34:38 +00005330
Aaron Ballman574705e2014-03-13 15:41:46 +00005331 for (auto &BI : RD->bases())
5332 if (!BI.isVirtual() &&
5333 SMI.shouldDeleteForBase(&BI))
Richard Smithd951a1d2012-02-18 02:02:13 +00005334 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00005335
Richard Smithd1627032013-07-22 18:06:23 +00005336 // Per DR1611, do not consider virtual bases of constructors of abstract
5337 // classes, since we are not going to construct them.
Richard Smithbc46e432013-07-22 02:56:56 +00005338 if (!RD->isAbstract() || !SMI.IsConstructor) {
Aaron Ballman445a9392014-03-13 16:15:17 +00005339 for (auto &BI : RD->vbases())
5340 if (SMI.shouldDeleteForBase(&BI))
Richard Smithbc46e432013-07-22 02:56:56 +00005341 return true;
5342 }
Alexis Huntea6f0322011-05-11 22:34:38 +00005343
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005344 for (auto *FI : RD->fields())
Richard Smithd951a1d2012-02-18 02:02:13 +00005345 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005346 SMI.shouldDeleteForField(FI))
Alexis Hunta671bca2011-05-20 21:43:47 +00005347 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00005348
Richard Smithd951a1d2012-02-18 02:02:13 +00005349 if (SMI.shouldDeleteForAllConstMembers())
Alexis Huntea6f0322011-05-11 22:34:38 +00005350 return true;
5351
5352 return false;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005353}
5354
Richard Smith92f241f2012-12-08 02:53:02 +00005355/// Perform lookup for a special member of the specified kind, and determine
5356/// whether it is trivial. If the triviality can be determined without the
5357/// lookup, skip it. This is intended for use when determining whether a
5358/// special member of a containing object is trivial, and thus does not ever
5359/// perform overload resolution for default constructors.
5360///
5361/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
5362/// member that was most likely to be intended to be trivial, if any.
5363static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
5364 Sema::CXXSpecialMember CSM, unsigned Quals,
Richard Smith41c35d62013-11-27 03:39:20 +00005365 bool ConstRHS, CXXMethodDecl **Selected) {
Richard Smith92f241f2012-12-08 02:53:02 +00005366 if (Selected)
5367 *Selected = 0;
5368
5369 switch (CSM) {
5370 case Sema::CXXInvalid:
5371 llvm_unreachable("not a special member");
5372
5373 case Sema::CXXDefaultConstructor:
5374 // C++11 [class.ctor]p5:
5375 // A default constructor is trivial if:
5376 // - all the [direct subobjects] have trivial default constructors
5377 //
5378 // Note, no overload resolution is performed in this case.
5379 if (RD->hasTrivialDefaultConstructor())
5380 return true;
5381
5382 if (Selected) {
5383 // If there's a default constructor which could have been trivial, dig it
5384 // out. Otherwise, if there's any user-provided default constructor, point
5385 // to that as an example of why there's not a trivial one.
5386 CXXConstructorDecl *DefCtor = 0;
5387 if (RD->needsImplicitDefaultConstructor())
5388 S.DeclareImplicitDefaultConstructor(RD);
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005389 for (auto *CI : RD->ctors()) {
Richard Smith92f241f2012-12-08 02:53:02 +00005390 if (!CI->isDefaultConstructor())
5391 continue;
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005392 DefCtor = CI;
Richard Smith92f241f2012-12-08 02:53:02 +00005393 if (!DefCtor->isUserProvided())
5394 break;
5395 }
5396
5397 *Selected = DefCtor;
5398 }
5399
5400 return false;
5401
5402 case Sema::CXXDestructor:
5403 // C++11 [class.dtor]p5:
5404 // A destructor is trivial if:
5405 // - all the direct [subobjects] have trivial destructors
5406 if (RD->hasTrivialDestructor())
5407 return true;
5408
5409 if (Selected) {
5410 if (RD->needsImplicitDestructor())
5411 S.DeclareImplicitDestructor(RD);
5412 *Selected = RD->getDestructor();
5413 }
5414
5415 return false;
5416
5417 case Sema::CXXCopyConstructor:
5418 // C++11 [class.copy]p12:
5419 // A copy constructor is trivial if:
5420 // - the constructor selected to copy each direct [subobject] is trivial
5421 if (RD->hasTrivialCopyConstructor()) {
5422 if (Quals == Qualifiers::Const)
5423 // We must either select the trivial copy constructor or reach an
5424 // ambiguity; no need to actually perform overload resolution.
5425 return true;
5426 } else if (!Selected) {
5427 return false;
5428 }
5429 // In C++98, we are not supposed to perform overload resolution here, but we
5430 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
5431 // cases like B as having a non-trivial copy constructor:
5432 // struct A { template<typename T> A(T&); };
5433 // struct B { mutable A a; };
5434 goto NeedOverloadResolution;
5435
5436 case Sema::CXXCopyAssignment:
5437 // C++11 [class.copy]p25:
5438 // A copy assignment operator is trivial if:
5439 // - the assignment operator selected to copy each direct [subobject] is
5440 // trivial
5441 if (RD->hasTrivialCopyAssignment()) {
5442 if (Quals == Qualifiers::Const)
5443 return true;
5444 } else if (!Selected) {
5445 return false;
5446 }
5447 // In C++98, we are not supposed to perform overload resolution here, but we
5448 // treat that as a language defect.
5449 goto NeedOverloadResolution;
5450
5451 case Sema::CXXMoveConstructor:
5452 case Sema::CXXMoveAssignment:
5453 NeedOverloadResolution:
5454 Sema::SpecialMemberOverloadResult *SMOR =
Richard Smith41c35d62013-11-27 03:39:20 +00005455 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
Richard Smith92f241f2012-12-08 02:53:02 +00005456
5457 // The standard doesn't describe how to behave if the lookup is ambiguous.
5458 // We treat it as not making the member non-trivial, just like the standard
5459 // mandates for the default constructor. This should rarely matter, because
5460 // the member will also be deleted.
5461 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5462 return true;
5463
5464 if (!SMOR->getMethod()) {
5465 assert(SMOR->getKind() ==
5466 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5467 return false;
5468 }
5469
5470 // We deliberately don't check if we found a deleted special member. We're
5471 // not supposed to!
5472 if (Selected)
5473 *Selected = SMOR->getMethod();
5474 return SMOR->getMethod()->isTrivial();
5475 }
5476
5477 llvm_unreachable("unknown special method kind");
5478}
5479
Benjamin Kramer3e350262013-02-15 12:30:38 +00005480static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005481 for (auto *CI : RD->ctors())
Richard Smith92f241f2012-12-08 02:53:02 +00005482 if (!CI->isImplicit())
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005483 return CI;
Richard Smith92f241f2012-12-08 02:53:02 +00005484
5485 // Look for constructor templates.
5486 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
5487 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
5488 if (CXXConstructorDecl *CD =
5489 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
5490 return CD;
5491 }
5492
5493 return 0;
5494}
5495
5496/// The kind of subobject we are checking for triviality. The values of this
5497/// enumeration are used in diagnostics.
5498enum TrivialSubobjectKind {
5499 /// The subobject is a base class.
5500 TSK_BaseClass,
5501 /// The subobject is a non-static data member.
5502 TSK_Field,
5503 /// The object is actually the complete object.
5504 TSK_CompleteObject
5505};
5506
5507/// Check whether the special member selected for a given type would be trivial.
5508static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
Richard Smith41c35d62013-11-27 03:39:20 +00005509 QualType SubType, bool ConstRHS,
Richard Smith92f241f2012-12-08 02:53:02 +00005510 Sema::CXXSpecialMember CSM,
5511 TrivialSubobjectKind Kind,
5512 bool Diagnose) {
5513 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
5514 if (!SubRD)
5515 return true;
5516
5517 CXXMethodDecl *Selected;
5518 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
Richard Smith41c35d62013-11-27 03:39:20 +00005519 ConstRHS, Diagnose ? &Selected : 0))
Richard Smith92f241f2012-12-08 02:53:02 +00005520 return true;
5521
5522 if (Diagnose) {
Richard Smith41c35d62013-11-27 03:39:20 +00005523 if (ConstRHS)
5524 SubType.addConst();
5525
Richard Smith92f241f2012-12-08 02:53:02 +00005526 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
5527 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
5528 << Kind << SubType.getUnqualifiedType();
5529 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
5530 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
5531 } else if (!Selected)
5532 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
5533 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
5534 else if (Selected->isUserProvided()) {
5535 if (Kind == TSK_CompleteObject)
5536 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
5537 << Kind << SubType.getUnqualifiedType() << CSM;
5538 else {
5539 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
5540 << Kind << SubType.getUnqualifiedType() << CSM;
5541 S.Diag(Selected->getLocation(), diag::note_declared_at);
5542 }
5543 } else {
5544 if (Kind != TSK_CompleteObject)
5545 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
5546 << Kind << SubType.getUnqualifiedType() << CSM;
5547
5548 // Explain why the defaulted or deleted special member isn't trivial.
5549 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
5550 }
5551 }
5552
5553 return false;
5554}
5555
5556/// Check whether the members of a class type allow a special member to be
5557/// trivial.
5558static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
5559 Sema::CXXSpecialMember CSM,
5560 bool ConstArg, bool Diagnose) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005561 for (const auto *FI : RD->fields()) {
Richard Smith92f241f2012-12-08 02:53:02 +00005562 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
5563 continue;
5564
5565 QualType FieldType = S.Context.getBaseElementType(FI->getType());
5566
5567 // Pretend anonymous struct or union members are members of this class.
5568 if (FI->isAnonymousStructOrUnion()) {
5569 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
5570 CSM, ConstArg, Diagnose))
5571 return false;
5572 continue;
5573 }
5574
5575 // C++11 [class.ctor]p5:
5576 // A default constructor is trivial if [...]
5577 // -- no non-static data member of its class has a
5578 // brace-or-equal-initializer
5579 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
5580 if (Diagnose)
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005581 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
Richard Smith92f241f2012-12-08 02:53:02 +00005582 return false;
5583 }
5584
5585 // Objective C ARC 4.3.5:
5586 // [...] nontrivally ownership-qualified types are [...] not trivially
5587 // default constructible, copy constructible, move constructible, copy
5588 // assignable, move assignable, or destructible [...]
5589 if (S.getLangOpts().ObjCAutoRefCount &&
5590 FieldType.hasNonTrivialObjCLifetime()) {
5591 if (Diagnose)
5592 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
5593 << RD << FieldType.getObjCLifetime();
5594 return false;
5595 }
5596
Richard Smith41c35d62013-11-27 03:39:20 +00005597 bool ConstRHS = ConstArg && !FI->isMutable();
5598 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
5599 CSM, TSK_Field, Diagnose))
Richard Smith92f241f2012-12-08 02:53:02 +00005600 return false;
5601 }
5602
5603 return true;
5604}
5605
5606/// Diagnose why the specified class does not have a trivial special member of
5607/// the given kind.
5608void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
5609 QualType Ty = Context.getRecordType(RD);
Richard Smith92f241f2012-12-08 02:53:02 +00005610
Richard Smith41c35d62013-11-27 03:39:20 +00005611 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
5612 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
Richard Smith92f241f2012-12-08 02:53:02 +00005613 TSK_CompleteObject, /*Diagnose*/true);
5614}
5615
5616/// Determine whether a defaulted or deleted special member function is trivial,
5617/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
5618/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
5619bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
5620 bool Diagnose) {
Richard Smith92f241f2012-12-08 02:53:02 +00005621 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
5622
5623 CXXRecordDecl *RD = MD->getParent();
5624
5625 bool ConstArg = false;
Richard Smith92f241f2012-12-08 02:53:02 +00005626
Richard Smith2002bfe2013-11-04 02:02:27 +00005627 // C++11 [class.copy]p12, p25: [DR1593]
5628 // A [special member] is trivial if [...] its parameter-type-list is
5629 // equivalent to the parameter-type-list of an implicit declaration [...]
Richard Smith92f241f2012-12-08 02:53:02 +00005630 switch (CSM) {
5631 case CXXDefaultConstructor:
5632 case CXXDestructor:
5633 // Trivial default constructors and destructors cannot have parameters.
5634 break;
5635
5636 case CXXCopyConstructor:
5637 case CXXCopyAssignment: {
5638 // Trivial copy operations always have const, non-volatile parameter types.
5639 ConstArg = true;
Jordan Rosed03d99d2013-03-05 01:27:54 +00005640 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smith92f241f2012-12-08 02:53:02 +00005641 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
5642 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
5643 if (Diagnose)
5644 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5645 << Param0->getSourceRange() << Param0->getType()
5646 << Context.getLValueReferenceType(
5647 Context.getRecordType(RD).withConst());
5648 return false;
5649 }
5650 break;
5651 }
5652
5653 case CXXMoveConstructor:
5654 case CXXMoveAssignment: {
5655 // Trivial move operations always have non-cv-qualified parameters.
Jordan Rosed03d99d2013-03-05 01:27:54 +00005656 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smith92f241f2012-12-08 02:53:02 +00005657 const RValueReferenceType *RT =
5658 Param0->getType()->getAs<RValueReferenceType>();
5659 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
5660 if (Diagnose)
5661 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5662 << Param0->getSourceRange() << Param0->getType()
5663 << Context.getRValueReferenceType(Context.getRecordType(RD));
5664 return false;
5665 }
5666 break;
5667 }
5668
5669 case CXXInvalid:
5670 llvm_unreachable("not a special member");
5671 }
5672
Richard Smith92f241f2012-12-08 02:53:02 +00005673 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
5674 if (Diagnose)
5675 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
5676 diag::note_nontrivial_default_arg)
5677 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
5678 return false;
5679 }
5680 if (MD->isVariadic()) {
5681 if (Diagnose)
5682 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
5683 return false;
5684 }
5685
5686 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5687 // A copy/move [constructor or assignment operator] is trivial if
5688 // -- the [member] selected to copy/move each direct base class subobject
5689 // is trivial
5690 //
5691 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5692 // A [default constructor or destructor] is trivial if
5693 // -- all the direct base classes have trivial [default constructors or
5694 // destructors]
Aaron Ballman574705e2014-03-13 15:41:46 +00005695 for (const auto &BI : RD->bases())
5696 if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(),
Richard Smith41c35d62013-11-27 03:39:20 +00005697 ConstArg, CSM, TSK_BaseClass, Diagnose))
Richard Smith92f241f2012-12-08 02:53:02 +00005698 return false;
5699
5700 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5701 // A copy/move [constructor or assignment operator] for a class X is
5702 // trivial if
5703 // -- for each non-static data member of X that is of class type (or array
5704 // thereof), the constructor selected to copy/move that member is
5705 // trivial
5706 //
5707 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5708 // A [default constructor or destructor] is trivial if
5709 // -- for all of the non-static data members of its class that are of class
5710 // type (or array thereof), each such class has a trivial [default
5711 // constructor or destructor]
5712 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
5713 return false;
5714
5715 // C++11 [class.dtor]p5:
5716 // A destructor is trivial if [...]
5717 // -- the destructor is not virtual
5718 if (CSM == CXXDestructor && MD->isVirtual()) {
5719 if (Diagnose)
5720 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
5721 return false;
5722 }
5723
5724 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
5725 // A [special member] for class X is trivial if [...]
5726 // -- class X has no virtual functions and no virtual base classes
5727 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
5728 if (!Diagnose)
5729 return false;
5730
5731 if (RD->getNumVBases()) {
5732 // Check for virtual bases. We already know that the corresponding
5733 // member in all bases is trivial, so vbases must all be direct.
5734 CXXBaseSpecifier &BS = *RD->vbases_begin();
5735 assert(BS.isVirtual());
5736 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
5737 return false;
5738 }
5739
5740 // Must have a virtual method.
Aaron Ballman2b124d12014-03-13 16:36:16 +00005741 for (const auto *MI : RD->methods()) {
Richard Smith92f241f2012-12-08 02:53:02 +00005742 if (MI->isVirtual()) {
5743 SourceLocation MLoc = MI->getLocStart();
5744 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
5745 return false;
5746 }
5747 }
5748
5749 llvm_unreachable("dynamic class with no vbases and no virtual functions");
5750 }
5751
5752 // Looks like it's trivial!
5753 return true;
5754}
5755
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005756/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramer024e6192011-03-04 13:12:48 +00005757namespace {
5758 struct FindHiddenVirtualMethodData {
5759 Sema *S;
5760 CXXMethodDecl *Method;
5761 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005762 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramer024e6192011-03-04 13:12:48 +00005763 };
5764}
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005765
David Blaikie282c92a2012-10-19 00:53:08 +00005766/// \brief Check whether any most overriden method from MD in Methods
5767static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
5768 const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5769 if (MD->size_overridden_methods() == 0)
5770 return Methods.count(MD->getCanonicalDecl());
5771 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5772 E = MD->end_overridden_methods();
5773 I != E; ++I)
5774 if (CheckMostOverridenMethods(*I, Methods))
5775 return true;
5776 return false;
5777}
5778
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005779/// \brief Member lookup function that determines whether a given C++
5780/// method overloads virtual methods in a base class without overriding any,
5781/// to be used with CXXRecordDecl::lookupInBases().
5782static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
5783 CXXBasePath &Path,
5784 void *UserData) {
5785 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5786
5787 FindHiddenVirtualMethodData &Data
5788 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
5789
5790 DeclarationName Name = Data.Method->getDeclName();
5791 assert(Name.getNameKind() == DeclarationName::Identifier);
5792
5793 bool foundSameNameMethod = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005794 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005795 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikieff7d47a2012-12-19 00:45:41 +00005796 !Path.Decls.empty();
5797 Path.Decls = Path.Decls.slice(1)) {
5798 NamedDecl *D = Path.Decls.front();
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005799 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00005800 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005801 foundSameNameMethod = true;
5802 // Interested only in hidden virtual methods.
5803 if (!MD->isVirtual())
5804 continue;
5805 // If the method we are checking overrides a method from its base
5806 // don't warn about the other overloaded methods.
5807 if (!Data.S->IsOverload(Data.Method, MD, false))
5808 return true;
5809 // Collect the overload only if its hidden.
David Blaikie282c92a2012-10-19 00:53:08 +00005810 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005811 overloadedMethods.push_back(MD);
5812 }
5813 }
5814
5815 if (foundSameNameMethod)
5816 Data.OverloadedMethods.append(overloadedMethods.begin(),
5817 overloadedMethods.end());
5818 return foundSameNameMethod;
5819}
5820
David Blaikie282c92a2012-10-19 00:53:08 +00005821/// \brief Add the most overriden methods from MD to Methods
5822static void AddMostOverridenMethods(const CXXMethodDecl *MD,
5823 llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5824 if (MD->size_overridden_methods() == 0)
5825 Methods.insert(MD->getCanonicalDecl());
5826 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5827 E = MD->end_overridden_methods();
5828 I != E; ++I)
5829 AddMostOverridenMethods(*I, Methods);
5830}
5831
Eli Friedmanaf65120b2013-09-05 23:51:03 +00005832/// \brief Check if a method overloads virtual methods in a base class without
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005833/// overriding any.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00005834void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
5835 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
Benjamin Kramer1458c1c2012-05-19 16:03:58 +00005836 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005837 return;
5838
5839 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
5840 /*bool RecordPaths=*/false,
5841 /*bool DetectVirtual=*/false);
5842 FindHiddenVirtualMethodData Data;
5843 Data.Method = MD;
5844 Data.S = this;
5845
5846 // Keep the base methods that were overriden or introduced in the subclass
5847 // by 'using' in a set. A base method not in this set is hidden.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00005848 CXXRecordDecl *DC = MD->getParent();
David Blaikieff7d47a2012-12-19 00:45:41 +00005849 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
5850 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
5851 NamedDecl *ND = *I;
5852 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
David Blaikie282c92a2012-10-19 00:53:08 +00005853 ND = shad->getTargetDecl();
5854 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5855 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005856 }
5857
Eli Friedmanaf65120b2013-09-05 23:51:03 +00005858 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths))
5859 OverloadedMethods = Data.OverloadedMethods;
5860}
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005861
Eli Friedmanaf65120b2013-09-05 23:51:03 +00005862void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
5863 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
5864 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
5865 CXXMethodDecl *overloadedMD = OverloadedMethods[i];
5866 PartialDiagnostic PD = PDiag(
5867 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
5868 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
5869 Diag(overloadedMD->getLocation(), PD);
5870 }
5871}
5872
5873/// \brief Diagnose methods which overload virtual methods in a base class
5874/// without overriding any.
5875void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
5876 if (MD->isInvalidDecl())
5877 return;
5878
5879 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
5880 MD->getLocation()) == DiagnosticsEngine::Ignored)
5881 return;
5882
5883 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
5884 FindHiddenVirtualMethods(MD, OverloadedMethods);
5885 if (!OverloadedMethods.empty()) {
5886 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
5887 << MD << (OverloadedMethods.size() > 1);
5888
5889 NoteHiddenVirtualMethods(MD, OverloadedMethods);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005890 }
Douglas Gregorc99f1552009-12-03 18:33:45 +00005891}
5892
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00005893void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCall48871652010-08-21 09:40:31 +00005894 Decl *TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00005895 SourceLocation LBrac,
Douglas Gregorc48a10d2010-03-29 14:42:08 +00005896 SourceLocation RBrac,
5897 AttributeList *AttrList) {
Douglas Gregor71a57182009-06-22 23:20:33 +00005898 if (!TagDecl)
5899 return;
Mike Stump11289f42009-09-09 15:08:12 +00005900
Douglas Gregorc9f9b862009-05-11 19:58:34 +00005901 AdjustDeclIfTemplate(TagDecl);
Douglas Gregorc99f1552009-12-03 18:33:45 +00005902
Rafael Espindola06e1b132012-07-12 04:32:30 +00005903 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
5904 if (l->getKind() != AttributeList::AT_Visibility)
5905 continue;
5906 l->setInvalid();
5907 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
5908 l->getName();
5909 }
5910
David Blaikie751c5582011-09-22 02:58:26 +00005911 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCall48871652010-08-21 09:40:31 +00005912 // strict aliasing violation!
5913 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie751c5582011-09-22 02:58:26 +00005914 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor463421d2009-03-03 04:44:36 +00005915
Douglas Gregor0be31a22010-07-02 17:43:08 +00005916 CheckCompletedCXXClass(
John McCall48871652010-08-21 09:40:31 +00005917 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00005918}
5919
Douglas Gregor05379422008-11-03 17:51:48 +00005920/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5921/// special functions, such as the default constructor, copy
5922/// constructor, or destructor, to the given C++ class (C++
5923/// [special]p1). This routine can only be executed just before the
5924/// definition of the class is complete.
Douglas Gregor0be31a22010-07-02 17:43:08 +00005925void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00005926 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00005927 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00005928
Richard Smith6b02d462012-12-08 08:32:28 +00005929 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005930 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00005931
Richard Smith6b02d462012-12-08 08:32:28 +00005932 // If the properties or semantics of the copy constructor couldn't be
5933 // determined while the class was being declared, force a declaration
5934 // of it now.
5935 if (ClassDecl->needsOverloadResolutionForCopyConstructor())
5936 DeclareImplicitCopyConstructor(ClassDecl);
5937 }
5938
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005939 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
Richard Smith966c1fb2011-12-24 21:56:24 +00005940 ++ASTContext::NumImplicitMoveConstructors;
5941
Richard Smith6b02d462012-12-08 08:32:28 +00005942 if (ClassDecl->needsOverloadResolutionForMoveConstructor())
5943 DeclareImplicitMoveConstructor(ClassDecl);
5944 }
5945
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005946 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
5947 ++ASTContext::NumImplicitCopyAssignmentOperators;
Richard Smith6b02d462012-12-08 08:32:28 +00005948
5949 // If we have a dynamic class, then the copy assignment operator may be
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005950 // virtual, so we have to declare it immediately. This ensures that, e.g.,
Richard Smith6b02d462012-12-08 08:32:28 +00005951 // it shows up in the right place in the vtable and that we diagnose
5952 // problems with the implicit exception specification.
5953 if (ClassDecl->isDynamicClass() ||
5954 ClassDecl->needsOverloadResolutionForCopyAssignment())
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005955 DeclareImplicitCopyAssignment(ClassDecl);
5956 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00005957
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005958 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smith966c1fb2011-12-24 21:56:24 +00005959 ++ASTContext::NumImplicitMoveAssignmentOperators;
5960
5961 // Likewise for the move assignment operator.
Richard Smith6b02d462012-12-08 08:32:28 +00005962 if (ClassDecl->isDynamicClass() ||
5963 ClassDecl->needsOverloadResolutionForMoveAssignment())
Richard Smith966c1fb2011-12-24 21:56:24 +00005964 DeclareImplicitMoveAssignment(ClassDecl);
5965 }
5966
Douglas Gregor7454c562010-07-02 20:37:36 +00005967 if (!ClassDecl->hasUserDeclaredDestructor()) {
5968 ++ASTContext::NumImplicitDestructors;
Richard Smith6b02d462012-12-08 08:32:28 +00005969
5970 // If we have a dynamic class, then the destructor may be virtual, so we
Douglas Gregor7454c562010-07-02 20:37:36 +00005971 // have to declare the destructor immediately. This ensures that, e.g., it
5972 // shows up in the right place in the vtable and that we diagnose problems
5973 // with the implicit exception specification.
Richard Smith6b02d462012-12-08 08:32:28 +00005974 if (ClassDecl->isDynamicClass() ||
5975 ClassDecl->needsOverloadResolutionForDestructor())
Douglas Gregor7454c562010-07-02 20:37:36 +00005976 DeclareImplicitDestructor(ClassDecl);
5977 }
Douglas Gregor05379422008-11-03 17:51:48 +00005978}
5979
Francois Pichet1c229c02011-04-22 22:18:13 +00005980void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
5981 if (!D)
5982 return;
5983
5984 int NumParamList = D->getNumTemplateParameterLists();
5985 for (int i = 0; i < NumParamList; i++) {
5986 TemplateParameterList* Params = D->getTemplateParameterList(i);
5987 for (TemplateParameterList::iterator Param = Params->begin(),
5988 ParamEnd = Params->end();
5989 Param != ParamEnd; ++Param) {
5990 NamedDecl *Named = cast<NamedDecl>(*Param);
5991 if (Named->getDeclName()) {
5992 S->AddDecl(Named);
5993 IdResolver.AddDecl(Named);
5994 }
5995 }
5996 }
5997}
5998
John McCall48871652010-08-21 09:40:31 +00005999void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregore61ef622009-09-10 00:12:48 +00006000 if (!D)
6001 return;
6002
6003 TemplateParameterList *Params = 0;
6004 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
6005 Params = Template->getTemplateParameters();
6006 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
6007 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
6008 Params = PartialSpec->getTemplateParameters();
6009 else
Douglas Gregore44a2ad2009-05-27 23:11:45 +00006010 return;
6011
Douglas Gregore44a2ad2009-05-27 23:11:45 +00006012 for (TemplateParameterList::iterator Param = Params->begin(),
6013 ParamEnd = Params->end();
6014 Param != ParamEnd; ++Param) {
6015 NamedDecl *Named = cast<NamedDecl>(*Param);
6016 if (Named->getDeclName()) {
John McCall48871652010-08-21 09:40:31 +00006017 S->AddDecl(Named);
Douglas Gregore44a2ad2009-05-27 23:11:45 +00006018 IdResolver.AddDecl(Named);
6019 }
6020 }
6021}
6022
John McCall48871652010-08-21 09:40:31 +00006023void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00006024 if (!RecordD) return;
6025 AdjustDeclIfTemplate(RecordD);
John McCall48871652010-08-21 09:40:31 +00006026 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall6df5fef2009-12-19 10:49:29 +00006027 PushDeclContext(S, Record);
6028}
6029
John McCall48871652010-08-21 09:40:31 +00006030void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00006031 if (!RecordD) return;
6032 PopDeclContext();
6033}
6034
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006035/// This is used to implement the constant expression evaluation part of the
6036/// attribute enable_if extension. There is nothing in standard C++ which would
6037/// require reentering parameters.
6038void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
6039 if (!Param)
6040 return;
6041
6042 S->AddDecl(Param);
6043 if (Param->getDeclName())
6044 IdResolver.AddDecl(Param);
6045}
6046
Douglas Gregor4d87df52008-12-16 21:30:33 +00006047/// ActOnStartDelayedCXXMethodDeclaration - We have completed
6048/// parsing a top-level (non-nested) C++ class, and we are now
6049/// parsing those parts of the given Method declaration that could
6050/// not be parsed earlier (C++ [class.mem]p2), such as default
6051/// arguments. This action should enter the scope of the given
6052/// Method declaration as if we had just parsed the qualified method
6053/// name. However, it should not bring the parameters into scope;
6054/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCall48871652010-08-21 09:40:31 +00006055void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00006056}
6057
6058/// ActOnDelayedCXXMethodParameter - We've already started a delayed
6059/// C++ method declaration. We're (re-)introducing the given
6060/// function parameter into scope for use in parsing later parts of
6061/// the method declaration. For example, we could see an
6062/// ActOnParamDefaultArgument event for this parameter.
John McCall48871652010-08-21 09:40:31 +00006063void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00006064 if (!ParamD)
6065 return;
Mike Stump11289f42009-09-09 15:08:12 +00006066
John McCall48871652010-08-21 09:40:31 +00006067 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor58354032008-12-24 00:01:03 +00006068
6069 // If this parameter has an unparsed default argument, clear it out
6070 // to make way for the parsed default argument.
6071 if (Param->hasUnparsedDefaultArg())
6072 Param->setDefaultArg(0);
6073
John McCall48871652010-08-21 09:40:31 +00006074 S->AddDecl(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006075 if (Param->getDeclName())
6076 IdResolver.AddDecl(Param);
6077}
6078
6079/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
6080/// processing the delayed method declaration for Method. The method
6081/// declaration is now considered finished. There may be a separate
6082/// ActOnStartOfFunctionDef action later (not necessarily
6083/// immediately!) for this method, if it was also defined inside the
6084/// class body.
John McCall48871652010-08-21 09:40:31 +00006085void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00006086 if (!MethodD)
6087 return;
Mike Stump11289f42009-09-09 15:08:12 +00006088
Douglas Gregorc8c277a2009-08-24 11:57:43 +00006089 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00006090
John McCall48871652010-08-21 09:40:31 +00006091 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006092
6093 // Now that we have our default arguments, check the constructor
6094 // again. It could produce additional diagnostics or affect whether
6095 // the class has implicitly-declared destructors, among other
6096 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006097 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
6098 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006099
6100 // Check the default arguments, which we may have added.
6101 if (!Method->isInvalidDecl())
6102 CheckCXXDefaultArguments(Method);
6103}
6104
Douglas Gregor831c93f2008-11-05 20:51:48 +00006105/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00006106/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00006107/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00006108/// emit diagnostics and set the invalid bit to true. In any case, the type
6109/// will be updated to reflect a well-formed type for the constructor and
6110/// returned.
6111QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00006112 StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006113 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006114
6115 // C++ [class.ctor]p3:
6116 // A constructor shall not be virtual (10.3) or static (9.4). A
6117 // constructor can be invoked for a const, volatile or const
6118 // volatile object. A constructor shall not be declared const,
6119 // volatile, or const volatile (9.3.2).
6120 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00006121 if (!D.isInvalidType())
6122 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6123 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
6124 << SourceRange(D.getIdentifierLoc());
6125 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006126 }
John McCall8e7d6562010-08-26 03:08:43 +00006127 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00006128 if (!D.isInvalidType())
6129 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6130 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6131 << SourceRange(D.getIdentifierLoc());
6132 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00006133 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00006134 }
Mike Stump11289f42009-09-09 15:08:12 +00006135
Abramo Bagnara924a8f32010-12-10 16:29:40 +00006136 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00006137 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00006138 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00006139 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6140 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006141 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00006142 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6143 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006144 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00006145 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6146 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalldb40c7f2010-12-14 08:05:40 +00006147 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006148 }
Mike Stump11289f42009-09-09 15:08:12 +00006149
Douglas Gregordb9d6642011-01-26 05:01:58 +00006150 // C++0x [class.ctor]p4:
6151 // A constructor shall not be declared with a ref-qualifier.
6152 if (FTI.hasRefQualifier()) {
6153 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
6154 << FTI.RefQualifierIsLValueRef
6155 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6156 D.setInvalidType();
6157 }
6158
Douglas Gregor831c93f2008-11-05 20:51:48 +00006159 // Rebuild the function type "R" without any type qualifiers (in
6160 // case any of the errors above fired) and with "void" as the
Douglas Gregor95755162010-07-01 05:10:53 +00006161 // return type, since constructors don't have return types.
John McCall9dd450b2009-09-21 23:43:11 +00006162 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +00006163 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
John McCalldb40c7f2010-12-14 08:05:40 +00006164 return R;
6165
6166 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6167 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00006168 EPI.RefQualifier = RQ_None;
Alp Toker9cacbab2014-01-20 20:26:09 +00006169
6170 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00006171}
6172
Douglas Gregor4d87df52008-12-16 21:30:33 +00006173/// CheckConstructor - Checks a fully-formed constructor for
6174/// well-formedness, issuing any diagnostics required. Returns true if
6175/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006176void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00006177 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00006178 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
6179 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006180 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00006181
6182 // C++ [class.copy]p3:
6183 // A declaration of a constructor for a class X is ill-formed if
6184 // its first parameter is of type (optionally cv-qualified) X and
6185 // either there are no other parameters or else all other
6186 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00006187 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00006188 ((Constructor->getNumParams() == 1) ||
6189 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00006190 Constructor->getParamDecl(1)->hasDefaultArg())) &&
6191 Constructor->getTemplateSpecializationKind()
6192 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00006193 QualType ParamType = Constructor->getParamDecl(0)->getType();
6194 QualType ClassTy = Context.getTagDeclType(ClassDecl);
6195 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00006196 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregorfd42e952010-05-27 21:28:21 +00006197 const char *ConstRef
6198 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
6199 : " const &";
Douglas Gregor170512f2009-04-01 23:51:29 +00006200 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregorfd42e952010-05-27 21:28:21 +00006201 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregorffe14e32009-11-14 01:20:54 +00006202
6203 // FIXME: Rather that making the constructor invalid, we should endeavor
6204 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006205 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00006206 }
6207 }
Douglas Gregor4d87df52008-12-16 21:30:33 +00006208}
6209
John McCalldeb646e2010-08-04 01:04:25 +00006210/// CheckDestructor - Checks a fully-formed destructor definition for
6211/// well-formedness, issuing any diagnostics required. Returns true
6212/// on error.
Anders Carlssonf98849e2009-12-02 17:15:43 +00006213bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00006214 CXXRecordDecl *RD = Destructor->getParent();
6215
Peter Collingbourneb289fe62013-05-20 14:12:25 +00006216 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00006217 SourceLocation Loc;
6218
6219 if (!Destructor->isImplicit())
6220 Loc = Destructor->getLocation();
6221 else
6222 Loc = RD->getLocation();
6223
6224 // If we have a virtual destructor, look up the deallocation function
6225 FunctionDecl *OperatorDelete = 0;
6226 DeclarationName Name =
6227 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlssonf98849e2009-12-02 17:15:43 +00006228 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson26a807d2009-11-30 21:24:50 +00006229 return true;
Richard Smithf03bd302013-12-05 08:30:59 +00006230 // If there's no class-specific operator delete, look up the global
6231 // non-array delete.
6232 if (!OperatorDelete)
6233 OperatorDelete = FindUsualDeallocationFunction(Loc, true, Name);
John McCall1e5d75d2010-07-03 18:33:00 +00006234
Eli Friedmanfa0df832012-02-02 03:46:19 +00006235 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson26a807d2009-11-30 21:24:50 +00006236
6237 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson2a50e952009-11-15 22:49:34 +00006238 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00006239
6240 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00006241}
6242
Mike Stump11289f42009-09-09 15:08:12 +00006243static inline bool
Anders Carlsson5e965472009-04-30 23:18:11 +00006244FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
Alp Tokerc5350722014-02-26 22:27:52 +00006245 return (FTI.NumParams == 1 && !FTI.isVariadic && FTI.Params[0].Ident == 0 &&
6246 FTI.Params[0].Param &&
6247 cast<ParmVarDecl>(FTI.Params[0].Param)->getType()->isVoidType());
Anders Carlsson5e965472009-04-30 23:18:11 +00006248}
6249
Douglas Gregor831c93f2008-11-05 20:51:48 +00006250/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
6251/// the well-formednes of the destructor declarator @p D with type @p
6252/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00006253/// emit diagnostics and set the declarator to invalid. Even if this happens,
6254/// will be updated to reflect a well-formed type for the destructor and
6255/// returned.
Douglas Gregor95755162010-07-01 05:10:53 +00006256QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00006257 StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006258 // C++ [class.dtor]p1:
6259 // [...] A typedef-name that names a class is a class-name
6260 // (7.1.3); however, a typedef-name that names a class shall not
6261 // be used as the identifier in the declarator for a destructor
6262 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00006263 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smithdda56e42011-04-15 14:24:37 +00006264 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner38378bf2009-04-25 08:28:21 +00006265 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smithdda56e42011-04-15 14:24:37 +00006266 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00006267 else if (const TemplateSpecializationType *TST =
6268 DeclaratorType->getAs<TemplateSpecializationType>())
6269 if (TST->isTypeAlias())
6270 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6271 << DeclaratorType << 1;
Douglas Gregor831c93f2008-11-05 20:51:48 +00006272
6273 // C++ [class.dtor]p2:
6274 // A destructor is used to destroy objects of its class type. A
6275 // destructor takes no parameters, and no return type can be
6276 // specified for it (not even void). The address of a destructor
6277 // shall not be taken. A destructor shall not be static. A
6278 // destructor can be invoked for a const, volatile or const
6279 // volatile object. A destructor shall not be declared const,
6280 // volatile or const volatile (9.3.2).
John McCall8e7d6562010-08-26 03:08:43 +00006281 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00006282 if (!D.isInvalidType())
6283 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
6284 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregor95755162010-07-01 05:10:53 +00006285 << SourceRange(D.getIdentifierLoc())
6286 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6287
John McCall8e7d6562010-08-26 03:08:43 +00006288 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00006289 }
Chris Lattner38378bf2009-04-25 08:28:21 +00006290 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006291 // Destructors don't have return types, but the parser will
6292 // happily parse something like:
6293 //
6294 // class X {
6295 // float ~X();
6296 // };
6297 //
6298 // The return type will be eliminated later.
Chris Lattner3b054132008-11-19 05:08:23 +00006299 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
6300 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6301 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00006302 }
Mike Stump11289f42009-09-09 15:08:12 +00006303
Abramo Bagnara924a8f32010-12-10 16:29:40 +00006304 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00006305 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00006306 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00006307 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6308 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006309 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00006310 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6311 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006312 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00006313 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6314 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00006315 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006316 }
6317
Douglas Gregordb9d6642011-01-26 05:01:58 +00006318 // C++0x [class.dtor]p2:
6319 // A destructor shall not be declared with a ref-qualifier.
6320 if (FTI.hasRefQualifier()) {
6321 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
6322 << FTI.RefQualifierIsLValueRef
6323 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6324 D.setInvalidType();
6325 }
6326
Douglas Gregor831c93f2008-11-05 20:51:48 +00006327 // Make sure we don't have any parameters.
Alp Tokerc5350722014-02-26 22:27:52 +00006328 if (FTI.NumParams > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006329 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
6330
6331 // Delete the parameters.
Alp Tokerc5350722014-02-26 22:27:52 +00006332 FTI.freeParams();
Chris Lattner38378bf2009-04-25 08:28:21 +00006333 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006334 }
6335
Mike Stump11289f42009-09-09 15:08:12 +00006336 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00006337 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006338 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00006339 D.setInvalidType();
6340 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00006341
6342 // Rebuild the function type "R" without any type qualifiers or
6343 // parameters (in case any of the errors above fired) and with
6344 // "void" as the return type, since destructors don't have return
Douglas Gregor95755162010-07-01 05:10:53 +00006345 // types.
John McCalldb40c7f2010-12-14 08:05:40 +00006346 if (!D.isInvalidType())
6347 return R;
6348
Douglas Gregor95755162010-07-01 05:10:53 +00006349 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00006350 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6351 EPI.Variadic = false;
6352 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00006353 EPI.RefQualifier = RQ_None;
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00006354 return Context.getFunctionType(Context.VoidTy, None, EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00006355}
6356
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006357/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6358/// well-formednes of the conversion function declarator @p D with
6359/// type @p R. If there are any errors in the declarator, this routine
6360/// will emit diagnostics and return true. Otherwise, it will return
6361/// false. Either way, the type @p R will be updated to reflect a
6362/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006363void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCall8e7d6562010-08-26 03:08:43 +00006364 StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006365 // C++ [class.conv.fct]p1:
6366 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00006367 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00006368 // parameter returning conversion-type-id."
John McCall8e7d6562010-08-26 03:08:43 +00006369 if (SC == SC_Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006370 if (!D.isInvalidType())
6371 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
Eli Friedman600bc242013-06-20 20:58:02 +00006372 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6373 << D.getName().getSourceRange();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006374 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00006375 SC = SC_None;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006376 }
John McCall212fa2e2010-04-13 00:04:31 +00006377
6378 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
6379
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006380 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006381 // Conversion functions don't have return types, but the parser will
6382 // happily parse something like:
6383 //
6384 // class X {
6385 // float operator bool();
6386 // };
6387 //
6388 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00006389 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
6390 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6391 << SourceRange(D.getIdentifierLoc());
John McCall212fa2e2010-04-13 00:04:31 +00006392 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006393 }
6394
John McCall212fa2e2010-04-13 00:04:31 +00006395 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6396
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006397 // Make sure we don't have any parameters.
Alp Toker9cacbab2014-01-20 20:26:09 +00006398 if (Proto->getNumParams() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006399 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
6400
6401 // Delete the parameters.
Alp Tokerc5350722014-02-26 22:27:52 +00006402 D.getFunctionTypeInfo().freeParams();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006403 D.setInvalidType();
John McCall212fa2e2010-04-13 00:04:31 +00006404 } else if (Proto->isVariadic()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006405 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006406 D.setInvalidType();
6407 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006408
John McCall212fa2e2010-04-13 00:04:31 +00006409 // Diagnose "&operator bool()" and other such nonsense. This
6410 // is actually a gcc extension which we don't support.
Alp Toker314cc812014-01-25 16:55:45 +00006411 if (Proto->getReturnType() != ConvType) {
John McCall212fa2e2010-04-13 00:04:31 +00006412 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
Alp Toker314cc812014-01-25 16:55:45 +00006413 << Proto->getReturnType();
John McCall212fa2e2010-04-13 00:04:31 +00006414 D.setInvalidType();
Alp Toker314cc812014-01-25 16:55:45 +00006415 ConvType = Proto->getReturnType();
John McCall212fa2e2010-04-13 00:04:31 +00006416 }
6417
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006418 // C++ [class.conv.fct]p4:
6419 // The conversion-type-id shall not represent a function type nor
6420 // an array type.
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006421 if (ConvType->isArrayType()) {
6422 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
6423 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006424 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006425 } else if (ConvType->isFunctionType()) {
6426 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
6427 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006428 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006429 }
6430
6431 // Rebuild the function type "R" without any parameters (in case any
6432 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00006433 // return type.
John McCalldb40c7f2010-12-14 08:05:40 +00006434 if (D.isInvalidType())
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00006435 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006436
Douglas Gregor5fb53972009-01-14 15:45:31 +00006437 // C++0x explicit conversion operators.
Richard Smith0bf8a4922011-10-18 20:49:44 +00006438 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump11289f42009-09-09 15:08:12 +00006439 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006440 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00006441 diag::warn_cxx98_compat_explicit_conversion_functions :
6442 diag::ext_explicit_conversion_functions)
Douglas Gregor5fb53972009-01-14 15:45:31 +00006443 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006444}
6445
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006446/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
6447/// the declaration of the given C++ conversion function. This routine
6448/// is responsible for recording the conversion function in the C++
6449/// class, if possible.
John McCall48871652010-08-21 09:40:31 +00006450Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006451 assert(Conversion && "Expected to receive a conversion function declaration");
6452
Douglas Gregor4287b372008-12-12 08:25:50 +00006453 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006454
6455 // Make sure we aren't redeclaring the conversion function.
6456 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006457
6458 // C++ [class.conv.fct]p1:
6459 // [...] A conversion function is never used to convert a
6460 // (possibly cv-qualified) object to the (possibly cv-qualified)
6461 // same object type (or a reference to it), to a (possibly
6462 // cv-qualified) base class of that type (or a reference to it),
6463 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00006464 // FIXME: Suppress this warning if the conversion function ends up being a
6465 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00006466 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006467 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006468 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006469 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregor6309e3d2010-09-12 07:22:28 +00006470 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
6471 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregore47191c2010-09-13 16:44:26 +00006472 /* Suppress diagnostics for instantiations. */;
Douglas Gregor6309e3d2010-09-12 07:22:28 +00006473 else if (ConvType->isRecordType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006474 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
6475 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00006476 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006477 << ClassType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006478 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00006479 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006480 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006481 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00006482 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006483 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006484 }
6485
Douglas Gregor457104e2010-09-29 04:25:11 +00006486 if (FunctionTemplateDecl *ConversionTemplate
6487 = Conversion->getDescribedFunctionTemplate())
6488 return ConversionTemplate;
6489
John McCall48871652010-08-21 09:40:31 +00006490 return Conversion;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006491}
6492
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006493//===----------------------------------------------------------------------===//
6494// Namespace Handling
6495//===----------------------------------------------------------------------===//
6496
Richard Smith45bb8852012-10-04 22:13:39 +00006497/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
6498/// reopened.
6499static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
6500 SourceLocation Loc,
6501 IdentifierInfo *II, bool *IsInline,
6502 NamespaceDecl *PrevNS) {
6503 assert(*IsInline != PrevNS->isInline());
John McCallb1be5232010-08-26 09:15:37 +00006504
Richard Smithf501cc32012-10-05 01:46:25 +00006505 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
6506 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
6507 // inline namespaces, with the intention of bringing names into namespace std.
6508 //
6509 // We support this just well enough to get that case working; this is not
6510 // sufficient to support reopening namespaces as inline in general.
Richard Smith45bb8852012-10-04 22:13:39 +00006511 if (*IsInline && II && II->getName().startswith("__atomic") &&
6512 S.getSourceManager().isInSystemHeader(Loc)) {
Richard Smithf501cc32012-10-05 01:46:25 +00006513 // Mark all prior declarations of the namespace as inline.
Richard Smith45bb8852012-10-04 22:13:39 +00006514 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
6515 NS = NS->getPreviousDecl())
6516 NS->setInline(*IsInline);
6517 // Patch up the lookup table for the containing namespace. This isn't really
6518 // correct, but it's good enough for this particular case.
Aaron Ballman629afae2014-03-07 19:56:05 +00006519 for (auto *I : PrevNS->decls())
6520 if (auto *ND = dyn_cast<NamedDecl>(I))
Richard Smith45bb8852012-10-04 22:13:39 +00006521 PrevNS->getParent()->makeDeclVisibleInContext(ND);
6522 return;
6523 }
6524
6525 if (PrevNS->isInline())
6526 // The user probably just forgot the 'inline', so suggest that it
6527 // be added back.
6528 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
6529 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
6530 else
Richard Smith5b5d21e2014-03-12 23:36:42 +00006531 S.Diag(Loc, diag::err_inline_namespace_mismatch) << *IsInline;
Richard Smith45bb8852012-10-04 22:13:39 +00006532
6533 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
6534 *IsInline = PrevNS->isInline();
6535}
John McCallb1be5232010-08-26 09:15:37 +00006536
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006537/// ActOnStartNamespaceDef - This is called at the start of a namespace
6538/// definition.
John McCall48871652010-08-21 09:40:31 +00006539Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redl67667942010-08-27 23:12:46 +00006540 SourceLocation InlineLoc,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00006541 SourceLocation NamespaceLoc,
John McCallb1be5232010-08-26 09:15:37 +00006542 SourceLocation IdentLoc,
6543 IdentifierInfo *II,
6544 SourceLocation LBrace,
6545 AttributeList *AttrList) {
Abramo Bagnarab5545be2011-03-08 12:38:20 +00006546 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
6547 // For anonymous namespace, take the location of the left brace.
6548 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregore57e7522012-01-07 09:11:48 +00006549 bool IsInline = InlineLoc.isValid();
Douglas Gregor21b3b292012-01-10 22:14:10 +00006550 bool IsInvalid = false;
Douglas Gregore57e7522012-01-07 09:11:48 +00006551 bool IsStd = false;
6552 bool AddToKnown = false;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006553 Scope *DeclRegionScope = NamespcScope->getParent();
6554
Douglas Gregore57e7522012-01-07 09:11:48 +00006555 NamespaceDecl *PrevNS = 0;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006556 if (II) {
6557 // C++ [namespace.def]p2:
Douglas Gregor412c3622010-10-22 15:24:46 +00006558 // The identifier in an original-namespace-definition shall not
6559 // have been previously defined in the declarative region in
6560 // which the original-namespace-definition appears. The
6561 // identifier in an original-namespace-definition is the name of
6562 // the namespace. Subsequently in that declarative region, it is
6563 // treated as an original-namespace-name.
6564 //
6565 // Since namespace names are unique in their scope, and we don't
Douglas Gregorb578fbe2011-05-06 23:28:47 +00006566 // look through using directives, just look for any ordinary names.
6567
6568 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregore57e7522012-01-07 09:11:48 +00006569 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
6570 Decl::IDNS_Namespace;
Douglas Gregorb578fbe2011-05-06 23:28:47 +00006571 NamedDecl *PrevDecl = 0;
David Blaikieff7d47a2012-12-19 00:45:41 +00006572 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
6573 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6574 ++I) {
6575 if ((*I)->getIdentifierNamespace() & IDNS) {
6576 PrevDecl = *I;
Douglas Gregorb578fbe2011-05-06 23:28:47 +00006577 break;
6578 }
6579 }
6580
Douglas Gregore57e7522012-01-07 09:11:48 +00006581 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
6582
6583 if (PrevNS) {
Douglas Gregor91f84212008-12-11 16:49:14 +00006584 // This is an extended namespace definition.
Richard Smith45bb8852012-10-04 22:13:39 +00006585 if (IsInline != PrevNS->isInline())
6586 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
6587 &IsInline, PrevNS);
Douglas Gregor91f84212008-12-11 16:49:14 +00006588 } else if (PrevDecl) {
6589 // This is an invalid name redefinition.
Douglas Gregore57e7522012-01-07 09:11:48 +00006590 Diag(Loc, diag::err_redefinition_different_kind)
6591 << II;
Douglas Gregor91f84212008-12-11 16:49:14 +00006592 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor21b3b292012-01-10 22:14:10 +00006593 IsInvalid = true;
Douglas Gregor91f84212008-12-11 16:49:14 +00006594 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregore57e7522012-01-07 09:11:48 +00006595 } else if (II->isStr("std") &&
Sebastian Redl50c68252010-08-31 00:36:30 +00006596 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00006597 // This is the first "real" definition of the namespace "std", so update
6598 // our cache of the "std" namespace to point at this definition.
Douglas Gregore57e7522012-01-07 09:11:48 +00006599 PrevNS = getStdNamespace();
6600 IsStd = true;
6601 AddToKnown = !IsInline;
6602 } else {
6603 // We've seen this namespace for the first time.
6604 AddToKnown = !IsInline;
Mike Stump11289f42009-09-09 15:08:12 +00006605 }
Douglas Gregor91f84212008-12-11 16:49:14 +00006606 } else {
John McCall4fa53422009-10-01 00:25:31 +00006607 // Anonymous namespaces.
Douglas Gregore57e7522012-01-07 09:11:48 +00006608
6609 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl50c68252010-08-31 00:36:30 +00006610 DeclContext *Parent = CurContext->getRedeclContext();
John McCall0db42252009-12-16 02:06:49 +00006611 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregore57e7522012-01-07 09:11:48 +00006612 PrevNS = TU->getAnonymousNamespace();
John McCall0db42252009-12-16 02:06:49 +00006613 } else {
6614 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregore57e7522012-01-07 09:11:48 +00006615 PrevNS = ND->getAnonymousNamespace();
John McCall0db42252009-12-16 02:06:49 +00006616 }
6617
Richard Smith45bb8852012-10-04 22:13:39 +00006618 if (PrevNS && IsInline != PrevNS->isInline())
6619 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
6620 &IsInline, PrevNS);
Douglas Gregore57e7522012-01-07 09:11:48 +00006621 }
6622
6623 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
6624 StartLoc, Loc, II, PrevNS);
Douglas Gregor21b3b292012-01-10 22:14:10 +00006625 if (IsInvalid)
6626 Namespc->setInvalidDecl();
Douglas Gregore57e7522012-01-07 09:11:48 +00006627
6628 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00006629
Douglas Gregore57e7522012-01-07 09:11:48 +00006630 // FIXME: Should we be merging attributes?
6631 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola6d65d7b2012-02-01 23:24:59 +00006632 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregore57e7522012-01-07 09:11:48 +00006633
6634 if (IsStd)
6635 StdNamespace = Namespc;
6636 if (AddToKnown)
6637 KnownNamespaces[Namespc] = false;
6638
6639 if (II) {
6640 PushOnScopeChains(Namespc, DeclRegionScope);
6641 } else {
6642 // Link the anonymous namespace into its parent.
6643 DeclContext *Parent = CurContext->getRedeclContext();
6644 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6645 TU->setAnonymousNamespace(Namespc);
6646 } else {
6647 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall0db42252009-12-16 02:06:49 +00006648 }
John McCall4fa53422009-10-01 00:25:31 +00006649
Douglas Gregorf9f54ea2010-03-24 00:46:35 +00006650 CurContext->addDecl(Namespc);
6651
John McCall4fa53422009-10-01 00:25:31 +00006652 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
6653 // behaves as if it were replaced by
6654 // namespace unique { /* empty body */ }
6655 // using namespace unique;
6656 // namespace unique { namespace-body }
6657 // where all occurrences of 'unique' in a translation unit are
6658 // replaced by the same identifier and this identifier differs
6659 // from all other identifiers in the entire program.
6660
6661 // We just create the namespace with an empty name and then add an
6662 // implicit using declaration, just like the standard suggests.
6663 //
6664 // CodeGen enforces the "universally unique" aspect by giving all
6665 // declarations semantically contained within an anonymous
6666 // namespace internal linkage.
6667
Douglas Gregore57e7522012-01-07 09:11:48 +00006668 if (!PrevNS) {
John McCall0db42252009-12-16 02:06:49 +00006669 UsingDirectiveDecl* UD
Nick Lewycky38115822012-11-04 20:21:54 +00006670 = UsingDirectiveDecl::Create(Context, Parent,
John McCall0db42252009-12-16 02:06:49 +00006671 /* 'using' */ LBrace,
6672 /* 'namespace' */ SourceLocation(),
Douglas Gregor12441b32011-02-25 16:33:46 +00006673 /* qualifier */ NestedNameSpecifierLoc(),
John McCall0db42252009-12-16 02:06:49 +00006674 /* identifier */ SourceLocation(),
6675 Namespc,
Nick Lewycky38115822012-11-04 20:21:54 +00006676 /* Ancestor */ Parent);
John McCall0db42252009-12-16 02:06:49 +00006677 UD->setImplicit();
Nick Lewycky38115822012-11-04 20:21:54 +00006678 Parent->addDecl(UD);
John McCall0db42252009-12-16 02:06:49 +00006679 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006680 }
6681
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00006682 ActOnDocumentableDecl(Namespc);
6683
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006684 // Although we could have an invalid decl (i.e. the namespace name is a
6685 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00006686 // FIXME: We should be able to push Namespc here, so that the each DeclContext
6687 // for the namespace has the declarations that showed up in that particular
6688 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00006689 PushDeclContext(NamespcScope, Namespc);
John McCall48871652010-08-21 09:40:31 +00006690 return Namespc;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006691}
6692
Sebastian Redla6602e92009-11-23 15:34:23 +00006693/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
6694/// is a namespace alias, returns the namespace it points to.
6695static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
6696 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
6697 return AD->getNamespace();
6698 return dyn_cast_or_null<NamespaceDecl>(D);
6699}
6700
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006701/// ActOnFinishNamespaceDef - This callback is called after a namespace is
6702/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCall48871652010-08-21 09:40:31 +00006703void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006704 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
6705 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnarab5545be2011-03-08 12:38:20 +00006706 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006707 PopDeclContext();
Eli Friedman570024a2010-08-05 06:57:20 +00006708 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola6d65d7b2012-02-01 23:24:59 +00006709 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006710}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006711
John McCall28a0cf72010-08-25 07:42:41 +00006712CXXRecordDecl *Sema::getStdBadAlloc() const {
6713 return cast_or_null<CXXRecordDecl>(
6714 StdBadAlloc.get(Context.getExternalSource()));
6715}
6716
6717NamespaceDecl *Sema::getStdNamespace() const {
6718 return cast_or_null<NamespaceDecl>(
6719 StdNamespace.get(Context.getExternalSource()));
6720}
6721
Douglas Gregorcdf87022010-06-29 17:53:46 +00006722/// \brief Retrieve the special "std" namespace, which may require us to
6723/// implicitly define the namespace.
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00006724NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregorcdf87022010-06-29 17:53:46 +00006725 if (!StdNamespace) {
6726 // The "std" namespace has not yet been defined, so build one implicitly.
6727 StdNamespace = NamespaceDecl::Create(Context,
6728 Context.getTranslationUnitDecl(),
Douglas Gregore57e7522012-01-07 09:11:48 +00006729 /*Inline=*/false,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00006730 SourceLocation(), SourceLocation(),
Douglas Gregore57e7522012-01-07 09:11:48 +00006731 &PP.getIdentifierTable().get("std"),
6732 /*PrevDecl=*/0);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00006733 getStdNamespace()->setImplicit(true);
Douglas Gregorcdf87022010-06-29 17:53:46 +00006734 }
6735
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00006736 return getStdNamespace();
Douglas Gregorcdf87022010-06-29 17:53:46 +00006737}
6738
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006739bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006740 assert(getLangOpts().CPlusPlus &&
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006741 "Looking for std::initializer_list outside of C++.");
6742
6743 // We're looking for implicit instantiations of
6744 // template <typename E> class std::initializer_list.
6745
6746 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
6747 return false;
6748
Sebastian Redl43144e72012-01-17 22:49:58 +00006749 ClassTemplateDecl *Template = 0;
6750 const TemplateArgument *Arguments = 0;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006751
Sebastian Redl43144e72012-01-17 22:49:58 +00006752 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006753
Sebastian Redl43144e72012-01-17 22:49:58 +00006754 ClassTemplateSpecializationDecl *Specialization =
6755 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
6756 if (!Specialization)
6757 return false;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006758
Sebastian Redl43144e72012-01-17 22:49:58 +00006759 Template = Specialization->getSpecializedTemplate();
6760 Arguments = Specialization->getTemplateArgs().data();
6761 } else if (const TemplateSpecializationType *TST =
6762 Ty->getAs<TemplateSpecializationType>()) {
6763 Template = dyn_cast_or_null<ClassTemplateDecl>(
6764 TST->getTemplateName().getAsTemplateDecl());
6765 Arguments = TST->getArgs();
6766 }
6767 if (!Template)
6768 return false;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006769
6770 if (!StdInitializerList) {
6771 // Haven't recognized std::initializer_list yet, maybe this is it.
6772 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
6773 if (TemplateClass->getIdentifier() !=
6774 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redl09edce02012-01-23 22:09:39 +00006775 !getStdNamespace()->InEnclosingNamespaceSetOf(
6776 TemplateClass->getDeclContext()))
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006777 return false;
6778 // This is a template called std::initializer_list, but is it the right
6779 // template?
6780 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redl09edce02012-01-23 22:09:39 +00006781 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006782 return false;
6783 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
6784 return false;
6785
6786 // It's the right template.
6787 StdInitializerList = Template;
6788 }
6789
6790 if (Template != StdInitializerList)
6791 return false;
6792
6793 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl43144e72012-01-17 22:49:58 +00006794 if (Element)
6795 *Element = Arguments[0].getAsType();
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006796 return true;
6797}
6798
Sebastian Redl42acd4a2012-01-17 22:50:08 +00006799static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
6800 NamespaceDecl *Std = S.getStdNamespace();
6801 if (!Std) {
6802 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6803 return 0;
6804 }
6805
6806 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
6807 Loc, Sema::LookupOrdinaryName);
6808 if (!S.LookupQualifiedName(Result, Std)) {
6809 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6810 return 0;
6811 }
6812 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
6813 if (!Template) {
6814 Result.suppressDiagnostics();
6815 // We found something weird. Complain about the first thing we found.
6816 NamedDecl *Found = *Result.begin();
6817 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
6818 return 0;
6819 }
6820
6821 // We found some template called std::initializer_list. Now verify that it's
6822 // correct.
6823 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redl09edce02012-01-23 22:09:39 +00006824 if (Params->getMinRequiredArguments() != 1 ||
6825 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl42acd4a2012-01-17 22:50:08 +00006826 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
6827 return 0;
6828 }
6829
6830 return Template;
6831}
6832
6833QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
6834 if (!StdInitializerList) {
6835 StdInitializerList = LookupStdInitializerList(*this, Loc);
6836 if (!StdInitializerList)
6837 return QualType();
6838 }
6839
6840 TemplateArgumentListInfo Args(Loc, Loc);
6841 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
6842 Context.getTrivialTypeSourceInfo(Element,
6843 Loc)));
6844 return Context.getCanonicalType(
6845 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
6846}
6847
Sebastian Redlbe24ec22012-01-17 22:50:14 +00006848bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
6849 // C++ [dcl.init.list]p2:
6850 // A constructor is an initializer-list constructor if its first parameter
6851 // is of type std::initializer_list<E> or reference to possibly cv-qualified
6852 // std::initializer_list<E> for some type E, and either there are no other
6853 // parameters or else all other parameters have default arguments.
6854 if (Ctor->getNumParams() < 1 ||
6855 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
6856 return false;
6857
6858 QualType ArgType = Ctor->getParamDecl(0)->getType();
6859 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
6860 ArgType = RT->getPointeeType().getUnqualifiedType();
6861
6862 return isStdInitializerList(ArgType, 0);
6863}
6864
Douglas Gregora172e082011-03-26 22:25:30 +00006865/// \brief Determine whether a using statement is in a context where it will be
6866/// apply in all contexts.
6867static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
6868 switch (CurContext->getDeclKind()) {
6869 case Decl::TranslationUnit:
6870 return true;
6871 case Decl::LinkageSpec:
6872 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
6873 default:
6874 return false;
6875 }
6876}
6877
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00006878namespace {
6879
6880// Callback to only accept typo corrections that are namespaces.
6881class NamespaceValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00006882public:
Craig Toppera798a9d2014-03-02 09:32:10 +00006883 bool ValidateCandidate(const TypoCorrection &candidate) override {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00006884 if (NamedDecl *ND = candidate.getCorrectionDecl())
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00006885 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00006886 return false;
6887 }
6888};
6889
6890}
6891
Douglas Gregorc2fa1692011-06-28 16:20:02 +00006892static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
6893 CXXScopeSpec &SS,
6894 SourceLocation IdentLoc,
6895 IdentifierInfo *Ident) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00006896 NamespaceValidatorCCC Validator;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00006897 R.clear();
6898 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00006899 R.getLookupKind(), Sc, &SS,
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00006900 Validator)) {
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00006901 if (DeclContext *DC = S.computeDeclContext(SS, false)) {
Richard Smithf9b15102013-08-17 00:46:16 +00006902 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
6903 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00006904 Ident->getName().equals(CorrectedStr);
Richard Smithf9b15102013-08-17 00:46:16 +00006905 S.diagnoseTypo(Corrected,
6906 S.PDiag(diag::err_using_directive_member_suggest)
6907 << Ident << DC << DroppedSpecifier << SS.getRange(),
6908 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00006909 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00006910 S.diagnoseTypo(Corrected,
6911 S.PDiag(diag::err_using_directive_suggest) << Ident,
6912 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00006913 }
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00006914 R.addDecl(Corrected.getCorrectionDecl());
6915 return true;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00006916 }
6917 return false;
6918}
6919
John McCall48871652010-08-21 09:40:31 +00006920Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattner83f095c2009-03-28 19:18:32 +00006921 SourceLocation UsingLoc,
6922 SourceLocation NamespcLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00006923 CXXScopeSpec &SS,
Chris Lattner83f095c2009-03-28 19:18:32 +00006924 SourceLocation IdentLoc,
6925 IdentifierInfo *NamespcName,
6926 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00006927 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6928 assert(NamespcName && "Invalid NamespcName.");
6929 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall9b72f892010-11-10 02:40:36 +00006930
6931 // This can only happen along a recovery path.
6932 while (S->getFlags() & Scope::TemplateParamScope)
6933 S = S->getParent();
Douglas Gregor889ceb72009-02-03 19:21:40 +00006934 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00006935
Douglas Gregor889ceb72009-02-03 19:21:40 +00006936 UsingDirectiveDecl *UDir = 0;
Douglas Gregorcdf87022010-06-29 17:53:46 +00006937 NestedNameSpecifier *Qualifier = 0;
6938 if (SS.isSet())
Aaron Ballman4a979672014-01-03 13:56:08 +00006939 Qualifier = SS.getScopeRep();
Douglas Gregorcdf87022010-06-29 17:53:46 +00006940
Douglas Gregor34074322009-01-14 22:20:51 +00006941 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00006942 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
6943 LookupParsedName(R, S, &SS);
6944 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00006945 return 0;
John McCall27b18f82009-11-17 02:14:36 +00006946
Douglas Gregorcdf87022010-06-29 17:53:46 +00006947 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00006948 R.clear();
Douglas Gregorcdf87022010-06-29 17:53:46 +00006949 // Allow "using namespace std;" or "using namespace ::std;" even if
6950 // "std" hasn't been defined yet, for GCC compatibility.
6951 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
6952 NamespcName->isStr("std")) {
6953 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00006954 R.addDecl(getOrCreateStdNamespace());
Douglas Gregorcdf87022010-06-29 17:53:46 +00006955 R.resolveKind();
6956 }
6957 // Otherwise, attempt typo correction.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00006958 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregorcdf87022010-06-29 17:53:46 +00006959 }
6960
John McCall9f3059a2009-10-09 21:13:30 +00006961 if (!R.empty()) {
Sebastian Redla6602e92009-11-23 15:34:23 +00006962 NamedDecl *Named = R.getFoundDecl();
6963 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
6964 && "expected namespace decl");
Douglas Gregor889ceb72009-02-03 19:21:40 +00006965 // C++ [namespace.udir]p1:
6966 // A using-directive specifies that the names in the nominated
6967 // namespace can be used in the scope in which the
6968 // using-directive appears after the using-directive. During
6969 // unqualified name lookup (3.4.1), the names appear as if they
6970 // were declared in the nearest enclosing namespace which
6971 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00006972 // namespace. [Note: in this context, "contains" means "contains
6973 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00006974
6975 // Find enclosing context containing both using-directive and
6976 // nominated namespace.
Sebastian Redla6602e92009-11-23 15:34:23 +00006977 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor889ceb72009-02-03 19:21:40 +00006978 DeclContext *CommonAncestor = cast<DeclContext>(NS);
6979 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
6980 CommonAncestor = CommonAncestor->getParent();
6981
Sebastian Redla6602e92009-11-23 15:34:23 +00006982 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor12441b32011-02-25 16:33:46 +00006983 SS.getWithLocInContext(Context),
Sebastian Redla6602e92009-11-23 15:34:23 +00006984 IdentLoc, Named, CommonAncestor);
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00006985
Douglas Gregora172e082011-03-26 22:25:30 +00006986 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Eli Friedman5ba37d52013-08-22 00:27:10 +00006987 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00006988 Diag(IdentLoc, diag::warn_using_directive_in_header);
6989 }
6990
Douglas Gregor889ceb72009-02-03 19:21:40 +00006991 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00006992 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00006993 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00006994 }
6995
Richard Smith54ecd982013-02-20 19:22:51 +00006996 if (UDir)
6997 ProcessDeclAttributeList(S, UDir, AttrList);
6998
John McCall48871652010-08-21 09:40:31 +00006999 return UDir;
Douglas Gregor889ceb72009-02-03 19:21:40 +00007000}
7001
7002void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith05afe5e2012-03-13 03:12:56 +00007003 // If the scope has an associated entity and the using directive is at
7004 // namespace or translation unit scope, add the UsingDirectiveDecl into
7005 // its lookup structure so qualified name lookup can find it.
Ted Kremenekc37877d2013-10-08 17:08:03 +00007006 DeclContext *Ctx = S->getEntity();
Richard Smith05afe5e2012-03-13 03:12:56 +00007007 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00007008 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00007009 else
Richard Smith05afe5e2012-03-13 03:12:56 +00007010 // Otherwise, it is at block sope. The using-directives will affect lookup
7011 // only to the end of the scope.
John McCall48871652010-08-21 09:40:31 +00007012 S->PushUsingDirective(UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00007013}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00007014
Douglas Gregorfec52632009-06-20 00:51:54 +00007015
John McCall48871652010-08-21 09:40:31 +00007016Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall9b72f892010-11-10 02:40:36 +00007017 AccessSpecifier AS,
7018 bool HasUsingKeyword,
7019 SourceLocation UsingLoc,
7020 CXXScopeSpec &SS,
7021 UnqualifiedId &Name,
7022 AttributeList *AttrList,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007023 bool HasTypenameKeyword,
John McCall9b72f892010-11-10 02:40:36 +00007024 SourceLocation TypenameLoc) {
Douglas Gregorfec52632009-06-20 00:51:54 +00007025 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00007026
Douglas Gregor220f4272009-11-04 16:30:06 +00007027 switch (Name.getKind()) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00007028 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor220f4272009-11-04 16:30:06 +00007029 case UnqualifiedId::IK_Identifier:
7030 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00007031 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00007032 case UnqualifiedId::IK_ConversionFunctionId:
7033 break;
7034
7035 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor9de54ea2010-01-13 17:31:36 +00007036 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smithd494c502012-04-27 19:33:05 +00007037 // C++11 inheriting constructors.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007038 Diag(Name.getLocStart(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007039 getLangOpts().CPlusPlus11 ?
Richard Smithc2bc61b2013-03-18 21:12:30 +00007040 diag::warn_cxx98_compat_using_decl_constructor :
Richard Smith0bf8a4922011-10-18 20:49:44 +00007041 diag::err_using_decl_constructor)
7042 << SS.getRange();
7043
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007044 if (getLangOpts().CPlusPlus11) break;
John McCall3969e302009-12-08 07:46:18 +00007045
John McCall48871652010-08-21 09:40:31 +00007046 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00007047
7048 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007049 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor220f4272009-11-04 16:30:06 +00007050 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00007051 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00007052
7053 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007054 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor220f4272009-11-04 16:30:06 +00007055 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCall48871652010-08-21 09:40:31 +00007056 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00007057 }
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007058
7059 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
7060 DeclarationName TargetName = TargetNameInfo.getName();
John McCall3969e302009-12-08 07:46:18 +00007061 if (!TargetName)
John McCall48871652010-08-21 09:40:31 +00007062 return 0;
John McCall3969e302009-12-08 07:46:18 +00007063
Richard Smithc2bc61b2013-03-18 21:12:30 +00007064 // Warn about access declarations.
John McCalla0097262009-12-11 02:10:03 +00007065 if (!HasUsingKeyword) {
Enea Zaffanellac70b2512013-07-17 17:28:56 +00007066 Diag(Name.getLocStart(),
Richard Smithf026b602013-06-13 02:12:17 +00007067 getLangOpts().CPlusPlus11 ? diag::err_access_decl
7068 : diag::warn_access_decl_deprecated)
Douglas Gregora771f462010-03-31 17:46:05 +00007069 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCalla0097262009-12-11 02:10:03 +00007070 }
7071
Douglas Gregorc4356532010-12-16 00:46:58 +00007072 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
7073 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
7074 return 0;
7075
John McCall3f746822009-11-17 05:59:44 +00007076 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007077 TargetNameInfo, AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00007078 /* IsInstantiation */ false,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007079 HasTypenameKeyword, TypenameLoc);
John McCallb96ec562009-12-04 22:46:56 +00007080 if (UD)
7081 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00007082
John McCall48871652010-08-21 09:40:31 +00007083 return UD;
Anders Carlsson696a3f12009-08-28 05:40:36 +00007084}
7085
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007086/// \brief Determine whether a using declaration considers the given
7087/// declarations as "equivalent", e.g., if they are redeclarations of
7088/// the same entity or are both typedefs of the same type.
Richard Smithfd8634a2013-10-23 02:17:46 +00007089static bool
7090IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
7091 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007092 return true;
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007093
Richard Smithdda56e42011-04-15 14:24:37 +00007094 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
Richard Smithfd8634a2013-10-23 02:17:46 +00007095 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007096 return Context.hasSameType(TD1->getUnderlyingType(),
7097 TD2->getUnderlyingType());
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007098
7099 return false;
7100}
7101
7102
John McCall84d87672009-12-10 09:41:52 +00007103/// Determines whether to create a using shadow decl for a particular
7104/// decl, given the set of decls existing prior to this using lookup.
7105bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
Richard Smithfd8634a2013-10-23 02:17:46 +00007106 const LookupResult &Previous,
7107 UsingShadowDecl *&PrevShadow) {
John McCall84d87672009-12-10 09:41:52 +00007108 // Diagnose finding a decl which is not from a base class of the
7109 // current class. We do this now because there are cases where this
7110 // function will silently decide not to build a shadow decl, which
7111 // will pre-empt further diagnostics.
7112 //
7113 // We don't need to do this in C++0x because we do the check once on
7114 // the qualifier.
7115 //
7116 // FIXME: diagnose the following if we care enough:
7117 // struct A { int foo; };
7118 // struct B : A { using A::foo; };
7119 // template <class T> struct C : A {};
7120 // template <class T> struct D : C<T> { using B::foo; } // <---
7121 // This is invalid (during instantiation) in C++03 because B::foo
7122 // resolves to the using decl in B, which is not a base class of D<T>.
7123 // We can't diagnose it immediately because C<T> is an unknown
7124 // specialization. The UsingShadowDecl in D<T> then points directly
7125 // to A::foo, which will look well-formed when we instantiate.
7126 // The right solution is to not collapse the shadow-decl chain.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007127 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
John McCall84d87672009-12-10 09:41:52 +00007128 DeclContext *OrigDC = Orig->getDeclContext();
7129
7130 // Handle enums and anonymous structs.
7131 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
7132 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
7133 while (OrigRec->isAnonymousStructOrUnion())
7134 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
7135
7136 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
7137 if (OrigDC == CurContext) {
7138 Diag(Using->getLocation(),
7139 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007140 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00007141 Diag(Orig->getLocation(), diag::note_using_decl_target);
7142 return true;
7143 }
7144
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007145 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall84d87672009-12-10 09:41:52 +00007146 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007147 << Using->getQualifier()
John McCall84d87672009-12-10 09:41:52 +00007148 << cast<CXXRecordDecl>(CurContext)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007149 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00007150 Diag(Orig->getLocation(), diag::note_using_decl_target);
7151 return true;
7152 }
7153 }
7154
7155 if (Previous.empty()) return false;
7156
7157 NamedDecl *Target = Orig;
7158 if (isa<UsingShadowDecl>(Target))
7159 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7160
John McCalla17e83e2009-12-11 02:33:26 +00007161 // If the target happens to be one of the previous declarations, we
7162 // don't have a conflict.
7163 //
7164 // FIXME: but we might be increasing its access, in which case we
7165 // should redeclare it.
7166 NamedDecl *NonTag = 0, *Tag = 0;
Richard Smithfd8634a2013-10-23 02:17:46 +00007167 bool FoundEquivalentDecl = false;
John McCalla17e83e2009-12-11 02:33:26 +00007168 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7169 I != E; ++I) {
7170 NamedDecl *D = (*I)->getUnderlyingDecl();
Richard Smithfd8634a2013-10-23 02:17:46 +00007171 if (IsEquivalentForUsingDecl(Context, D, Target)) {
7172 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
7173 PrevShadow = Shadow;
7174 FoundEquivalentDecl = true;
7175 }
John McCalla17e83e2009-12-11 02:33:26 +00007176
7177 (isa<TagDecl>(D) ? Tag : NonTag) = D;
7178 }
7179
Richard Smithfd8634a2013-10-23 02:17:46 +00007180 if (FoundEquivalentDecl)
7181 return false;
7182
Alp Tokera2794f92014-01-22 07:29:52 +00007183 if (FunctionDecl *FD = Target->getAsFunction()) {
John McCall84d87672009-12-10 09:41:52 +00007184 NamedDecl *OldDecl = 0;
John McCalle9cccd82010-06-16 08:42:20 +00007185 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall84d87672009-12-10 09:41:52 +00007186 case Ovl_Overload:
7187 return false;
7188
7189 case Ovl_NonFunction:
John McCalle29c5cd2009-12-10 19:51:03 +00007190 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007191 break;
Richard Smith18819302014-02-06 01:31:33 +00007192
John McCall84d87672009-12-10 09:41:52 +00007193 // We found a decl with the exact signature.
7194 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00007195 // If we're in a record, we want to hide the target, so we
7196 // return true (without a diagnostic) to tell the caller not to
7197 // build a shadow decl.
7198 if (CurContext->isRecord())
7199 return true;
7200
7201 // If we're not in a record, this is an error.
John McCalle29c5cd2009-12-10 19:51:03 +00007202 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007203 break;
7204 }
7205
7206 Diag(Target->getLocation(), diag::note_using_decl_target);
7207 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
7208 return true;
7209 }
7210
7211 // Target is not a function.
7212
John McCall84d87672009-12-10 09:41:52 +00007213 if (isa<TagDecl>(Target)) {
7214 // No conflict between a tag and a non-tag.
7215 if (!Tag) return false;
7216
John McCalle29c5cd2009-12-10 19:51:03 +00007217 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007218 Diag(Target->getLocation(), diag::note_using_decl_target);
7219 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
7220 return true;
7221 }
7222
7223 // No conflict between a tag and a non-tag.
7224 if (!NonTag) return false;
7225
John McCalle29c5cd2009-12-10 19:51:03 +00007226 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007227 Diag(Target->getLocation(), diag::note_using_decl_target);
7228 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
7229 return true;
7230}
7231
John McCall3f746822009-11-17 05:59:44 +00007232/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall3969e302009-12-08 07:46:18 +00007233UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall3969e302009-12-08 07:46:18 +00007234 UsingDecl *UD,
Richard Smithfd8634a2013-10-23 02:17:46 +00007235 NamedDecl *Orig,
7236 UsingShadowDecl *PrevDecl) {
John McCall3f746822009-11-17 05:59:44 +00007237
7238 // If we resolved to another shadow declaration, just coalesce them.
John McCall3969e302009-12-08 07:46:18 +00007239 NamedDecl *Target = Orig;
7240 if (isa<UsingShadowDecl>(Target)) {
7241 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7242 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall3f746822009-11-17 05:59:44 +00007243 }
Richard Smithfd8634a2013-10-23 02:17:46 +00007244
John McCall3f746822009-11-17 05:59:44 +00007245 UsingShadowDecl *Shadow
John McCall3969e302009-12-08 07:46:18 +00007246 = UsingShadowDecl::Create(Context, CurContext,
7247 UD->getLocation(), UD, Target);
John McCall3f746822009-11-17 05:59:44 +00007248 UD->addShadowDecl(Shadow);
Richard Smithfd8634a2013-10-23 02:17:46 +00007249
Douglas Gregor457104e2010-09-29 04:25:11 +00007250 Shadow->setAccess(UD->getAccess());
7251 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
7252 Shadow->setInvalidDecl();
Richard Smithfd8634a2013-10-23 02:17:46 +00007253
7254 Shadow->setPreviousDecl(PrevDecl);
7255
John McCall3f746822009-11-17 05:59:44 +00007256 if (S)
John McCall3969e302009-12-08 07:46:18 +00007257 PushOnScopeChains(Shadow, S);
John McCall3f746822009-11-17 05:59:44 +00007258 else
John McCall3969e302009-12-08 07:46:18 +00007259 CurContext->addDecl(Shadow);
John McCall3f746822009-11-17 05:59:44 +00007260
John McCall3969e302009-12-08 07:46:18 +00007261
John McCall84d87672009-12-10 09:41:52 +00007262 return Shadow;
7263}
John McCall3969e302009-12-08 07:46:18 +00007264
John McCall84d87672009-12-10 09:41:52 +00007265/// Hides a using shadow declaration. This is required by the current
7266/// using-decl implementation when a resolvable using declaration in a
7267/// class is followed by a declaration which would hide or override
7268/// one or more of the using decl's targets; for example:
7269///
7270/// struct Base { void foo(int); };
7271/// struct Derived : Base {
7272/// using Base::foo;
7273/// void foo(int);
7274/// };
7275///
7276/// The governing language is C++03 [namespace.udecl]p12:
7277///
7278/// When a using-declaration brings names from a base class into a
7279/// derived class scope, member functions in the derived class
7280/// override and/or hide member functions with the same name and
7281/// parameter types in a base class (rather than conflicting).
7282///
7283/// There are two ways to implement this:
7284/// (1) optimistically create shadow decls when they're not hidden
7285/// by existing declarations, or
7286/// (2) don't create any shadow decls (or at least don't make them
7287/// visible) until we've fully parsed/instantiated the class.
7288/// The problem with (1) is that we might have to retroactively remove
7289/// a shadow decl, which requires several O(n) operations because the
7290/// decl structures are (very reasonably) not designed for removal.
7291/// (2) avoids this but is very fiddly and phase-dependent.
7292void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCallda4458e2010-03-31 01:36:47 +00007293 if (Shadow->getDeclName().getNameKind() ==
7294 DeclarationName::CXXConversionFunctionName)
7295 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
7296
John McCall84d87672009-12-10 09:41:52 +00007297 // Remove it from the DeclContext...
7298 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00007299
John McCall84d87672009-12-10 09:41:52 +00007300 // ...and the scope, if applicable...
7301 if (S) {
John McCall48871652010-08-21 09:40:31 +00007302 S->RemoveDecl(Shadow);
John McCall84d87672009-12-10 09:41:52 +00007303 IdResolver.RemoveDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00007304 }
7305
John McCall84d87672009-12-10 09:41:52 +00007306 // ...and the using decl.
7307 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
7308
7309 // TODO: complain somehow if Shadow was used. It shouldn't
John McCallda4458e2010-03-31 01:36:47 +00007310 // be possible for this to happen, because...?
John McCall3f746822009-11-17 05:59:44 +00007311}
7312
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007313namespace {
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007314class UsingValidatorCCC : public CorrectionCandidateCallback {
7315public:
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +00007316 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
7317 bool RequireMember)
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007318 : HasTypenameKeyword(HasTypenameKeyword),
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +00007319 IsInstantiation(IsInstantiation), RequireMember(RequireMember) {}
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007320
Craig Toppera798a9d2014-03-02 09:32:10 +00007321 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007322 NamedDecl *ND = Candidate.getCorrectionDecl();
7323
7324 // Keywords are not valid here.
7325 if (!ND || isa<NamespaceDecl>(ND))
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007326 return false;
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007327
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +00007328 if (RequireMember && !isa<FieldDecl>(ND) && !isa<CXXMethodDecl>(ND) &&
7329 !isa<TypeDecl>(ND))
7330 return false;
7331
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007332 // Completely unqualified names are invalid for a 'using' declaration.
7333 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
7334 return false;
7335
7336 if (isa<TypeDecl>(ND))
7337 return HasTypenameKeyword || !IsInstantiation;
7338
7339 return !HasTypenameKeyword;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007340 }
7341
7342private:
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007343 bool HasTypenameKeyword;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007344 bool IsInstantiation;
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +00007345 bool RequireMember;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007346};
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007347} // end anonymous namespace
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007348
John McCalle61f2ba2009-11-18 02:36:19 +00007349/// Builds a using declaration.
7350///
7351/// \param IsInstantiation - Whether this call arises from an
7352/// instantiation of an unresolved using declaration. We treat
7353/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00007354NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
7355 SourceLocation UsingLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00007356 CXXScopeSpec &SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007357 const DeclarationNameInfo &NameInfo,
Anders Carlsson696a3f12009-08-28 05:40:36 +00007358 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00007359 bool IsInstantiation,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007360 bool HasTypenameKeyword,
John McCalle61f2ba2009-11-18 02:36:19 +00007361 SourceLocation TypenameLoc) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00007362 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007363 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlsson696a3f12009-08-28 05:40:36 +00007364 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00007365
Anders Carlssonf038fc22009-08-28 05:49:21 +00007366 // FIXME: We ignore attributes for now.
Mike Stump11289f42009-09-09 15:08:12 +00007367
Anders Carlsson59140b32009-08-28 03:16:11 +00007368 if (SS.isEmpty()) {
7369 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlsson696a3f12009-08-28 05:40:36 +00007370 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00007371 }
Mike Stump11289f42009-09-09 15:08:12 +00007372
John McCall84d87672009-12-10 09:41:52 +00007373 // Do the redeclaration lookup in the current scope.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007374 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall84d87672009-12-10 09:41:52 +00007375 ForRedeclaration);
7376 Previous.setHideTags(false);
7377 if (S) {
7378 LookupName(Previous, S);
7379
7380 // It is really dumb that we have to do this.
7381 LookupResult::Filter F = Previous.makeFilter();
7382 while (F.hasNext()) {
7383 NamedDecl *D = F.next();
7384 if (!isDeclInScope(D, CurContext, S))
7385 F.erase();
7386 }
7387 F.done();
7388 } else {
7389 assert(IsInstantiation && "no scope in non-instantiation");
7390 assert(CurContext->isRecord() && "scope not record in instantiation");
7391 LookupQualifiedName(Previous, CurContext);
7392 }
7393
John McCall84d87672009-12-10 09:41:52 +00007394 // Check for invalid redeclarations.
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007395 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
7396 SS, IdentLoc, Previous))
John McCall84d87672009-12-10 09:41:52 +00007397 return 0;
7398
7399 // Check for bad qualifiers.
John McCallb96ec562009-12-04 22:46:56 +00007400 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
7401 return 0;
7402
John McCall84c16cf2009-11-12 03:15:40 +00007403 DeclContext *LookupContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00007404 NamedDecl *D;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007405 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall84c16cf2009-11-12 03:15:40 +00007406 if (!LookupContext) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007407 if (HasTypenameKeyword) {
John McCallb96ec562009-12-04 22:46:56 +00007408 // FIXME: not all declaration name kinds are legal here
7409 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
7410 UsingLoc, TypenameLoc,
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007411 QualifierLoc,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007412 IdentLoc, NameInfo.getName());
John McCallb96ec562009-12-04 22:46:56 +00007413 } else {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007414 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
7415 QualifierLoc, NameInfo);
John McCalle61f2ba2009-11-18 02:36:19 +00007416 }
John McCallb96ec562009-12-04 22:46:56 +00007417 } else {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007418 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007419 NameInfo, HasTypenameKeyword);
Anders Carlssonf038fc22009-08-28 05:49:21 +00007420 }
John McCallb96ec562009-12-04 22:46:56 +00007421 D->setAccess(AS);
7422 CurContext->addDecl(D);
7423
7424 if (!LookupContext) return D;
7425 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump11289f42009-09-09 15:08:12 +00007426
John McCall0b66eb32010-05-01 00:40:08 +00007427 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall3969e302009-12-08 07:46:18 +00007428 UD->setInvalidDecl();
7429 return UD;
Anders Carlsson59140b32009-08-28 03:16:11 +00007430 }
7431
Richard Smith23d55872012-04-02 01:30:27 +00007432 // The normal rules do not apply to inheriting constructor declarations.
Sebastian Redl08905022011-02-05 19:23:19 +00007433 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Richard Smith23d55872012-04-02 01:30:27 +00007434 if (CheckInheritingConstructorUsingDecl(UD))
Sebastian Redlc1f8e492011-03-12 13:44:32 +00007435 UD->setInvalidDecl();
Sebastian Redl08905022011-02-05 19:23:19 +00007436 return UD;
7437 }
7438
7439 // Otherwise, look up the target name.
John McCall3969e302009-12-08 07:46:18 +00007440
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007441 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle61f2ba2009-11-18 02:36:19 +00007442
John McCall3969e302009-12-08 07:46:18 +00007443 // Unlike most lookups, we don't always want to hide tag
7444 // declarations: tag names are visible through the using declaration
7445 // even if hidden by ordinary names, *except* in a dependent context
7446 // where it's important for the sanity of two-phase lookup.
John McCalle61f2ba2009-11-18 02:36:19 +00007447 if (!IsInstantiation)
7448 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00007449
John McCall5dadb652012-04-07 03:04:20 +00007450 // For the purposes of this lookup, we have a base object type
7451 // equal to that of the current context.
7452 if (CurContext->isRecord()) {
7453 R.setBaseObjectType(
7454 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
7455 }
7456
John McCall27b18f82009-11-17 02:14:36 +00007457 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00007458
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007459 // Try to correct typos if possible.
John McCall9f3059a2009-10-09 21:13:30 +00007460 if (R.empty()) {
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +00007461 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation,
7462 CurContext->isRecord());
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007463 if (TypoCorrection Corrected = CorrectTypo(R.getLookupNameInfo(),
7464 R.getLookupKind(), S, &SS, CCC)){
7465 // We reject any correction for which ND would be NULL.
7466 NamedDecl *ND = Corrected.getCorrectionDecl();
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007467 R.setLookupName(Corrected.getCorrection());
7468 R.addDecl(ND);
Richard Smithf9b15102013-08-17 00:46:16 +00007469 // We reject candidates where DroppedSpecifier == true, hence the
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007470 // literal '0' below.
Richard Smithf9b15102013-08-17 00:46:16 +00007471 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
7472 << NameInfo.getName() << LookupContext << 0
7473 << SS.getRange());
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007474 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00007475 Diag(IdentLoc, diag::err_no_member)
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007476 << NameInfo.getName() << LookupContext << SS.getRange();
7477 UD->setInvalidDecl();
7478 return UD;
7479 }
Douglas Gregorfec52632009-06-20 00:51:54 +00007480 }
7481
John McCallb96ec562009-12-04 22:46:56 +00007482 if (R.isAmbiguous()) {
7483 UD->setInvalidDecl();
7484 return UD;
7485 }
Mike Stump11289f42009-09-09 15:08:12 +00007486
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007487 if (HasTypenameKeyword) {
John McCalle61f2ba2009-11-18 02:36:19 +00007488 // If we asked for a typename and got a non-type decl, error out.
John McCallb96ec562009-12-04 22:46:56 +00007489 if (!R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00007490 Diag(IdentLoc, diag::err_using_typename_non_type);
7491 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
7492 Diag((*I)->getUnderlyingDecl()->getLocation(),
7493 diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00007494 UD->setInvalidDecl();
7495 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00007496 }
7497 } else {
7498 // If we asked for a non-typename and we got a type, error out,
7499 // but only if this is an instantiation of an unresolved using
7500 // decl. Otherwise just silently find the type name.
John McCallb96ec562009-12-04 22:46:56 +00007501 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00007502 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
7503 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00007504 UD->setInvalidDecl();
7505 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00007506 }
Anders Carlsson59140b32009-08-28 03:16:11 +00007507 }
7508
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00007509 // C++0x N2914 [namespace.udecl]p6:
7510 // A using-declaration shall not name a namespace.
John McCallb96ec562009-12-04 22:46:56 +00007511 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00007512 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
7513 << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00007514 UD->setInvalidDecl();
7515 return UD;
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00007516 }
Mike Stump11289f42009-09-09 15:08:12 +00007517
John McCall84d87672009-12-10 09:41:52 +00007518 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
Richard Smithfd8634a2013-10-23 02:17:46 +00007519 UsingShadowDecl *PrevDecl = 0;
7520 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
7521 BuildUsingShadowDecl(S, UD, *I, PrevDecl);
John McCall84d87672009-12-10 09:41:52 +00007522 }
John McCall3f746822009-11-17 05:59:44 +00007523
7524 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00007525}
7526
Sebastian Redl08905022011-02-05 19:23:19 +00007527/// Additional checks for a using declaration referring to a constructor name.
Richard Smith23d55872012-04-02 01:30:27 +00007528bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007529 assert(!UD->hasTypename() && "expecting a constructor name");
Sebastian Redl08905022011-02-05 19:23:19 +00007530
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007531 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redl08905022011-02-05 19:23:19 +00007532 assert(SourceType &&
7533 "Using decl naming constructor doesn't have type in scope spec.");
7534 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
7535
7536 // Check whether the named type is a direct base class.
7537 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
7538 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
7539 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
7540 BaseIt != BaseE; ++BaseIt) {
7541 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
7542 if (CanonicalSourceType == BaseType)
7543 break;
Richard Smith23d55872012-04-02 01:30:27 +00007544 if (BaseIt->getType()->isDependentType())
7545 break;
Sebastian Redl08905022011-02-05 19:23:19 +00007546 }
7547
7548 if (BaseIt == BaseE) {
7549 // Did not find SourceType in the bases.
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007550 Diag(UD->getUsingLoc(),
Sebastian Redl08905022011-02-05 19:23:19 +00007551 diag::err_using_decl_constructor_not_in_direct_base)
7552 << UD->getNameInfo().getSourceRange()
7553 << QualType(SourceType, 0) << TargetClass;
7554 return true;
7555 }
7556
Richard Smith23d55872012-04-02 01:30:27 +00007557 if (!CurContext->isDependentContext())
7558 BaseIt->setInheritConstructors();
Sebastian Redl08905022011-02-05 19:23:19 +00007559
7560 return false;
7561}
7562
John McCall84d87672009-12-10 09:41:52 +00007563/// Checks that the given using declaration is not an invalid
7564/// redeclaration. Note that this is checking only for the using decl
7565/// itself, not for any ill-formedness among the UsingShadowDecls.
7566bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007567 bool HasTypenameKeyword,
John McCall84d87672009-12-10 09:41:52 +00007568 const CXXScopeSpec &SS,
7569 SourceLocation NameLoc,
7570 const LookupResult &Prev) {
7571 // C++03 [namespace.udecl]p8:
7572 // C++0x [namespace.udecl]p10:
7573 // A using-declaration is a declaration and can therefore be used
7574 // repeatedly where (and only where) multiple declarations are
7575 // allowed.
Douglas Gregor4b718ee2010-05-06 23:31:27 +00007576 //
John McCall032092f2010-11-29 18:01:58 +00007577 // That's in non-member contexts.
7578 if (!CurContext->getRedeclContext()->isRecord())
John McCall84d87672009-12-10 09:41:52 +00007579 return false;
7580
Aaron Ballman4a979672014-01-03 13:56:08 +00007581 NestedNameSpecifier *Qual = SS.getScopeRep();
John McCall84d87672009-12-10 09:41:52 +00007582
7583 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
7584 NamedDecl *D = *I;
7585
7586 bool DTypename;
7587 NestedNameSpecifier *DQual;
7588 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007589 DTypename = UD->hasTypename();
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007590 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00007591 } else if (UnresolvedUsingValueDecl *UD
7592 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
7593 DTypename = false;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007594 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00007595 } else if (UnresolvedUsingTypenameDecl *UD
7596 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
7597 DTypename = true;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007598 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00007599 } else continue;
7600
7601 // using decls differ if one says 'typename' and the other doesn't.
7602 // FIXME: non-dependent using decls?
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007603 if (HasTypenameKeyword != DTypename) continue;
John McCall84d87672009-12-10 09:41:52 +00007604
7605 // using decls differ if they name different scopes (but note that
7606 // template instantiation can cause this check to trigger when it
7607 // didn't before instantiation).
7608 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
7609 Context.getCanonicalNestedNameSpecifier(DQual))
7610 continue;
7611
7612 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCalle29c5cd2009-12-10 19:51:03 +00007613 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall84d87672009-12-10 09:41:52 +00007614 return true;
7615 }
7616
7617 return false;
7618}
7619
John McCall3969e302009-12-08 07:46:18 +00007620
John McCallb96ec562009-12-04 22:46:56 +00007621/// Checks that the given nested-name qualifier used in a using decl
7622/// in the current context is appropriately related to the current
7623/// scope. If an error is found, diagnoses it and returns true.
7624bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
7625 const CXXScopeSpec &SS,
7626 SourceLocation NameLoc) {
John McCall3969e302009-12-08 07:46:18 +00007627 DeclContext *NamedContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00007628
John McCall3969e302009-12-08 07:46:18 +00007629 if (!CurContext->isRecord()) {
7630 // C++03 [namespace.udecl]p3:
7631 // C++0x [namespace.udecl]p8:
7632 // A using-declaration for a class member shall be a member-declaration.
7633
7634 // If we weren't able to compute a valid scope, it must be a
7635 // dependent class scope.
7636 if (!NamedContext || NamedContext->isRecord()) {
7637 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
7638 << SS.getRange();
7639 return true;
7640 }
7641
7642 // Otherwise, everything is known to be fine.
7643 return false;
7644 }
7645
7646 // The current scope is a record.
7647
7648 // If the named context is dependent, we can't decide much.
7649 if (!NamedContext) {
7650 // FIXME: in C++0x, we can diagnose if we can prove that the
7651 // nested-name-specifier does not refer to a base class, which is
7652 // still possible in some cases.
7653
7654 // Otherwise we have to conservatively report that things might be
7655 // okay.
7656 return false;
7657 }
7658
7659 if (!NamedContext->isRecord()) {
7660 // Ideally this would point at the last name in the specifier,
7661 // but we don't have that level of source info.
7662 Diag(SS.getRange().getBegin(),
7663 diag::err_using_decl_nested_name_specifier_is_not_class)
Aaron Ballman5fe6c802014-01-03 13:45:46 +00007664 << SS.getScopeRep() << SS.getRange();
John McCall3969e302009-12-08 07:46:18 +00007665 return true;
7666 }
7667
Douglas Gregor7c842292010-12-21 07:41:49 +00007668 if (!NamedContext->isDependentContext() &&
7669 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
7670 return true;
7671
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007672 if (getLangOpts().CPlusPlus11) {
John McCall3969e302009-12-08 07:46:18 +00007673 // C++0x [namespace.udecl]p3:
7674 // In a using-declaration used as a member-declaration, the
7675 // nested-name-specifier shall name a base class of the class
7676 // being defined.
7677
7678 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
7679 cast<CXXRecordDecl>(NamedContext))) {
7680 if (CurContext == NamedContext) {
7681 Diag(NameLoc,
7682 diag::err_using_decl_nested_name_specifier_is_current_class)
7683 << SS.getRange();
7684 return true;
7685 }
7686
7687 Diag(SS.getRange().getBegin(),
7688 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Aaron Ballman4a979672014-01-03 13:56:08 +00007689 << SS.getScopeRep()
John McCall3969e302009-12-08 07:46:18 +00007690 << cast<CXXRecordDecl>(CurContext)
7691 << SS.getRange();
7692 return true;
7693 }
7694
7695 return false;
7696 }
7697
7698 // C++03 [namespace.udecl]p4:
7699 // A using-declaration used as a member-declaration shall refer
7700 // to a member of a base class of the class being defined [etc.].
7701
7702 // Salient point: SS doesn't have to name a base class as long as
7703 // lookup only finds members from base classes. Therefore we can
7704 // diagnose here only if we can prove that that can't happen,
7705 // i.e. if the class hierarchies provably don't intersect.
7706
7707 // TODO: it would be nice if "definitely valid" results were cached
7708 // in the UsingDecl and UsingShadowDecl so that these checks didn't
7709 // need to be repeated.
7710
7711 struct UserData {
Benjamin Kramer3adbe1c2012-02-23 16:06:01 +00007712 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
John McCall3969e302009-12-08 07:46:18 +00007713
7714 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
7715 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7716 Data->Bases.insert(Base);
7717 return true;
7718 }
7719
7720 bool hasDependentBases(const CXXRecordDecl *Class) {
7721 return !Class->forallBases(collect, this);
7722 }
7723
7724 /// Returns true if the base is dependent or is one of the
7725 /// accumulated base classes.
7726 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
7727 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7728 return !Data->Bases.count(Base);
7729 }
7730
7731 bool mightShareBases(const CXXRecordDecl *Class) {
7732 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
7733 }
7734 };
7735
7736 UserData Data;
7737
7738 // Returns false if we find a dependent base.
7739 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
7740 return false;
7741
7742 // Returns false if the class has a dependent base or if it or one
7743 // of its bases is present in the base set of the current context.
7744 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
7745 return false;
7746
7747 Diag(SS.getRange().getBegin(),
7748 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Aaron Ballman4a979672014-01-03 13:56:08 +00007749 << SS.getScopeRep()
John McCall3969e302009-12-08 07:46:18 +00007750 << cast<CXXRecordDecl>(CurContext)
7751 << SS.getRange();
7752
7753 return true;
John McCallb96ec562009-12-04 22:46:56 +00007754}
7755
Richard Smithdda56e42011-04-15 14:24:37 +00007756Decl *Sema::ActOnAliasDeclaration(Scope *S,
7757 AccessSpecifier AS,
Richard Smith3f1b5d02011-05-05 21:57:07 +00007758 MultiTemplateParamsArg TemplateParamLists,
Richard Smithdda56e42011-04-15 14:24:37 +00007759 SourceLocation UsingLoc,
7760 UnqualifiedId &Name,
Richard Smith54ecd982013-02-20 19:22:51 +00007761 AttributeList *AttrList,
Richard Smithdda56e42011-04-15 14:24:37 +00007762 TypeResult Type) {
Richard Smith3f1b5d02011-05-05 21:57:07 +00007763 // Skip up to the relevant declaration scope.
7764 while (S->getFlags() & Scope::TemplateParamScope)
7765 S = S->getParent();
Richard Smithdda56e42011-04-15 14:24:37 +00007766 assert((S->getFlags() & Scope::DeclScope) &&
7767 "got alias-declaration outside of declaration scope");
7768
7769 if (Type.isInvalid())
7770 return 0;
7771
7772 bool Invalid = false;
7773 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
7774 TypeSourceInfo *TInfo = 0;
Nick Lewycky82e47802011-05-02 01:07:19 +00007775 GetTypeFromParser(Type.get(), &TInfo);
Richard Smithdda56e42011-04-15 14:24:37 +00007776
7777 if (DiagnoseClassNameShadow(CurContext, NameInfo))
7778 return 0;
7779
7780 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3f1b5d02011-05-05 21:57:07 +00007781 UPPC_DeclarationType)) {
Richard Smithdda56e42011-04-15 14:24:37 +00007782 Invalid = true;
Richard Smith3f1b5d02011-05-05 21:57:07 +00007783 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
7784 TInfo->getTypeLoc().getBeginLoc());
7785 }
Richard Smithdda56e42011-04-15 14:24:37 +00007786
7787 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
7788 LookupName(Previous, S);
7789
7790 // Warn about shadowing the name of a template parameter.
7791 if (Previous.isSingleResult() &&
7792 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorf4ef4d22011-10-20 17:58:49 +00007793 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smithdda56e42011-04-15 14:24:37 +00007794 Previous.clear();
7795 }
7796
7797 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
7798 "name in alias declaration must be an identifier");
7799 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
7800 Name.StartLocation,
7801 Name.Identifier, TInfo);
7802
7803 NewTD->setAccess(AS);
7804
7805 if (Invalid)
7806 NewTD->setInvalidDecl();
7807
Richard Smith54ecd982013-02-20 19:22:51 +00007808 ProcessDeclAttributeList(S, NewTD, AttrList);
7809
Richard Smith3f1b5d02011-05-05 21:57:07 +00007810 CheckTypedefForVariablyModifiedType(S, NewTD);
7811 Invalid |= NewTD->isInvalidDecl();
7812
Richard Smithdda56e42011-04-15 14:24:37 +00007813 bool Redeclaration = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00007814
7815 NamedDecl *NewND;
7816 if (TemplateParamLists.size()) {
7817 TypeAliasTemplateDecl *OldDecl = 0;
7818 TemplateParameterList *OldTemplateParams = 0;
7819
7820 if (TemplateParamLists.size() != 1) {
7821 Diag(UsingLoc, diag::err_alias_template_extra_headers)
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007822 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
7823 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
Richard Smith3f1b5d02011-05-05 21:57:07 +00007824 }
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007825 TemplateParameterList *TemplateParams = TemplateParamLists[0];
Richard Smith3f1b5d02011-05-05 21:57:07 +00007826
7827 // Only consider previous declarations in the same scope.
7828 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
7829 /*ExplicitInstantiationOrSpecialization*/false);
7830 if (!Previous.empty()) {
7831 Redeclaration = true;
7832
7833 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
7834 if (!OldDecl && !Invalid) {
7835 Diag(UsingLoc, diag::err_redefinition_different_kind)
7836 << Name.Identifier;
7837
7838 NamedDecl *OldD = Previous.getRepresentativeDecl();
7839 if (OldD->getLocation().isValid())
7840 Diag(OldD->getLocation(), diag::note_previous_definition);
7841
7842 Invalid = true;
7843 }
7844
7845 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
7846 if (TemplateParameterListsAreEqual(TemplateParams,
7847 OldDecl->getTemplateParameters(),
7848 /*Complain=*/true,
7849 TPL_TemplateMatch))
7850 OldTemplateParams = OldDecl->getTemplateParameters();
7851 else
7852 Invalid = true;
7853
7854 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
7855 if (!Invalid &&
7856 !Context.hasSameType(OldTD->getUnderlyingType(),
7857 NewTD->getUnderlyingType())) {
7858 // FIXME: The C++0x standard does not clearly say this is ill-formed,
7859 // but we can't reasonably accept it.
7860 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
7861 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
7862 if (OldTD->getLocation().isValid())
7863 Diag(OldTD->getLocation(), diag::note_previous_definition);
7864 Invalid = true;
7865 }
7866 }
7867 }
7868
7869 // Merge any previous default template arguments into our parameters,
7870 // and check the parameter list.
7871 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
7872 TPC_TypeAliasTemplate))
7873 return 0;
7874
7875 TypeAliasTemplateDecl *NewDecl =
7876 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
7877 Name.Identifier, TemplateParams,
7878 NewTD);
7879
7880 NewDecl->setAccess(AS);
7881
7882 if (Invalid)
7883 NewDecl->setInvalidDecl();
7884 else if (OldDecl)
Rafael Espindola8db352d2013-10-17 15:37:26 +00007885 NewDecl->setPreviousDecl(OldDecl);
Richard Smith3f1b5d02011-05-05 21:57:07 +00007886
7887 NewND = NewDecl;
7888 } else {
7889 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
7890 NewND = NewTD;
7891 }
Richard Smithdda56e42011-04-15 14:24:37 +00007892
7893 if (!Redeclaration)
Richard Smith3f1b5d02011-05-05 21:57:07 +00007894 PushOnScopeChains(NewND, S);
Richard Smithdda56e42011-04-15 14:24:37 +00007895
Dmitri Gribenko7f4b3772012-08-02 20:49:51 +00007896 ActOnDocumentableDecl(NewND);
Richard Smith3f1b5d02011-05-05 21:57:07 +00007897 return NewND;
Richard Smithdda56e42011-04-15 14:24:37 +00007898}
7899
John McCall48871652010-08-21 09:40:31 +00007900Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson47952ae2009-03-28 22:53:22 +00007901 SourceLocation NamespaceLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00007902 SourceLocation AliasLoc,
7903 IdentifierInfo *Alias,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00007904 CXXScopeSpec &SS,
Anders Carlsson47952ae2009-03-28 22:53:22 +00007905 SourceLocation IdentLoc,
7906 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00007907
Anders Carlssonbb1e4722009-03-28 23:53:49 +00007908 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00007909 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
7910 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00007911
Anders Carlssondca83c42009-03-28 06:23:46 +00007912 // Check if we have a previous declaration with the same name.
Douglas Gregor5cf8d672010-05-03 15:37:31 +00007913 NamedDecl *PrevDecl
7914 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
7915 ForRedeclaration);
7916 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
7917 PrevDecl = 0;
7918
7919 if (PrevDecl) {
Anders Carlssonbb1e4722009-03-28 23:53:49 +00007920 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump11289f42009-09-09 15:08:12 +00007921 // We already have an alias with the same name that points to the same
Anders Carlssonbb1e4722009-03-28 23:53:49 +00007922 // namespace, so don't create a new one.
Douglas Gregor4667eff2010-03-26 22:59:39 +00007923 // FIXME: At some point, we'll want to create the (redundant)
7924 // declaration to maintain better source information.
John McCall9f3059a2009-10-09 21:13:30 +00007925 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregor4667eff2010-03-26 22:59:39 +00007926 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCall48871652010-08-21 09:40:31 +00007927 return 0;
Anders Carlssonbb1e4722009-03-28 23:53:49 +00007928 }
Mike Stump11289f42009-09-09 15:08:12 +00007929
Anders Carlssondca83c42009-03-28 06:23:46 +00007930 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
7931 diag::err_redefinition_different_kind;
7932 Diag(AliasLoc, DiagID) << Alias;
7933 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCall48871652010-08-21 09:40:31 +00007934 return 0;
Anders Carlssondca83c42009-03-28 06:23:46 +00007935 }
7936
John McCall27b18f82009-11-17 02:14:36 +00007937 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00007938 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00007939
John McCall9f3059a2009-10-09 21:13:30 +00007940 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00007941 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smitha9746882012-04-05 23:13:23 +00007942 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00007943 return 0;
Douglas Gregor9629e9a2010-06-29 18:55:19 +00007944 }
Anders Carlssonac2c9652009-03-28 06:42:02 +00007945 }
Mike Stump11289f42009-09-09 15:08:12 +00007946
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00007947 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00007948 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregorc05ba2e2011-02-25 17:08:07 +00007949 Alias, SS.getWithLocInContext(Context),
John McCall9f3059a2009-10-09 21:13:30 +00007950 IdentLoc, R.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00007951
John McCalld8d0d432010-02-16 06:53:13 +00007952 PushOnScopeChains(AliasDecl, S);
John McCall48871652010-08-21 09:40:31 +00007953 return AliasDecl;
Anders Carlsson9205d552009-03-28 05:27:17 +00007954}
7955
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00007956Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +00007957Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
7958 CXXMethodDecl *MD) {
7959 CXXRecordDecl *ClassDecl = MD->getParent();
7960
Douglas Gregor6d880b12010-07-01 22:31:05 +00007961 // C++ [except.spec]p14:
7962 // An implicitly declared special member function (Clause 12) shall have an
7963 // exception-specification. [...]
Richard Smithf623c962012-04-17 00:58:00 +00007964 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00007965 if (ClassDecl->isInvalidDecl())
7966 return ExceptSpec;
Douglas Gregor6d880b12010-07-01 22:31:05 +00007967
Sebastian Redlfa453cf2011-03-12 11:50:43 +00007968 // Direct base-class constructors.
Aaron Ballman574705e2014-03-13 15:41:46 +00007969 for (const auto &B : ClassDecl->bases()) {
7970 if (B.isVirtual()) // Handled below.
Douglas Gregor6d880b12010-07-01 22:31:05 +00007971 continue;
7972
Aaron Ballman574705e2014-03-13 15:41:46 +00007973 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Douglas Gregor9672f922010-07-03 00:47:00 +00007974 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00007975 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7976 // If this is a deleted function, add it anyway. This might be conformant
7977 // with the standard. This might not. I'm not sure. It might not matter.
7978 if (Constructor)
Aaron Ballman574705e2014-03-13 15:41:46 +00007979 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00007980 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00007981 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00007982
7983 // Virtual base-class constructors.
Aaron Ballman445a9392014-03-13 16:15:17 +00007984 for (const auto &B : ClassDecl->vbases()) {
7985 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Douglas Gregor9672f922010-07-03 00:47:00 +00007986 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00007987 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7988 // If this is a deleted function, add it anyway. This might be conformant
7989 // with the standard. This might not. I'm not sure. It might not matter.
7990 if (Constructor)
Aaron Ballman445a9392014-03-13 16:15:17 +00007991 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00007992 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00007993 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00007994
7995 // Field constructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007996 for (const auto *F : ClassDecl->fields()) {
Richard Smith938f40b2011-06-11 17:19:42 +00007997 if (F->hasInClassInitializer()) {
7998 if (Expr *E = F->getInClassInitializer())
7999 ExceptSpec.CalledExpr(E);
8000 else if (!F->isInvalidDecl())
Richard Smithd3b5c9082012-07-27 04:22:15 +00008001 // DR1351:
8002 // If the brace-or-equal-initializer of a non-static data member
8003 // invokes a defaulted default constructor of its class or of an
8004 // enclosing class in a potentially evaluated subexpression, the
8005 // program is ill-formed.
8006 //
8007 // This resolution is unworkable: the exception specification of the
8008 // default constructor can be needed in an unevaluated context, in
8009 // particular, in the operand of a noexcept-expression, and we can be
8010 // unable to compute an exception specification for an enclosed class.
8011 //
8012 // We do not allow an in-class initializer to require the evaluation
8013 // of the exception specification for any in-class initializer whose
8014 // definition is not lexically complete.
8015 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
Richard Smith938f40b2011-06-11 17:19:42 +00008016 } else if (const RecordType *RecordTy
Douglas Gregor9672f922010-07-03 00:47:00 +00008017 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00008018 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8019 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8020 // If this is a deleted function, add it anyway. This might be conformant
8021 // with the standard. This might not. I'm not sure. It might not matter.
8022 // In particular, the problem is that this function never gets called. It
8023 // might just be ill-formed because this function attempts to refer to
8024 // a deleted function here.
8025 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +00008026 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00008027 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00008028 }
John McCalldb40c7f2010-12-14 08:05:40 +00008029
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008030 return ExceptSpec;
8031}
8032
Richard Smithc2bc61b2013-03-18 21:12:30 +00008033Sema::ImplicitExceptionSpecification
Richard Smithb7151b92013-04-10 06:11:48 +00008034Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
8035 CXXRecordDecl *ClassDecl = CD->getParent();
8036
8037 // C++ [except.spec]p14:
8038 // An inheriting constructor [...] shall have an exception-specification. [...]
Richard Smithc2bc61b2013-03-18 21:12:30 +00008039 ImplicitExceptionSpecification ExceptSpec(*this);
Richard Smithb7151b92013-04-10 06:11:48 +00008040 if (ClassDecl->isInvalidDecl())
8041 return ExceptSpec;
8042
8043 // Inherited constructor.
8044 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
8045 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
8046 // FIXME: Copying or moving the parameters could add extra exceptions to the
8047 // set, as could the default arguments for the inherited constructor. This
8048 // will be addressed when we implement the resolution of core issue 1351.
8049 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
8050
8051 // Direct base-class constructors.
Aaron Ballman574705e2014-03-13 15:41:46 +00008052 for (const auto &B : ClassDecl->bases()) {
8053 if (B.isVirtual()) // Handled below.
Richard Smithb7151b92013-04-10 06:11:48 +00008054 continue;
8055
Aaron Ballman574705e2014-03-13 15:41:46 +00008056 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Richard Smithb7151b92013-04-10 06:11:48 +00008057 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8058 if (BaseClassDecl == InheritedDecl)
8059 continue;
8060 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8061 if (Constructor)
Aaron Ballman574705e2014-03-13 15:41:46 +00008062 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Richard Smithb7151b92013-04-10 06:11:48 +00008063 }
8064 }
8065
8066 // Virtual base-class constructors.
Aaron Ballman445a9392014-03-13 16:15:17 +00008067 for (const auto &B : ClassDecl->vbases()) {
8068 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Richard Smithb7151b92013-04-10 06:11:48 +00008069 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8070 if (BaseClassDecl == InheritedDecl)
8071 continue;
8072 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8073 if (Constructor)
Aaron Ballman445a9392014-03-13 16:15:17 +00008074 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Richard Smithb7151b92013-04-10 06:11:48 +00008075 }
8076 }
8077
8078 // Field constructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008079 for (const auto *F : ClassDecl->fields()) {
Richard Smithb7151b92013-04-10 06:11:48 +00008080 if (F->hasInClassInitializer()) {
8081 if (Expr *E = F->getInClassInitializer())
8082 ExceptSpec.CalledExpr(E);
8083 else if (!F->isInvalidDecl())
8084 Diag(CD->getLocation(),
8085 diag::err_in_class_initializer_references_def_ctor) << CD;
8086 } else if (const RecordType *RecordTy
8087 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8088 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8089 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8090 if (Constructor)
8091 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
8092 }
8093 }
8094
Richard Smithc2bc61b2013-03-18 21:12:30 +00008095 return ExceptSpec;
8096}
8097
Richard Smith8bf22e52012-11-29 01:34:07 +00008098namespace {
8099/// RAII object to register a special member as being currently declared.
8100struct DeclaringSpecialMember {
8101 Sema &S;
8102 Sema::SpecialMemberDecl D;
8103 bool WasAlreadyBeingDeclared;
8104
8105 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
8106 : S(S), D(RD, CSM) {
8107 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D);
8108 if (WasAlreadyBeingDeclared)
8109 // This almost never happens, but if it does, ensure that our cache
8110 // doesn't contain a stale result.
8111 S.SpecialMemberCache.clear();
8112
8113 // FIXME: Register a note to be produced if we encounter an error while
8114 // declaring the special member.
8115 }
8116 ~DeclaringSpecialMember() {
8117 if (!WasAlreadyBeingDeclared)
8118 S.SpecialMembersBeingDeclared.erase(D);
8119 }
8120
8121 /// \brief Are we already trying to declare this special member?
8122 bool isAlreadyBeingDeclared() const {
8123 return WasAlreadyBeingDeclared;
8124 }
8125};
8126}
8127
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008128CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
8129 CXXRecordDecl *ClassDecl) {
8130 // C++ [class.ctor]p5:
8131 // A default constructor for a class X is a constructor of class X
8132 // that can be called without an argument. If there is no
8133 // user-declared constructor for class X, a default constructor is
8134 // implicitly declared. An implicitly-declared default constructor
8135 // is an inline public member of its class.
Richard Smith7d125a12012-11-27 21:20:31 +00008136 assert(ClassDecl->needsImplicitDefaultConstructor() &&
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008137 "Should not build implicit default constructor!");
8138
Richard Smith8bf22e52012-11-29 01:34:07 +00008139 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
8140 if (DSM.isAlreadyBeingDeclared())
8141 return 0;
8142
Richard Smithb5800092012-06-10 05:43:50 +00008143 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8144 CXXDefaultConstructor,
8145 false);
8146
Douglas Gregor6d880b12010-07-01 22:31:05 +00008147 // Create the actual constructor declaration.
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008148 CanQualType ClassType
8149 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00008150 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008151 DeclarationName Name
8152 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00008153 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smithcc36f692011-12-22 02:22:31 +00008154 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
Richard Smithd3b5c9082012-07-27 04:22:15 +00008155 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0,
Richard Smithcc36f692011-12-22 02:22:31 +00008156 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smithb5800092012-06-10 05:43:50 +00008157 Constexpr);
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008158 DefaultCon->setAccess(AS_public);
Alexis Huntf92197c2011-05-12 03:51:51 +00008159 DefaultCon->setDefaulted();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008160 DefaultCon->setImplicit();
Richard Smithd3b5c9082012-07-27 04:22:15 +00008161
8162 // Build an exception specification pointing back at this constructor.
Reid Kleckner78af0702013-08-27 23:08:25 +00008163 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00008164 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00008165
Richard Smith6b02d462012-12-08 08:32:28 +00008166 // We don't need to use SpecialMemberIsTrivial here; triviality for default
8167 // constructors is easy to compute.
8168 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
8169
8170 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Richard Smithb4d2a152013-04-02 19:38:47 +00008171 SetDeclDeleted(DefaultCon, ClassLoc);
Richard Smith6b02d462012-12-08 08:32:28 +00008172
Douglas Gregor9672f922010-07-03 00:47:00 +00008173 // Note that we have declared this constructor.
Douglas Gregor9672f922010-07-03 00:47:00 +00008174 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
Richard Smith6b02d462012-12-08 08:32:28 +00008175
Douglas Gregor0be31a22010-07-02 17:43:08 +00008176 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor9672f922010-07-03 00:47:00 +00008177 PushOnScopeChains(DefaultCon, S, false);
8178 ClassDecl->addDecl(DefaultCon);
Alexis Hunte77a28f2011-05-18 03:41:58 +00008179
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008180 return DefaultCon;
8181}
8182
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00008183void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
8184 CXXConstructorDecl *Constructor) {
Alexis Huntf92197c2011-05-12 03:51:51 +00008185 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Alexis Hunt61ae8d32011-05-23 23:14:04 +00008186 !Constructor->doesThisDeclarationHaveABody() &&
8187 !Constructor->isDeleted()) &&
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00008188 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00008189
Anders Carlsson423f5d82010-04-23 16:04:08 +00008190 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman9cf6b592009-11-09 19:20:36 +00008191 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +00008192
Eli Friedmaneaf34142012-10-18 20:14:08 +00008193 SynthesizedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00008194 DiagnosticErrorTrap Trap(Diags);
David Blaikie3fc2f912013-01-17 05:26:25 +00008195 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00008196 Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00008197 Diag(CurrentLocation, diag::note_member_synthesized_at)
Alexis Hunt80f00ff2011-05-10 19:08:14 +00008198 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00008199 Constructor->setInvalidDecl();
Douglas Gregor73193272010-09-20 16:48:21 +00008200 return;
Eli Friedman9cf6b592009-11-09 19:20:36 +00008201 }
Douglas Gregor73193272010-09-20 16:48:21 +00008202
8203 SourceLocation Loc = Constructor->getLocation();
Benjamin Kramere2a929d2012-07-04 17:03:41 +00008204 Constructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor73193272010-09-20 16:48:21 +00008205
Eli Friedman276dd182013-09-05 00:02:25 +00008206 Constructor->markUsed(Context);
Douglas Gregor73193272010-09-20 16:48:21 +00008207 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00008208
8209 if (ASTMutationListener *L = getASTMutationListener()) {
8210 L->CompletedImplicitDefinition(Constructor);
8211 }
Richard Trieuef64e942013-10-25 00:56:00 +00008212
8213 DiagnoseUninitializedFields(*this, Constructor);
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00008214}
8215
Richard Smith938f40b2011-06-11 17:19:42 +00008216void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
Alp Tokerae3a9442013-10-18 05:54:19 +00008217 // Perform any delayed checks on exception specifications.
8218 CheckDelayedMemberExceptionSpecs();
Richard Smith938f40b2011-06-11 17:19:42 +00008219}
8220
Richard Smith185be182013-04-10 05:48:59 +00008221namespace {
8222/// Information on inheriting constructors to declare.
8223class InheritingConstructorInfo {
8224public:
8225 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
8226 : SemaRef(SemaRef), Derived(Derived) {
8227 // Mark the constructors that we already have in the derived class.
8228 //
8229 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
8230 // unless there is a user-declared constructor with the same signature in
8231 // the class where the using-declaration appears.
8232 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
8233 }
8234
8235 void inheritAll(CXXRecordDecl *RD) {
8236 visitAll(RD, &InheritingConstructorInfo::inherit);
8237 }
8238
8239private:
8240 /// Information about an inheriting constructor.
8241 struct InheritingConstructor {
8242 InheritingConstructor()
8243 : DeclaredInDerived(false), BaseCtor(0), DerivedCtor(0) {}
8244
8245 /// If \c true, a constructor with this signature is already declared
8246 /// in the derived class.
8247 bool DeclaredInDerived;
8248
8249 /// The constructor which is inherited.
8250 const CXXConstructorDecl *BaseCtor;
8251
8252 /// The derived constructor we declared.
8253 CXXConstructorDecl *DerivedCtor;
8254 };
8255
8256 /// Inheriting constructors with a given canonical type. There can be at
8257 /// most one such non-template constructor, and any number of templated
8258 /// constructors.
8259 struct InheritingConstructorsForType {
8260 InheritingConstructor NonTemplate;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008261 SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4>
8262 Templates;
Richard Smith185be182013-04-10 05:48:59 +00008263
8264 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
8265 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
8266 TemplateParameterList *ParamList = FTD->getTemplateParameters();
8267 for (unsigned I = 0, N = Templates.size(); I != N; ++I)
8268 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
8269 false, S.TPL_TemplateMatch))
8270 return Templates[I].second;
8271 Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
8272 return Templates.back().second;
Sebastian Redl08905022011-02-05 19:23:19 +00008273 }
Richard Smith185be182013-04-10 05:48:59 +00008274
8275 return NonTemplate;
8276 }
8277 };
8278
8279 /// Get or create the inheriting constructor record for a constructor.
8280 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
8281 QualType CtorType) {
8282 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
8283 .getEntry(SemaRef, Ctor);
8284 }
8285
8286 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
8287
8288 /// Process all constructors for a class.
8289 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00008290 for (const auto *Ctor : RD->ctors())
8291 (this->*Callback)(Ctor);
Richard Smith185be182013-04-10 05:48:59 +00008292 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
8293 I(RD->decls_begin()), E(RD->decls_end());
8294 I != E; ++I) {
8295 const FunctionDecl *FD = (*I)->getTemplatedDecl();
8296 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
8297 (this->*Callback)(CD);
Sebastian Redl08905022011-02-05 19:23:19 +00008298 }
8299 }
Richard Smith185be182013-04-10 05:48:59 +00008300
8301 /// Note that a constructor (or constructor template) was declared in Derived.
8302 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
8303 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
8304 }
8305
8306 /// Inherit a single constructor.
8307 void inherit(const CXXConstructorDecl *Ctor) {
8308 const FunctionProtoType *CtorType =
8309 Ctor->getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00008310 ArrayRef<QualType> ArgTypes(CtorType->getParamTypes());
Richard Smith185be182013-04-10 05:48:59 +00008311 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
8312
8313 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
8314
8315 // Core issue (no number yet): the ellipsis is always discarded.
8316 if (EPI.Variadic) {
8317 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
8318 SemaRef.Diag(Ctor->getLocation(),
8319 diag::note_using_decl_constructor_ellipsis);
8320 EPI.Variadic = false;
8321 }
8322
8323 // Declare a constructor for each number of parameters.
8324 //
8325 // C++11 [class.inhctor]p1:
8326 // The candidate set of inherited constructors from the class X named in
8327 // the using-declaration consists of [... modulo defects ...] for each
8328 // constructor or constructor template of X, the set of constructors or
8329 // constructor templates that results from omitting any ellipsis parameter
8330 // specification and successively omitting parameters with a default
8331 // argument from the end of the parameter-type-list
Richard Smith3c626ed2013-04-17 19:00:52 +00008332 unsigned MinParams = minParamsToInherit(Ctor);
8333 unsigned Params = Ctor->getNumParams();
8334 if (Params >= MinParams) {
8335 do
8336 declareCtor(UsingLoc, Ctor,
8337 SemaRef.Context.getFunctionType(
Alp Toker314cc812014-01-25 16:55:45 +00008338 Ctor->getReturnType(), ArgTypes.slice(0, Params), EPI));
Richard Smith3c626ed2013-04-17 19:00:52 +00008339 while (Params > MinParams &&
8340 Ctor->getParamDecl(--Params)->hasDefaultArg());
8341 }
Richard Smith185be182013-04-10 05:48:59 +00008342 }
8343
8344 /// Find the using-declaration which specified that we should inherit the
8345 /// constructors of \p Base.
8346 SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
8347 // No fancy lookup required; just look for the base constructor name
8348 // directly within the derived class.
8349 ASTContext &Context = SemaRef.Context;
8350 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8351 Context.getCanonicalType(Context.getRecordType(Base)));
8352 DeclContext::lookup_const_result Decls = Derived->lookup(Name);
8353 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
8354 }
8355
8356 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
8357 // C++11 [class.inhctor]p3:
8358 // [F]or each constructor template in the candidate set of inherited
8359 // constructors, a constructor template is implicitly declared
8360 if (Ctor->getDescribedFunctionTemplate())
8361 return 0;
8362
8363 // For each non-template constructor in the candidate set of inherited
8364 // constructors other than a constructor having no parameters or a
8365 // copy/move constructor having a single parameter, a constructor is
8366 // implicitly declared [...]
8367 if (Ctor->getNumParams() == 0)
8368 return 1;
8369 if (Ctor->isCopyOrMoveConstructor())
8370 return 2;
8371
8372 // Per discussion on core reflector, never inherit a constructor which
8373 // would become a default, copy, or move constructor of Derived either.
8374 const ParmVarDecl *PD = Ctor->getParamDecl(0);
8375 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
8376 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
8377 }
8378
8379 /// Declare a single inheriting constructor, inheriting the specified
8380 /// constructor, with the given type.
8381 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
8382 QualType DerivedType) {
8383 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
8384
8385 // C++11 [class.inhctor]p3:
8386 // ... a constructor is implicitly declared with the same constructor
8387 // characteristics unless there is a user-declared constructor with
8388 // the same signature in the class where the using-declaration appears
8389 if (Entry.DeclaredInDerived)
8390 return;
8391
8392 // C++11 [class.inhctor]p7:
8393 // If two using-declarations declare inheriting constructors with the
8394 // same signature, the program is ill-formed
8395 if (Entry.DerivedCtor) {
8396 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
8397 // Only diagnose this once per constructor.
8398 if (Entry.DerivedCtor->isInvalidDecl())
8399 return;
8400 Entry.DerivedCtor->setInvalidDecl();
8401
8402 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
8403 SemaRef.Diag(BaseCtor->getLocation(),
8404 diag::note_using_decl_constructor_conflict_current_ctor);
8405 SemaRef.Diag(Entry.BaseCtor->getLocation(),
8406 diag::note_using_decl_constructor_conflict_previous_ctor);
8407 SemaRef.Diag(Entry.DerivedCtor->getLocation(),
8408 diag::note_using_decl_constructor_conflict_previous_using);
8409 } else {
8410 // Core issue (no number): if the same inheriting constructor is
8411 // produced by multiple base class constructors from the same base
8412 // class, the inheriting constructor is defined as deleted.
8413 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
8414 }
8415
8416 return;
8417 }
8418
8419 ASTContext &Context = SemaRef.Context;
8420 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8421 Context.getCanonicalType(Context.getRecordType(Derived)));
8422 DeclarationNameInfo NameInfo(Name, UsingLoc);
8423
8424 TemplateParameterList *TemplateParams = 0;
8425 if (const FunctionTemplateDecl *FTD =
8426 BaseCtor->getDescribedFunctionTemplate()) {
8427 TemplateParams = FTD->getTemplateParameters();
8428 // We're reusing template parameters from a different DeclContext. This
8429 // is questionable at best, but works out because the template depth in
8430 // both places is guaranteed to be 0.
8431 // FIXME: Rebuild the template parameters in the new context, and
8432 // transform the function type to refer to them.
8433 }
8434
8435 // Build type source info pointing at the using-declaration. This is
8436 // required by template instantiation.
8437 TypeSourceInfo *TInfo =
8438 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
8439 FunctionProtoTypeLoc ProtoLoc =
8440 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
8441
8442 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
8443 Context, Derived, UsingLoc, NameInfo, DerivedType,
8444 TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
8445 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
8446
8447 // Build an unevaluated exception specification for this constructor.
8448 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
8449 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8450 EPI.ExceptionSpecType = EST_Unevaluated;
8451 EPI.ExceptionSpecDecl = DerivedCtor;
Alp Toker314cc812014-01-25 16:55:45 +00008452 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00008453 FPT->getParamTypes(), EPI));
Richard Smith185be182013-04-10 05:48:59 +00008454
8455 // Build the parameter declarations.
8456 SmallVector<ParmVarDecl *, 16> ParamDecls;
Alp Toker9cacbab2014-01-20 20:26:09 +00008457 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
Richard Smith185be182013-04-10 05:48:59 +00008458 TypeSourceInfo *TInfo =
Alp Toker9cacbab2014-01-20 20:26:09 +00008459 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
Richard Smith185be182013-04-10 05:48:59 +00008460 ParmVarDecl *PD = ParmVarDecl::Create(
8461 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/0,
Alp Toker9cacbab2014-01-20 20:26:09 +00008462 FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/0);
Richard Smith185be182013-04-10 05:48:59 +00008463 PD->setScopeInfo(0, I);
8464 PD->setImplicit();
8465 ParamDecls.push_back(PD);
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00008466 ProtoLoc.setParam(I, PD);
Richard Smith185be182013-04-10 05:48:59 +00008467 }
8468
8469 // Set up the new constructor.
8470 DerivedCtor->setAccess(BaseCtor->getAccess());
8471 DerivedCtor->setParams(ParamDecls);
8472 DerivedCtor->setInheritedConstructor(BaseCtor);
8473 if (BaseCtor->isDeleted())
8474 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
8475
8476 // If this is a constructor template, build the template declaration.
8477 if (TemplateParams) {
8478 FunctionTemplateDecl *DerivedTemplate =
8479 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
8480 TemplateParams, DerivedCtor);
8481 DerivedTemplate->setAccess(BaseCtor->getAccess());
8482 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
8483 Derived->addDecl(DerivedTemplate);
8484 } else {
8485 Derived->addDecl(DerivedCtor);
8486 }
8487
8488 Entry.BaseCtor = BaseCtor;
8489 Entry.DerivedCtor = DerivedCtor;
8490 }
8491
8492 Sema &SemaRef;
8493 CXXRecordDecl *Derived;
8494 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
8495 MapType Map;
8496};
8497}
8498
8499void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
8500 // Defer declaring the inheriting constructors until the class is
8501 // instantiated.
8502 if (ClassDecl->isDependentContext())
Sebastian Redl08905022011-02-05 19:23:19 +00008503 return;
8504
Richard Smith185be182013-04-10 05:48:59 +00008505 // Find base classes from which we might inherit constructors.
8506 SmallVector<CXXRecordDecl*, 4> InheritedBases;
Aaron Ballman574705e2014-03-13 15:41:46 +00008507 for (const auto &BaseIt : ClassDecl->bases())
8508 if (BaseIt.getInheritConstructors())
8509 InheritedBases.push_back(BaseIt.getType()->getAsCXXRecordDecl());
Richard Smithc2bc61b2013-03-18 21:12:30 +00008510
Richard Smith185be182013-04-10 05:48:59 +00008511 // Go no further if we're not inheriting any constructors.
8512 if (InheritedBases.empty())
8513 return;
Sebastian Redl08905022011-02-05 19:23:19 +00008514
Richard Smith185be182013-04-10 05:48:59 +00008515 // Declare the inherited constructors.
8516 InheritingConstructorInfo ICI(*this, ClassDecl);
8517 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
8518 ICI.inheritAll(InheritedBases[I]);
Sebastian Redl08905022011-02-05 19:23:19 +00008519}
8520
Richard Smithc2bc61b2013-03-18 21:12:30 +00008521void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
8522 CXXConstructorDecl *Constructor) {
8523 CXXRecordDecl *ClassDecl = Constructor->getParent();
8524 assert(Constructor->getInheritedConstructor() &&
8525 !Constructor->doesThisDeclarationHaveABody() &&
8526 !Constructor->isDeleted());
8527
8528 SynthesizedFunctionScope Scope(*this, Constructor);
8529 DiagnosticErrorTrap Trap(Diags);
8530 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
8531 Trap.hasErrorOccurred()) {
8532 Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
8533 << Context.getTagDeclType(ClassDecl);
8534 Constructor->setInvalidDecl();
8535 return;
8536 }
8537
8538 SourceLocation Loc = Constructor->getLocation();
8539 Constructor->setBody(new (Context) CompoundStmt(Loc));
8540
Eli Friedman276dd182013-09-05 00:02:25 +00008541 Constructor->markUsed(Context);
Richard Smithc2bc61b2013-03-18 21:12:30 +00008542 MarkVTableUsed(CurrentLocation, ClassDecl);
8543
8544 if (ASTMutationListener *L = getASTMutationListener()) {
8545 L->CompletedImplicitDefinition(Constructor);
8546 }
8547}
8548
8549
Alexis Huntf91729462011-05-12 22:46:25 +00008550Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +00008551Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
8552 CXXRecordDecl *ClassDecl = MD->getParent();
8553
Douglas Gregorf1203042010-07-01 19:09:28 +00008554 // C++ [except.spec]p14:
8555 // An implicitly declared special member function (Clause 12) shall have
8556 // an exception-specification.
Richard Smithf623c962012-04-17 00:58:00 +00008557 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00008558 if (ClassDecl->isInvalidDecl())
8559 return ExceptSpec;
8560
Douglas Gregorf1203042010-07-01 19:09:28 +00008561 // Direct base-class destructors.
Aaron Ballman574705e2014-03-13 15:41:46 +00008562 for (const auto &B : ClassDecl->bases()) {
8563 if (B.isVirtual()) // Handled below.
Douglas Gregorf1203042010-07-01 19:09:28 +00008564 continue;
8565
Aaron Ballman574705e2014-03-13 15:41:46 +00008566 if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
8567 ExceptSpec.CalledDecl(B.getLocStart(),
Sebastian Redl623ea822011-05-19 05:13:44 +00008568 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00008569 }
Sebastian Redl623ea822011-05-19 05:13:44 +00008570
Douglas Gregorf1203042010-07-01 19:09:28 +00008571 // Virtual base-class destructors.
Aaron Ballman445a9392014-03-13 16:15:17 +00008572 for (const auto &B : ClassDecl->vbases()) {
8573 if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
8574 ExceptSpec.CalledDecl(B.getLocStart(),
Sebastian Redl623ea822011-05-19 05:13:44 +00008575 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00008576 }
Sebastian Redl623ea822011-05-19 05:13:44 +00008577
Douglas Gregorf1203042010-07-01 19:09:28 +00008578 // Field destructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008579 for (const auto *F : ClassDecl->fields()) {
Douglas Gregorf1203042010-07-01 19:09:28 +00008580 if (const RecordType *RecordTy
8581 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
Richard Smithf623c962012-04-17 00:58:00 +00008582 ExceptSpec.CalledDecl(F->getLocation(),
Sebastian Redl623ea822011-05-19 05:13:44 +00008583 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00008584 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008585
Alexis Huntf91729462011-05-12 22:46:25 +00008586 return ExceptSpec;
8587}
8588
8589CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
8590 // C++ [class.dtor]p2:
8591 // If a class has no user-declared destructor, a destructor is
8592 // declared implicitly. An implicitly-declared destructor is an
8593 // inline public member of its class.
Richard Smith2be35f52012-12-01 02:35:44 +00008594 assert(ClassDecl->needsImplicitDestructor());
Alexis Huntf91729462011-05-12 22:46:25 +00008595
Richard Smith8bf22e52012-11-29 01:34:07 +00008596 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
8597 if (DSM.isAlreadyBeingDeclared())
8598 return 0;
8599
Douglas Gregor7454c562010-07-02 20:37:36 +00008600 // Create the actual destructor declaration.
Douglas Gregorf1203042010-07-01 19:09:28 +00008601 CanQualType ClassType
8602 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00008603 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorf1203042010-07-01 19:09:28 +00008604 DeclarationName Name
8605 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00008606 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorf1203042010-07-01 19:09:28 +00008607 CXXDestructorDecl *Destructor
Richard Smithd3b5c9082012-07-27 04:22:15 +00008608 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8609 QualType(), 0, /*isInline=*/true,
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008610 /*isImplicitlyDeclared=*/true);
Douglas Gregorf1203042010-07-01 19:09:28 +00008611 Destructor->setAccess(AS_public);
Alexis Huntf91729462011-05-12 22:46:25 +00008612 Destructor->setDefaulted();
Douglas Gregorf1203042010-07-01 19:09:28 +00008613 Destructor->setImplicit();
Richard Smithd3b5c9082012-07-27 04:22:15 +00008614
8615 // Build an exception specification pointing back at this destructor.
Reid Kleckner78af0702013-08-27 23:08:25 +00008616 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00008617 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00008618
Richard Smith6b02d462012-12-08 08:32:28 +00008619 AddOverriddenMethods(ClassDecl, Destructor);
8620
8621 // We don't need to use SpecialMemberIsTrivial here; triviality for
8622 // destructors is easy to compute.
8623 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
8624
8625 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
Richard Smithb4d2a152013-04-02 19:38:47 +00008626 SetDeclDeleted(Destructor, ClassLoc);
Richard Smith6b02d462012-12-08 08:32:28 +00008627
Douglas Gregor7454c562010-07-02 20:37:36 +00008628 // Note that we have declared this destructor.
Douglas Gregor7454c562010-07-02 20:37:36 +00008629 ++ASTContext::NumImplicitDestructorsDeclared;
Richard Smithd3b5c9082012-07-27 04:22:15 +00008630
Douglas Gregor7454c562010-07-02 20:37:36 +00008631 // Introduce this destructor into its scope.
Douglas Gregor0be31a22010-07-02 17:43:08 +00008632 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor7454c562010-07-02 20:37:36 +00008633 PushOnScopeChains(Destructor, S, false);
8634 ClassDecl->addDecl(Destructor);
Alexis Huntf91729462011-05-12 22:46:25 +00008635
Douglas Gregorf1203042010-07-01 19:09:28 +00008636 return Destructor;
8637}
8638
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008639void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00008640 CXXDestructorDecl *Destructor) {
Alexis Hunt61ae8d32011-05-23 23:14:04 +00008641 assert((Destructor->isDefaulted() &&
Richard Smith273c4e92012-02-26 07:51:39 +00008642 !Destructor->doesThisDeclarationHaveABody() &&
8643 !Destructor->isDeleted()) &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008644 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +00008645 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008646 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008647
Douglas Gregor54818f02010-05-12 16:39:35 +00008648 if (Destructor->isInvalidDecl())
8649 return;
8650
Eli Friedmaneaf34142012-10-18 20:14:08 +00008651 SynthesizedFunctionScope Scope(*this, Destructor);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008652
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00008653 DiagnosticErrorTrap Trap(Diags);
John McCalla6309952010-03-16 21:39:52 +00008654 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
8655 Destructor->getParent());
Mike Stump11289f42009-09-09 15:08:12 +00008656
Douglas Gregor54818f02010-05-12 16:39:35 +00008657 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00008658 Diag(CurrentLocation, diag::note_member_synthesized_at)
8659 << CXXDestructor << Context.getTagDeclType(ClassDecl);
8660
8661 Destructor->setInvalidDecl();
8662 return;
8663 }
8664
Douglas Gregor73193272010-09-20 16:48:21 +00008665 SourceLocation Loc = Destructor->getLocation();
Benjamin Kramere2a929d2012-07-04 17:03:41 +00008666 Destructor->setBody(new (Context) CompoundStmt(Loc));
Eli Friedman276dd182013-09-05 00:02:25 +00008667 Destructor->markUsed(Context);
Douglas Gregor88d292c2010-05-13 16:44:06 +00008668 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00008669
8670 if (ASTMutationListener *L = getASTMutationListener()) {
8671 L->CompletedImplicitDefinition(Destructor);
8672 }
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008673}
8674
Richard Smith84973e52012-04-21 18:42:51 +00008675/// \brief Perform any semantic analysis which needs to be delayed until all
8676/// pending class member declarations have been parsed.
8677void Sema::ActOnFinishCXXMemberDecls() {
Douglas Gregorbc0e5c02013-02-01 04:49:10 +00008678 // If the context is an invalid C++ class, just suppress these checks.
8679 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
8680 if (Record->isInvalidDecl()) {
Alp Tokerae3a9442013-10-18 05:54:19 +00008681 DelayedDefaultedMemberExceptionSpecs.clear();
Douglas Gregorbc0e5c02013-02-01 04:49:10 +00008682 DelayedDestructorExceptionSpecChecks.clear();
8683 return;
8684 }
8685 }
Richard Smith84973e52012-04-21 18:42:51 +00008686}
8687
Richard Smithd3b5c9082012-07-27 04:22:15 +00008688void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
8689 CXXDestructorDecl *Destructor) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008690 assert(getLangOpts().CPlusPlus11 &&
Richard Smithd3b5c9082012-07-27 04:22:15 +00008691 "adjusting dtor exception specs was introduced in c++11");
8692
Sebastian Redl623ea822011-05-19 05:13:44 +00008693 // C++11 [class.dtor]p3:
8694 // A declaration of a destructor that does not have an exception-
8695 // specification is implicitly considered to have the same exception-
8696 // specification as an implicit declaration.
Richard Smithd3b5c9082012-07-27 04:22:15 +00008697 const FunctionProtoType *DtorType = Destructor->getType()->
Sebastian Redl623ea822011-05-19 05:13:44 +00008698 getAs<FunctionProtoType>();
Richard Smithd3b5c9082012-07-27 04:22:15 +00008699 if (DtorType->hasExceptionSpec())
Sebastian Redl623ea822011-05-19 05:13:44 +00008700 return;
8701
Chandler Carruth9a797572011-09-20 04:55:26 +00008702 // Replace the destructor's type, building off the existing one. Fortunately,
8703 // the only thing of interest in the destructor type is its extended info.
8704 // The return and arguments are fixed.
Richard Smithd3b5c9082012-07-27 04:22:15 +00008705 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
8706 EPI.ExceptionSpecType = EST_Unevaluated;
8707 EPI.ExceptionSpecDecl = Destructor;
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00008708 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smith84973e52012-04-21 18:42:51 +00008709
Sebastian Redl623ea822011-05-19 05:13:44 +00008710 // FIXME: If the destructor has a body that could throw, and the newly created
8711 // spec doesn't allow exceptions, we should emit a warning, because this
8712 // change in behavior can break conforming C++03 programs at runtime.
Richard Smithd3b5c9082012-07-27 04:22:15 +00008713 // However, we don't have a body or an exception specification yet, so it
8714 // needs to be done somewhere else.
Sebastian Redl623ea822011-05-19 05:13:44 +00008715}
8716
Pavel Labath58934982013-08-30 08:52:28 +00008717namespace {
8718/// \brief An abstract base class for all helper classes used in building the
8719// copy/move operators. These classes serve as factory functions and help us
8720// avoid using the same Expr* in the AST twice.
8721class ExprBuilder {
8722 ExprBuilder(const ExprBuilder&) LLVM_DELETED_FUNCTION;
8723 ExprBuilder &operator=(const ExprBuilder&) LLVM_DELETED_FUNCTION;
8724
8725protected:
8726 static Expr *assertNotNull(Expr *E) {
8727 assert(E && "Expression construction must not fail.");
8728 return E;
8729 }
8730
8731public:
8732 ExprBuilder() {}
8733 virtual ~ExprBuilder() {}
8734
8735 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
8736};
8737
8738class RefBuilder: public ExprBuilder {
8739 VarDecl *Var;
8740 QualType VarType;
8741
8742public:
Craig Toppera798a9d2014-03-02 09:32:10 +00008743 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00008744 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).take());
8745 }
8746
8747 RefBuilder(VarDecl *Var, QualType VarType)
8748 : Var(Var), VarType(VarType) {}
8749};
8750
8751class ThisBuilder: public ExprBuilder {
8752public:
Craig Toppera798a9d2014-03-02 09:32:10 +00008753 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00008754 return assertNotNull(S.ActOnCXXThis(Loc).takeAs<Expr>());
8755 }
8756};
8757
8758class CastBuilder: public ExprBuilder {
8759 const ExprBuilder &Builder;
8760 QualType Type;
8761 ExprValueKind Kind;
8762 const CXXCastPath &Path;
8763
8764public:
Craig Toppera798a9d2014-03-02 09:32:10 +00008765 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00008766 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
8767 CK_UncheckedDerivedToBase, Kind,
8768 &Path).take());
8769 }
8770
8771 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
8772 const CXXCastPath &Path)
8773 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
8774};
8775
8776class DerefBuilder: public ExprBuilder {
8777 const ExprBuilder &Builder;
8778
8779public:
Craig Toppera798a9d2014-03-02 09:32:10 +00008780 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00008781 return assertNotNull(
8782 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).take());
8783 }
8784
8785 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
8786};
8787
8788class MemberBuilder: public ExprBuilder {
8789 const ExprBuilder &Builder;
8790 QualType Type;
8791 CXXScopeSpec SS;
8792 bool IsArrow;
8793 LookupResult &MemberLookup;
8794
8795public:
Craig Toppera798a9d2014-03-02 09:32:10 +00008796 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00008797 return assertNotNull(S.BuildMemberReferenceExpr(
8798 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 0,
8799 MemberLookup, 0).take());
8800 }
8801
8802 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
8803 LookupResult &MemberLookup)
8804 : Builder(Builder), Type(Type), IsArrow(IsArrow),
8805 MemberLookup(MemberLookup) {}
8806};
8807
8808class MoveCastBuilder: public ExprBuilder {
8809 const ExprBuilder &Builder;
8810
8811public:
Craig Toppera798a9d2014-03-02 09:32:10 +00008812 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00008813 return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
8814 }
8815
8816 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
8817};
8818
8819class LvalueConvBuilder: public ExprBuilder {
8820 const ExprBuilder &Builder;
8821
8822public:
Craig Toppera798a9d2014-03-02 09:32:10 +00008823 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00008824 return assertNotNull(
8825 S.DefaultLvalueConversion(Builder.build(S, Loc)).take());
8826 }
8827
8828 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
8829};
8830
8831class SubscriptBuilder: public ExprBuilder {
8832 const ExprBuilder &Base;
8833 const ExprBuilder &Index;
8834
8835public:
Craig Toppera798a9d2014-03-02 09:32:10 +00008836 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00008837 return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
8838 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).take());
8839 }
8840
8841 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
8842 : Base(Base), Index(Index) {}
8843};
8844
8845} // end anonymous namespace
8846
Richard Smith41ae3282012-11-14 00:50:40 +00008847/// When generating a defaulted copy or move assignment operator, if a field
8848/// should be copied with __builtin_memcpy rather than via explicit assignments,
8849/// do so. This optimization only applies for arrays of scalars, and for arrays
8850/// of class type where the selected copy/move-assignment operator is trivial.
8851static StmtResult
8852buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +00008853 const ExprBuilder &ToB, const ExprBuilder &FromB) {
Richard Smith41ae3282012-11-14 00:50:40 +00008854 // Compute the size of the memory buffer to be copied.
8855 QualType SizeType = S.Context.getSizeType();
8856 llvm::APInt Size(S.Context.getTypeSize(SizeType),
8857 S.Context.getTypeSizeInChars(T).getQuantity());
8858
8859 // Take the address of the field references for "from" and "to". We
8860 // directly construct UnaryOperators here because semantic analysis
8861 // does not permit us to take the address of an xvalue.
Pavel Labath58934982013-08-30 08:52:28 +00008862 Expr *From = FromB.build(S, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00008863 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
8864 S.Context.getPointerType(From->getType()),
8865 VK_RValue, OK_Ordinary, Loc);
Pavel Labath58934982013-08-30 08:52:28 +00008866 Expr *To = ToB.build(S, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00008867 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
8868 S.Context.getPointerType(To->getType()),
8869 VK_RValue, OK_Ordinary, Loc);
8870
8871 const Type *E = T->getBaseElementTypeUnsafe();
8872 bool NeedsCollectableMemCpy =
8873 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
8874
8875 // Create a reference to the __builtin_objc_memmove_collectable function
8876 StringRef MemCpyName = NeedsCollectableMemCpy ?
8877 "__builtin_objc_memmove_collectable" :
8878 "__builtin_memcpy";
8879 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
8880 Sema::LookupOrdinaryName);
8881 S.LookupName(R, S.TUScope, true);
8882
8883 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
8884 if (!MemCpy)
8885 // Something went horribly wrong earlier, and we will have complained
8886 // about it.
8887 return StmtError();
8888
8889 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
8890 VK_RValue, Loc, 0);
8891 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
8892
8893 Expr *CallArgs[] = {
8894 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
8895 };
8896 ExprResult Call = S.ActOnCallExpr(/*Scope=*/0, MemCpyRef.take(),
8897 Loc, CallArgs, Loc);
8898
8899 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8900 return S.Owned(Call.takeAs<Stmt>());
8901}
8902
Sebastian Redl22653ba2011-08-30 19:58:05 +00008903/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregorb139cd52010-05-01 20:49:11 +00008904/// \c To.
8905///
Sebastian Redl22653ba2011-08-30 19:58:05 +00008906/// This routine is used to copy/move the members of a class with an
8907/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregorb139cd52010-05-01 20:49:11 +00008908/// copied are arrays, this routine builds for loops to copy them.
8909///
8910/// \param S The Sema object used for type-checking.
8911///
Sebastian Redl22653ba2011-08-30 19:58:05 +00008912/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregorb139cd52010-05-01 20:49:11 +00008913///
Sebastian Redl22653ba2011-08-30 19:58:05 +00008914/// \param T The type of the expressions being copied/moved. Both expressions
8915/// must have this type.
Douglas Gregorb139cd52010-05-01 20:49:11 +00008916///
Sebastian Redl22653ba2011-08-30 19:58:05 +00008917/// \param To The expression we are copying/moving to.
Douglas Gregorb139cd52010-05-01 20:49:11 +00008918///
Sebastian Redl22653ba2011-08-30 19:58:05 +00008919/// \param From The expression we are copying/moving from.
Douglas Gregorb139cd52010-05-01 20:49:11 +00008920///
Sebastian Redl22653ba2011-08-30 19:58:05 +00008921/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor40c92bb2010-05-04 15:20:55 +00008922/// Otherwise, it's a non-static member subobject.
8923///
Sebastian Redl22653ba2011-08-30 19:58:05 +00008924/// \param Copying Whether we're copying or moving.
8925///
Douglas Gregorb139cd52010-05-01 20:49:11 +00008926/// \param Depth Internal parameter recording the depth of the recursion.
8927///
Richard Smith41ae3282012-11-14 00:50:40 +00008928/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
8929/// if a memcpy should be used instead.
John McCalldadc5752010-08-24 06:29:42 +00008930static StmtResult
Richard Smith41ae3282012-11-14 00:50:40 +00008931buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +00008932 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith41ae3282012-11-14 00:50:40 +00008933 bool CopyingBaseSubobject, bool Copying,
8934 unsigned Depth = 0) {
Richard Smith52c0b582012-11-13 00:54:12 +00008935 // C++11 [class.copy]p28:
Douglas Gregorb139cd52010-05-01 20:49:11 +00008936 // Each subobject is assigned in the manner appropriate to its type:
8937 //
Sebastian Redl22653ba2011-08-30 19:58:05 +00008938 // - if the subobject is of class type, as if by a call to operator= with
8939 // the subobject as the object expression and the corresponding
8940 // subobject of x as a single function argument (as if by explicit
8941 // qualification; that is, ignoring any possible virtual overriding
8942 // functions in more derived classes);
Richard Smith52c0b582012-11-13 00:54:12 +00008943 //
8944 // C++03 [class.copy]p13:
8945 // - if the subobject is of class type, the copy assignment operator for
8946 // the class is used (as if by explicit qualification; that is,
8947 // ignoring any possible virtual overriding functions in more derived
8948 // classes);
Douglas Gregorb139cd52010-05-01 20:49:11 +00008949 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
8950 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith52c0b582012-11-13 00:54:12 +00008951
Douglas Gregorb139cd52010-05-01 20:49:11 +00008952 // Look for operator=.
8953 DeclarationName Name
8954 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8955 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
8956 S.LookupQualifiedName(OpLookup, ClassDecl, false);
Sebastian Redl22653ba2011-08-30 19:58:05 +00008957
Richard Smith52c0b582012-11-13 00:54:12 +00008958 // Prior to C++11, filter out any result that isn't a copy/move-assignment
8959 // operator.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008960 if (!S.getLangOpts().CPlusPlus11) {
Richard Smith52c0b582012-11-13 00:54:12 +00008961 LookupResult::Filter F = OpLookup.makeFilter();
8962 while (F.hasNext()) {
8963 NamedDecl *D = F.next();
8964 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
8965 if (Method->isCopyAssignmentOperator() ||
8966 (!Copying && Method->isMoveAssignmentOperator()))
8967 continue;
8968
8969 F.erase();
8970 }
8971 F.done();
John McCallab8c2732010-03-16 06:11:48 +00008972 }
Richard Smith52c0b582012-11-13 00:54:12 +00008973
Douglas Gregor40c92bb2010-05-04 15:20:55 +00008974 // Suppress the protected check (C++ [class.protected]) for each of the
Richard Smith52c0b582012-11-13 00:54:12 +00008975 // assignment operators we found. This strange dance is required when
Douglas Gregor40c92bb2010-05-04 15:20:55 +00008976 // we're assigning via a base classes's copy-assignment operator. To
Richard Smith52c0b582012-11-13 00:54:12 +00008977 // ensure that we're getting the right base class subobject (without
Douglas Gregor40c92bb2010-05-04 15:20:55 +00008978 // ambiguities), we need to cast "this" to that subobject type; to
8979 // ensure that we don't go through the virtual call mechanism, we need
8980 // to qualify the operator= name with the base class (see below). However,
8981 // this means that if the base class has a protected copy assignment
8982 // operator, the protected member access check will fail. So, we
8983 // rewrite "protected" access to "public" access in this case, since we
8984 // know by construction that we're calling from a derived class.
8985 if (CopyingBaseSubobject) {
8986 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
8987 L != LEnd; ++L) {
8988 if (L.getAccess() == AS_protected)
8989 L.setAccess(AS_public);
8990 }
8991 }
Richard Smith52c0b582012-11-13 00:54:12 +00008992
Douglas Gregorb139cd52010-05-01 20:49:11 +00008993 // Create the nested-name-specifier that will be used to qualify the
8994 // reference to operator=; this is required to suppress the virtual
8995 // call mechanism.
8996 CXXScopeSpec SS;
Manuel Klimeke7167412012-02-06 21:51:39 +00008997 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Richard Smith52c0b582012-11-13 00:54:12 +00008998 SS.MakeTrivial(S.Context,
8999 NestedNameSpecifier::Create(S.Context, 0, false,
Manuel Klimeke7167412012-02-06 21:51:39 +00009000 CanonicalT),
Douglas Gregor869ad452011-02-24 17:54:50 +00009001 Loc);
Richard Smith52c0b582012-11-13 00:54:12 +00009002
Douglas Gregorb139cd52010-05-01 20:49:11 +00009003 // Create the reference to operator=.
John McCalldadc5752010-08-24 06:29:42 +00009004 ExprResult OpEqualRef
Pavel Labath58934982013-08-30 08:52:28 +00009005 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
9006 SS, /*TemplateKWLoc=*/SourceLocation(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00009007 /*FirstQualifierInScope=*/0,
9008 OpLookup,
Douglas Gregorb139cd52010-05-01 20:49:11 +00009009 /*TemplateArgs=*/0,
9010 /*SuppressQualifierCheck=*/true);
9011 if (OpEqualRef.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009012 return StmtError();
Richard Smith52c0b582012-11-13 00:54:12 +00009013
Douglas Gregorb139cd52010-05-01 20:49:11 +00009014 // Build the call to the assignment operator.
John McCallb268a282010-08-23 23:25:46 +00009015
Pavel Labath58934982013-08-30 08:52:28 +00009016 Expr *FromInst = From.build(S, Loc);
Richard Smith52c0b582012-11-13 00:54:12 +00009017 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregorce5aa332010-09-09 16:33:13 +00009018 OpEqualRef.takeAs<Expr>(),
Pavel Labath58934982013-08-30 08:52:28 +00009019 Loc, FromInst, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009020 if (Call.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009021 return StmtError();
Richard Smith52c0b582012-11-13 00:54:12 +00009022
Richard Smith41ae3282012-11-14 00:50:40 +00009023 // If we built a call to a trivial 'operator=' while copying an array,
9024 // bail out. We'll replace the whole shebang with a memcpy.
9025 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
9026 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
9027 return StmtResult((Stmt*)0);
9028
Richard Smith52c0b582012-11-13 00:54:12 +00009029 // Convert to an expression-statement, and clean up any produced
9030 // temporaries.
Richard Smith945f8d32013-01-14 22:39:08 +00009031 return S.ActOnExprStmt(Call);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009032 }
John McCallab8c2732010-03-16 06:11:48 +00009033
Richard Smith52c0b582012-11-13 00:54:12 +00009034 // - if the subobject is of scalar type, the built-in assignment
Douglas Gregorb139cd52010-05-01 20:49:11 +00009035 // operator is used.
Richard Smith52c0b582012-11-13 00:54:12 +00009036 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009037 if (!ArrayTy) {
Pavel Labath58934982013-08-30 08:52:28 +00009038 ExprResult Assignment = S.CreateBuiltinBinOp(
9039 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00009040 if (Assignment.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009041 return StmtError();
Richard Smith945f8d32013-01-14 22:39:08 +00009042 return S.ActOnExprStmt(Assignment);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009043 }
Richard Smith52c0b582012-11-13 00:54:12 +00009044
9045 // - if the subobject is an array, each element is assigned, in the
Douglas Gregorb139cd52010-05-01 20:49:11 +00009046 // manner appropriate to the element type;
Richard Smith52c0b582012-11-13 00:54:12 +00009047
Douglas Gregorb139cd52010-05-01 20:49:11 +00009048 // Construct a loop over the array bounds, e.g.,
9049 //
9050 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
9051 //
9052 // that will copy each of the array elements.
9053 QualType SizeType = S.Context.getSizeType();
Richard Smith41ae3282012-11-14 00:50:40 +00009054
Douglas Gregorb139cd52010-05-01 20:49:11 +00009055 // Create the iteration variable.
9056 IdentifierInfo *IterationVarName = 0;
9057 {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00009058 SmallString<8> Str;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009059 llvm::raw_svector_ostream OS(Str);
9060 OS << "__i" << Depth;
9061 IterationVarName = &S.Context.Idents.get(OS.str());
9062 }
Abramo Bagnaradff19302011-03-08 08:55:46 +00009063 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregorb139cd52010-05-01 20:49:11 +00009064 IterationVarName, SizeType,
9065 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00009066 SC_None);
Richard Smith41ae3282012-11-14 00:50:40 +00009067
Douglas Gregorb139cd52010-05-01 20:49:11 +00009068 // Initialize the iteration variable to zero.
9069 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00009070 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00009071
Pavel Labath58934982013-08-30 08:52:28 +00009072 // Creates a reference to the iteration variable.
9073 RefBuilder IterationVarRef(IterationVar, SizeType);
9074 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
Eli Friedman844f9452012-01-23 02:35:22 +00009075
Douglas Gregorb139cd52010-05-01 20:49:11 +00009076 // Create the DeclStmt that holds the iteration variable.
9077 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009078
Douglas Gregorb139cd52010-05-01 20:49:11 +00009079 // Subscript the "from" and "to" expressions with the iteration variable.
Pavel Labath58934982013-08-30 08:52:28 +00009080 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
9081 MoveCastBuilder FromIndexMove(FromIndexCopy);
9082 const ExprBuilder *FromIndex;
9083 if (Copying)
9084 FromIndex = &FromIndexCopy;
9085 else
9086 FromIndex = &FromIndexMove;
9087
9088 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009089
9090 // Build the copy/move for an individual element of the array.
Richard Smith41ae3282012-11-14 00:50:40 +00009091 StmtResult Copy =
9092 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
Pavel Labath58934982013-08-30 08:52:28 +00009093 ToIndex, *FromIndex, CopyingBaseSubobject,
Richard Smith41ae3282012-11-14 00:50:40 +00009094 Copying, Depth + 1);
9095 // Bail out if copying fails or if we determined that we should use memcpy.
9096 if (Copy.isInvalid() || !Copy.get())
9097 return Copy;
9098
9099 // Create the comparison against the array bound.
9100 llvm::APInt Upper
9101 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
9102 Expr *Comparison
Pavel Labath58934982013-08-30 08:52:28 +00009103 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
Richard Smith41ae3282012-11-14 00:50:40 +00009104 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
9105 BO_NE, S.Context.BoolTy,
9106 VK_RValue, OK_Ordinary, Loc, false);
9107
9108 // Create the pre-increment of the iteration variable.
9109 Expr *Increment
Pavel Labath58934982013-08-30 08:52:28 +00009110 = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
9111 SizeType, VK_LValue, OK_Ordinary, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009112
Douglas Gregorb139cd52010-05-01 20:49:11 +00009113 // Construct the loop that copies all elements of this array.
John McCallb268a282010-08-23 23:25:46 +00009114 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregorb139cd52010-05-01 20:49:11 +00009115 S.MakeFullExpr(Comparison),
Richard Smith945f8d32013-01-14 22:39:08 +00009116 0, S.MakeFullDiscardedValueExpr(Increment),
John McCallb268a282010-08-23 23:25:46 +00009117 Loc, Copy.take());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009118}
9119
Richard Smith41ae3282012-11-14 00:50:40 +00009120static StmtResult
9121buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +00009122 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith41ae3282012-11-14 00:50:40 +00009123 bool CopyingBaseSubobject, bool Copying) {
9124 // Maybe we should use a memcpy?
9125 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
9126 T.isTriviallyCopyableType(S.Context))
9127 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9128
9129 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
9130 CopyingBaseSubobject,
9131 Copying, 0));
9132
9133 // If we ended up picking a trivial assignment operator for an array of a
9134 // non-trivially-copyable class type, just emit a memcpy.
9135 if (!Result.isInvalid() && !Result.get())
9136 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9137
9138 return Result;
9139}
9140
Richard Smithd3b5c9082012-07-27 04:22:15 +00009141Sema::ImplicitExceptionSpecification
9142Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
9143 CXXRecordDecl *ClassDecl = MD->getParent();
9144
9145 ImplicitExceptionSpecification ExceptSpec(*this);
9146 if (ClassDecl->isInvalidDecl())
9147 return ExceptSpec;
9148
9149 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00009150 assert(T->getNumParams() == 1 && "not a copy assignment op");
9151 unsigned ArgQuals =
9152 T->getParamType(0).getNonReferenceType().getCVRQualifiers();
Richard Smithd3b5c9082012-07-27 04:22:15 +00009153
Douglas Gregor68e11362010-07-01 17:48:08 +00009154 // C++ [except.spec]p14:
Richard Smithd3b5c9082012-07-27 04:22:15 +00009155 // An implicitly declared special member function (Clause 12) shall have an
Douglas Gregor68e11362010-07-01 17:48:08 +00009156 // exception-specification. [...]
Alexis Hunt491ec602011-06-21 23:42:56 +00009157
9158 // It is unspecified whether or not an implicit copy assignment operator
9159 // attempts to deduplicate calls to assignment operators of virtual bases are
9160 // made. As such, this exception specification is effectively unspecified.
9161 // Based on a similar decision made for constness in C++0x, we're erring on
9162 // the side of assuming such calls to be made regardless of whether they
9163 // actually happen.
Aaron Ballman574705e2014-03-13 15:41:46 +00009164 for (const auto &Base : ClassDecl->bases()) {
9165 if (Base.isVirtual())
Alexis Hunt491ec602011-06-21 23:42:56 +00009166 continue;
9167
Douglas Gregor330b9cf2010-07-02 21:50:04 +00009168 CXXRecordDecl *BaseClassDecl
Aaron Ballman574705e2014-03-13 15:41:46 +00009169 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +00009170 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9171 ArgQuals, false, 0))
Aaron Ballman574705e2014-03-13 15:41:46 +00009172 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
Douglas Gregor68e11362010-07-01 17:48:08 +00009173 }
Alexis Hunt491ec602011-06-21 23:42:56 +00009174
Aaron Ballman445a9392014-03-13 16:15:17 +00009175 for (const auto &Base : ClassDecl->vbases()) {
Alexis Hunt491ec602011-06-21 23:42:56 +00009176 CXXRecordDecl *BaseClassDecl
Aaron Ballman445a9392014-03-13 16:15:17 +00009177 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +00009178 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9179 ArgQuals, false, 0))
Aaron Ballman445a9392014-03-13 16:15:17 +00009180 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
Alexis Hunt491ec602011-06-21 23:42:56 +00009181 }
9182
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009183 for (const auto *Field : ClassDecl->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00009184 QualType FieldType = Context.getBaseElementType(Field->getType());
Alexis Hunt491ec602011-06-21 23:42:56 +00009185 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9186 if (CXXMethodDecl *CopyAssign =
Richard Smith1c6461e2012-07-18 03:36:00 +00009187 LookupCopyingAssignment(FieldClassDecl,
9188 ArgQuals | FieldType.getCVRQualifiers(),
9189 false, 0))
Richard Smithf623c962012-04-17 00:58:00 +00009190 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00009191 }
Douglas Gregor68e11362010-07-01 17:48:08 +00009192 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00009193
Richard Smithd3b5c9082012-07-27 04:22:15 +00009194 return ExceptSpec;
Alexis Hunt119f3652011-05-14 05:23:20 +00009195}
9196
9197CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
9198 // Note: The following rules are largely analoguous to the copy
9199 // constructor rules. Note that virtual bases are not taken into account
9200 // for determining the argument type of the operator. Note also that
9201 // operators taking an object instead of a reference are allowed.
Richard Smith2be35f52012-12-01 02:35:44 +00009202 assert(ClassDecl->needsImplicitCopyAssignment());
Alexis Hunt119f3652011-05-14 05:23:20 +00009203
Richard Smith8bf22e52012-11-29 01:34:07 +00009204 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
9205 if (DSM.isAlreadyBeingDeclared())
9206 return 0;
9207
Alexis Hunt119f3652011-05-14 05:23:20 +00009208 QualType ArgType = Context.getTypeDeclType(ClassDecl);
9209 QualType RetType = Context.getLValueReferenceType(ArgType);
Richard Smith99005e62013-05-07 03:19:20 +00009210 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
9211 if (Const)
Alexis Hunt119f3652011-05-14 05:23:20 +00009212 ArgType = ArgType.withConst();
9213 ArgType = Context.getLValueReferenceType(ArgType);
9214
Richard Smith99005e62013-05-07 03:19:20 +00009215 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9216 CXXCopyAssignment,
9217 Const);
9218
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009219 // An implicitly-declared copy assignment operator is an inline public
9220 // member of its class.
9221 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaradff19302011-03-08 08:55:46 +00009222 SourceLocation ClassLoc = ClassDecl->getLocation();
9223 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith99005e62013-05-07 03:19:20 +00009224 CXXMethodDecl *CopyAssignment =
9225 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
9226 /*TInfo=*/ 0, /*StorageClass=*/ SC_None,
9227 /*isInline=*/ true, Constexpr, SourceLocation());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009228 CopyAssignment->setAccess(AS_public);
Alexis Huntb2f27802011-05-14 05:23:24 +00009229 CopyAssignment->setDefaulted();
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009230 CopyAssignment->setImplicit();
Richard Smithd3b5c9082012-07-27 04:22:15 +00009231
9232 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +00009233 FunctionProtoType::ExtProtoInfo EPI =
9234 getImplicitMethodEPI(*this, CopyAssignment);
Jordan Rose5c382722013-03-08 21:51:21 +00009235 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00009236
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009237 // Add the parameter to the operator.
9238 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaradff19302011-03-08 08:55:46 +00009239 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009240 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00009241 SC_None, 0);
David Blaikie9c70e042011-09-21 18:16:56 +00009242 CopyAssignment->setParams(FromParam);
Alexis Huntb2f27802011-05-14 05:23:24 +00009243
Richard Smith6b02d462012-12-08 08:32:28 +00009244 AddOverriddenMethods(ClassDecl, CopyAssignment);
9245
9246 CopyAssignment->setTrivial(
9247 ClassDecl->needsOverloadResolutionForCopyAssignment()
9248 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
9249 : ClassDecl->hasTrivialCopyAssignment());
9250
Richard Smith852265f2012-03-30 20:53:28 +00009251 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
Richard Smithb4d2a152013-04-02 19:38:47 +00009252 SetDeclDeleted(CopyAssignment, ClassLoc);
Richard Smith852265f2012-03-30 20:53:28 +00009253
Richard Smith6b02d462012-12-08 08:32:28 +00009254 // Note that we have added this copy-assignment operator.
9255 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
9256
9257 if (Scope *S = getScopeForContext(ClassDecl))
9258 PushOnScopeChains(CopyAssignment, S, false);
9259 ClassDecl->addDecl(CopyAssignment);
9260
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009261 return CopyAssignment;
9262}
9263
Richard Smithd577fbb2013-06-13 03:23:42 +00009264/// Diagnose an implicit copy operation for a class which is odr-used, but
9265/// which is deprecated because the class has a user-declared copy constructor,
9266/// copy assignment operator, or destructor.
9267static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
9268 SourceLocation UseLoc) {
9269 assert(CopyOp->isImplicit());
9270
9271 CXXRecordDecl *RD = CopyOp->getParent();
9272 CXXMethodDecl *UserDeclaredOperation = 0;
9273
9274 // In Microsoft mode, assignment operations don't affect constructors and
9275 // vice versa.
9276 if (RD->hasUserDeclaredDestructor()) {
9277 UserDeclaredOperation = RD->getDestructor();
9278 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
9279 RD->hasUserDeclaredCopyConstructor() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00009280 !S.getLangOpts().MSVCCompat) {
Richard Smithd577fbb2013-06-13 03:23:42 +00009281 // Find any user-declared copy constructor.
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00009282 for (auto *I : RD->ctors()) {
Richard Smithd577fbb2013-06-13 03:23:42 +00009283 if (I->isCopyConstructor()) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00009284 UserDeclaredOperation = I;
Richard Smithd577fbb2013-06-13 03:23:42 +00009285 break;
9286 }
9287 }
9288 assert(UserDeclaredOperation);
9289 } else if (isa<CXXConstructorDecl>(CopyOp) &&
9290 RD->hasUserDeclaredCopyAssignment() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00009291 !S.getLangOpts().MSVCCompat) {
Richard Smithd577fbb2013-06-13 03:23:42 +00009292 // Find any user-declared move assignment operator.
Aaron Ballman2b124d12014-03-13 16:36:16 +00009293 for (auto *I : RD->methods()) {
Richard Smithd577fbb2013-06-13 03:23:42 +00009294 if (I->isCopyAssignmentOperator()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00009295 UserDeclaredOperation = I;
Richard Smithd577fbb2013-06-13 03:23:42 +00009296 break;
9297 }
9298 }
9299 assert(UserDeclaredOperation);
9300 }
9301
9302 if (UserDeclaredOperation) {
9303 S.Diag(UserDeclaredOperation->getLocation(),
9304 diag::warn_deprecated_copy_operation)
9305 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
9306 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
9307 S.Diag(UseLoc, diag::note_member_synthesized_at)
9308 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
9309 : Sema::CXXCopyAssignment)
9310 << RD;
9311 }
9312}
9313
Douglas Gregorb139cd52010-05-01 20:49:11 +00009314void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
9315 CXXMethodDecl *CopyAssignOperator) {
Alexis Huntb2f27802011-05-14 05:23:24 +00009316 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00009317 CopyAssignOperator->isOverloadedOperator() &&
9318 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith273c4e92012-02-26 07:51:39 +00009319 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
9320 !CopyAssignOperator->isDeleted()) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00009321 "DefineImplicitCopyAssignment called for wrong function");
9322
9323 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
9324
9325 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
9326 CopyAssignOperator->setInvalidDecl();
9327 return;
9328 }
Richard Smithd577fbb2013-06-13 03:23:42 +00009329
9330 // C++11 [class.copy]p18:
9331 // The [definition of an implicitly declared copy assignment operator] is
9332 // deprecated if the class has a user-declared copy constructor or a
9333 // user-declared destructor.
9334 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
9335 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
9336
Eli Friedman276dd182013-09-05 00:02:25 +00009337 CopyAssignOperator->markUsed(Context);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009338
Eli Friedmaneaf34142012-10-18 20:14:08 +00009339 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00009340 DiagnosticErrorTrap Trap(Diags);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009341
9342 // C++0x [class.copy]p30:
9343 // The implicitly-defined or explicitly-defaulted copy assignment operator
9344 // for a non-union class X performs memberwise copy assignment of its
9345 // subobjects. The direct base classes of X are assigned first, in the
9346 // order of their declaration in the base-specifier-list, and then the
9347 // immediate non-static data members of X are assigned, in the order in
9348 // which they were declared in the class definition.
9349
9350 // The statements that form the synthesized function body.
Benjamin Kramerf0623432012-08-23 22:51:59 +00009351 SmallVector<Stmt*, 8> Statements;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009352
9353 // The parameter for the "other" object, which we are copying from.
9354 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
9355 Qualifiers OtherQuals = Other->getType().getQualifiers();
9356 QualType OtherRefType = Other->getType();
9357 if (const LValueReferenceType *OtherRef
9358 = OtherRefType->getAs<LValueReferenceType>()) {
9359 OtherRefType = OtherRef->getPointeeType();
9360 OtherQuals = OtherRefType.getQualifiers();
9361 }
9362
9363 // Our location for everything implicitly-generated.
9364 SourceLocation Loc = CopyAssignOperator->getLocation();
9365
Pavel Labath58934982013-08-30 08:52:28 +00009366 // Builds a DeclRefExpr for the "other" object.
9367 RefBuilder OtherRef(Other, OtherRefType);
9368
9369 // Builds the "this" pointer.
9370 ThisBuilder This;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009371
9372 // Assign base classes.
9373 bool Invalid = false;
Aaron Ballman574705e2014-03-13 15:41:46 +00009374 for (auto &Base : ClassDecl->bases()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00009375 // Form the assignment:
9376 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
Aaron Ballman574705e2014-03-13 15:41:46 +00009377 QualType BaseType = Base.getType().getUnqualifiedType();
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00009378 if (!BaseType->isRecordType()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00009379 Invalid = true;
9380 continue;
9381 }
9382
John McCallcf142162010-08-07 06:22:56 +00009383 CXXCastPath BasePath;
Aaron Ballman574705e2014-03-13 15:41:46 +00009384 BasePath.push_back(&Base);
John McCallcf142162010-08-07 06:22:56 +00009385
Douglas Gregorb139cd52010-05-01 20:49:11 +00009386 // Construct the "from" expression, which is an implicit cast to the
9387 // appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +00009388 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
9389 VK_LValue, BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009390
9391 // Dereference "this".
Pavel Labath58934982013-08-30 08:52:28 +00009392 DerefBuilder DerefThis(This);
9393 CastBuilder To(DerefThis,
9394 Context.getCVRQualifiedType(
9395 BaseType, CopyAssignOperator->getTypeQualifiers()),
9396 VK_LValue, BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009397
9398 // Build the copy.
Richard Smith41ae3282012-11-14 00:50:40 +00009399 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath58934982013-08-30 08:52:28 +00009400 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +00009401 /*CopyingBaseSubobject=*/true,
9402 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009403 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00009404 Diag(CurrentLocation, diag::note_member_synthesized_at)
9405 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9406 CopyAssignOperator->setInvalidDecl();
9407 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009408 }
9409
9410 // Success! Record the copy.
9411 Statements.push_back(Copy.takeAs<Expr>());
9412 }
9413
Douglas Gregorb139cd52010-05-01 20:49:11 +00009414 // Assign non-static members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009415 for (auto *Field : ClassDecl->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +00009416 if (Field->isUnnamedBitfield())
9417 continue;
Eli Friedmanc9817fd2013-06-07 01:48:56 +00009418
9419 if (Field->isInvalidDecl()) {
9420 Invalid = true;
9421 continue;
9422 }
9423
Douglas Gregorb139cd52010-05-01 20:49:11 +00009424 // Check for members of reference type; we can't copy those.
9425 if (Field->getType()->isReferenceType()) {
9426 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9427 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9428 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00009429 Diag(CurrentLocation, diag::note_member_synthesized_at)
9430 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009431 Invalid = true;
9432 continue;
9433 }
9434
9435 // Check for members of const-qualified, non-class type.
9436 QualType BaseType = Context.getBaseElementType(Field->getType());
9437 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9438 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9439 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9440 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00009441 Diag(CurrentLocation, diag::note_member_synthesized_at)
9442 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009443 Invalid = true;
9444 continue;
9445 }
John McCall1b1a1db2011-06-17 00:18:42 +00009446
9447 // Suppress assigning zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +00009448 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9449 continue;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009450
9451 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00009452 if (FieldType->isIncompleteArrayType()) {
9453 assert(ClassDecl->hasFlexibleArrayMember() &&
9454 "Incomplete array type is not valid");
9455 continue;
9456 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00009457
9458 // Build references to the field in the object we're copying from and to.
9459 CXXScopeSpec SS; // Intentionally empty
9460 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9461 LookupMemberName);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009462 MemberLookup.addDecl(Field);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009463 MemberLookup.resolveKind();
Pavel Labath58934982013-08-30 08:52:28 +00009464
9465 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
9466
9467 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009468
Douglas Gregorb139cd52010-05-01 20:49:11 +00009469 // Build the copy of this field.
Richard Smith41ae3282012-11-14 00:50:40 +00009470 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath58934982013-08-30 08:52:28 +00009471 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +00009472 /*CopyingBaseSubobject=*/false,
9473 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009474 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00009475 Diag(CurrentLocation, diag::note_member_synthesized_at)
9476 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9477 CopyAssignOperator->setInvalidDecl();
9478 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009479 }
9480
9481 // Success! Record the copy.
9482 Statements.push_back(Copy.takeAs<Stmt>());
9483 }
9484
9485 if (!Invalid) {
9486 // Add a "return *this;"
Pavel Labath58934982013-08-30 08:52:28 +00009487 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00009488
John McCalldadc5752010-08-24 06:29:42 +00009489 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregorb139cd52010-05-01 20:49:11 +00009490 if (Return.isInvalid())
9491 Invalid = true;
9492 else {
9493 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregor54818f02010-05-12 16:39:35 +00009494
9495 if (Trap.hasErrorOccurred()) {
9496 Diag(CurrentLocation, diag::note_member_synthesized_at)
9497 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9498 Invalid = true;
9499 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00009500 }
9501 }
9502
9503 if (Invalid) {
9504 CopyAssignOperator->setInvalidDecl();
9505 return;
9506 }
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009507
9508 StmtResult Body;
9509 {
9510 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00009511 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009512 /*isStmtExpr=*/false);
9513 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9514 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00009515 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redlab238a72011-04-24 16:28:06 +00009516
9517 if (ASTMutationListener *L = getASTMutationListener()) {
9518 L->CompletedImplicitDefinition(CopyAssignOperator);
9519 }
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009520}
9521
Sebastian Redl22653ba2011-08-30 19:58:05 +00009522Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +00009523Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
9524 CXXRecordDecl *ClassDecl = MD->getParent();
Sebastian Redl22653ba2011-08-30 19:58:05 +00009525
Richard Smithd3b5c9082012-07-27 04:22:15 +00009526 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009527 if (ClassDecl->isInvalidDecl())
9528 return ExceptSpec;
9529
9530 // C++0x [except.spec]p14:
9531 // An implicitly declared special member function (Clause 12) shall have an
9532 // exception-specification. [...]
9533
9534 // It is unspecified whether or not an implicit move assignment operator
9535 // attempts to deduplicate calls to assignment operators of virtual bases are
9536 // made. As such, this exception specification is effectively unspecified.
9537 // Based on a similar decision made for constness in C++0x, we're erring on
9538 // the side of assuming such calls to be made regardless of whether they
9539 // actually happen.
9540 // Note that a move constructor is not implicitly declared when there are
9541 // virtual bases, but it can still be user-declared and explicitly defaulted.
Aaron Ballman574705e2014-03-13 15:41:46 +00009542 for (const auto &Base : ClassDecl->bases()) {
9543 if (Base.isVirtual())
Sebastian Redl22653ba2011-08-30 19:58:05 +00009544 continue;
9545
9546 CXXRecordDecl *BaseClassDecl
Aaron Ballman574705e2014-03-13 15:41:46 +00009547 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Sebastian Redl22653ba2011-08-30 19:58:05 +00009548 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith1c6461e2012-07-18 03:36:00 +00009549 0, false, 0))
Aaron Ballman574705e2014-03-13 15:41:46 +00009550 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009551 }
9552
Aaron Ballman445a9392014-03-13 16:15:17 +00009553 for (const auto &Base : ClassDecl->vbases()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00009554 CXXRecordDecl *BaseClassDecl
Aaron Ballman445a9392014-03-13 16:15:17 +00009555 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Sebastian Redl22653ba2011-08-30 19:58:05 +00009556 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith1c6461e2012-07-18 03:36:00 +00009557 0, false, 0))
Aaron Ballman445a9392014-03-13 16:15:17 +00009558 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009559 }
9560
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009561 for (const auto *Field : ClassDecl->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00009562 QualType FieldType = Context.getBaseElementType(Field->getType());
Sebastian Redl22653ba2011-08-30 19:58:05 +00009563 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith1c6461e2012-07-18 03:36:00 +00009564 if (CXXMethodDecl *MoveAssign =
9565 LookupMovingAssignment(FieldClassDecl,
9566 FieldType.getCVRQualifiers(),
9567 false, 0))
Richard Smithf623c962012-04-17 00:58:00 +00009568 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009569 }
9570 }
9571
9572 return ExceptSpec;
9573}
9574
9575CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +00009576 assert(ClassDecl->needsImplicitMoveAssignment());
9577
Richard Smith8bf22e52012-11-29 01:34:07 +00009578 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
9579 if (DSM.isAlreadyBeingDeclared())
9580 return 0;
9581
Sebastian Redl22653ba2011-08-30 19:58:05 +00009582 // Note: The following rules are largely analoguous to the move
9583 // constructor rules.
9584
Sebastian Redl22653ba2011-08-30 19:58:05 +00009585 QualType ArgType = Context.getTypeDeclType(ClassDecl);
9586 QualType RetType = Context.getLValueReferenceType(ArgType);
9587 ArgType = Context.getRValueReferenceType(ArgType);
9588
Richard Smith99005e62013-05-07 03:19:20 +00009589 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9590 CXXMoveAssignment,
9591 false);
9592
Sebastian Redl22653ba2011-08-30 19:58:05 +00009593 // An implicitly-declared move assignment operator is an inline public
9594 // member of its class.
Sebastian Redl22653ba2011-08-30 19:58:05 +00009595 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9596 SourceLocation ClassLoc = ClassDecl->getLocation();
9597 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith99005e62013-05-07 03:19:20 +00009598 CXXMethodDecl *MoveAssignment =
9599 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
9600 /*TInfo=*/0, /*StorageClass=*/SC_None,
9601 /*isInline=*/true, Constexpr, SourceLocation());
Sebastian Redl22653ba2011-08-30 19:58:05 +00009602 MoveAssignment->setAccess(AS_public);
9603 MoveAssignment->setDefaulted();
9604 MoveAssignment->setImplicit();
Sebastian Redl22653ba2011-08-30 19:58:05 +00009605
Richard Smithd3b5c9082012-07-27 04:22:15 +00009606 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +00009607 FunctionProtoType::ExtProtoInfo EPI =
9608 getImplicitMethodEPI(*this, MoveAssignment);
Jordan Rose5c382722013-03-08 21:51:21 +00009609 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00009610
Sebastian Redl22653ba2011-08-30 19:58:05 +00009611 // Add the parameter to the operator.
9612 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
9613 ClassLoc, ClassLoc, /*Id=*/0,
9614 ArgType, /*TInfo=*/0,
Sebastian Redl22653ba2011-08-30 19:58:05 +00009615 SC_None, 0);
David Blaikie9c70e042011-09-21 18:16:56 +00009616 MoveAssignment->setParams(FromParam);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009617
Richard Smith6b02d462012-12-08 08:32:28 +00009618 AddOverriddenMethods(ClassDecl, MoveAssignment);
9619
9620 MoveAssignment->setTrivial(
9621 ClassDecl->needsOverloadResolutionForMoveAssignment()
9622 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
9623 : ClassDecl->hasTrivialMoveAssignment());
Sebastian Redl22653ba2011-08-30 19:58:05 +00009624
Richard Smithd951a1d2012-02-18 02:02:13 +00009625 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Richard Smith8b86f2d2013-11-04 01:48:18 +00009626 ClassDecl->setImplicitMoveAssignmentIsDeleted();
9627 SetDeclDeleted(MoveAssignment, ClassLoc);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009628 }
9629
Richard Smith6b02d462012-12-08 08:32:28 +00009630 // Note that we have added this copy-assignment operator.
9631 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
9632
Sebastian Redl22653ba2011-08-30 19:58:05 +00009633 if (Scope *S = getScopeForContext(ClassDecl))
9634 PushOnScopeChains(MoveAssignment, S, false);
9635 ClassDecl->addDecl(MoveAssignment);
9636
Sebastian Redl22653ba2011-08-30 19:58:05 +00009637 return MoveAssignment;
9638}
9639
Richard Smithb2504bd2013-11-04 04:26:14 +00009640/// Check if we're implicitly defining a move assignment operator for a class
9641/// with virtual bases. Such a move assignment might move-assign the virtual
9642/// base multiple times.
9643static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
9644 SourceLocation CurrentLocation) {
9645 assert(!Class->isDependentContext() && "should not define dependent move");
9646
9647 // Only a virtual base could get implicitly move-assigned multiple times.
9648 // Only a non-trivial move assignment can observe this. We only want to
9649 // diagnose if we implicitly define an assignment operator that assigns
9650 // two base classes, both of which move-assign the same virtual base.
9651 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
9652 Class->getNumBases() < 2)
9653 return;
9654
9655 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
9656 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
9657 VBaseMap VBases;
9658
Aaron Ballman574705e2014-03-13 15:41:46 +00009659 for (auto &BI : Class->bases()) {
9660 Worklist.push_back(&BI);
Richard Smithb2504bd2013-11-04 04:26:14 +00009661 while (!Worklist.empty()) {
9662 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
9663 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
9664
9665 // If the base has no non-trivial move assignment operators,
9666 // we don't care about moves from it.
9667 if (!Base->hasNonTrivialMoveAssignment())
9668 continue;
9669
9670 // If there's nothing virtual here, skip it.
9671 if (!BaseSpec->isVirtual() && !Base->getNumVBases())
9672 continue;
9673
9674 // If we're not actually going to call a move assignment for this base,
9675 // or the selected move assignment is trivial, skip it.
9676 Sema::SpecialMemberOverloadResult *SMOR =
9677 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
9678 /*ConstArg*/false, /*VolatileArg*/false,
9679 /*RValueThis*/true, /*ConstThis*/false,
9680 /*VolatileThis*/false);
9681 if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() ||
9682 !SMOR->getMethod()->isMoveAssignmentOperator())
9683 continue;
9684
9685 if (BaseSpec->isVirtual()) {
9686 // We're going to move-assign this virtual base, and its move
9687 // assignment operator is not trivial. If this can happen for
9688 // multiple distinct direct bases of Class, diagnose it. (If it
9689 // only happens in one base, we'll diagnose it when synthesizing
9690 // that base class's move assignment operator.)
9691 CXXBaseSpecifier *&Existing =
Aaron Ballman574705e2014-03-13 15:41:46 +00009692 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
Richard Smithb2504bd2013-11-04 04:26:14 +00009693 .first->second;
Aaron Ballman574705e2014-03-13 15:41:46 +00009694 if (Existing && Existing != &BI) {
Richard Smithb2504bd2013-11-04 04:26:14 +00009695 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
9696 << Class << Base;
9697 S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here)
9698 << (Base->getCanonicalDecl() ==
9699 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
9700 << Base << Existing->getType() << Existing->getSourceRange();
Aaron Ballman574705e2014-03-13 15:41:46 +00009701 S.Diag(BI.getLocStart(), diag::note_vbase_moved_here)
Richard Smithb2504bd2013-11-04 04:26:14 +00009702 << (Base->getCanonicalDecl() ==
Aaron Ballman574705e2014-03-13 15:41:46 +00009703 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
9704 << Base << BI.getType() << BaseSpec->getSourceRange();
Richard Smithb2504bd2013-11-04 04:26:14 +00009705
9706 // Only diagnose each vbase once.
9707 Existing = 0;
9708 }
9709 } else {
9710 // Only walk over bases that have defaulted move assignment operators.
9711 // We assume that any user-provided move assignment operator handles
9712 // the multiple-moves-of-vbase case itself somehow.
9713 if (!SMOR->getMethod()->isDefaulted())
9714 continue;
9715
9716 // We're going to move the base classes of Base. Add them to the list.
Aaron Ballman574705e2014-03-13 15:41:46 +00009717 for (auto &BI : Base->bases())
9718 Worklist.push_back(&BI);
Richard Smithb2504bd2013-11-04 04:26:14 +00009719 }
9720 }
9721 }
9722}
9723
Sebastian Redl22653ba2011-08-30 19:58:05 +00009724void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
9725 CXXMethodDecl *MoveAssignOperator) {
9726 assert((MoveAssignOperator->isDefaulted() &&
9727 MoveAssignOperator->isOverloadedOperator() &&
9728 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith273c4e92012-02-26 07:51:39 +00009729 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
9730 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl22653ba2011-08-30 19:58:05 +00009731 "DefineImplicitMoveAssignment called for wrong function");
9732
9733 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
9734
9735 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
9736 MoveAssignOperator->setInvalidDecl();
9737 return;
9738 }
9739
Eli Friedman276dd182013-09-05 00:02:25 +00009740 MoveAssignOperator->markUsed(Context);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009741
Eli Friedmaneaf34142012-10-18 20:14:08 +00009742 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009743 DiagnosticErrorTrap Trap(Diags);
9744
9745 // C++0x [class.copy]p28:
9746 // The implicitly-defined or move assignment operator for a non-union class
9747 // X performs memberwise move assignment of its subobjects. The direct base
9748 // classes of X are assigned first, in the order of their declaration in the
9749 // base-specifier-list, and then the immediate non-static data members of X
9750 // are assigned, in the order in which they were declared in the class
9751 // definition.
9752
Richard Smithb2504bd2013-11-04 04:26:14 +00009753 // Issue a warning if our implicit move assignment operator will move
9754 // from a virtual base more than once.
9755 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
Richard Smith8b86f2d2013-11-04 01:48:18 +00009756
Sebastian Redl22653ba2011-08-30 19:58:05 +00009757 // The statements that form the synthesized function body.
Benjamin Kramerf0623432012-08-23 22:51:59 +00009758 SmallVector<Stmt*, 8> Statements;
Sebastian Redl22653ba2011-08-30 19:58:05 +00009759
9760 // The parameter for the "other" object, which we are move from.
9761 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
9762 QualType OtherRefType = Other->getType()->
9763 getAs<RValueReferenceType>()->getPointeeType();
David Blaikie7d170102013-05-15 07:37:26 +00009764 assert(!OtherRefType.getQualifiers() &&
Sebastian Redl22653ba2011-08-30 19:58:05 +00009765 "Bad argument type of defaulted move assignment");
9766
9767 // Our location for everything implicitly-generated.
9768 SourceLocation Loc = MoveAssignOperator->getLocation();
9769
Pavel Labath58934982013-08-30 08:52:28 +00009770 // Builds a reference to the "other" object.
9771 RefBuilder OtherRef(Other, OtherRefType);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009772 // Cast to rvalue.
Pavel Labath58934982013-08-30 08:52:28 +00009773 MoveCastBuilder MoveOther(OtherRef);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009774
Pavel Labath58934982013-08-30 08:52:28 +00009775 // Builds the "this" pointer.
9776 ThisBuilder This;
Richard Smithcf8ec8d2012-04-02 18:40:40 +00009777
Sebastian Redl22653ba2011-08-30 19:58:05 +00009778 // Assign base classes.
9779 bool Invalid = false;
Aaron Ballman574705e2014-03-13 15:41:46 +00009780 for (auto &Base : ClassDecl->bases()) {
Richard Smithb2504bd2013-11-04 04:26:14 +00009781 // C++11 [class.copy]p28:
9782 // It is unspecified whether subobjects representing virtual base classes
9783 // are assigned more than once by the implicitly-defined copy assignment
9784 // operator.
9785 // FIXME: Do not assign to a vbase that will be assigned by some other base
9786 // class. For a move-assignment, this can result in the vbase being moved
9787 // multiple times.
9788
Sebastian Redl22653ba2011-08-30 19:58:05 +00009789 // Form the assignment:
9790 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
Aaron Ballman574705e2014-03-13 15:41:46 +00009791 QualType BaseType = Base.getType().getUnqualifiedType();
Sebastian Redl22653ba2011-08-30 19:58:05 +00009792 if (!BaseType->isRecordType()) {
9793 Invalid = true;
9794 continue;
9795 }
9796
9797 CXXCastPath BasePath;
Aaron Ballman574705e2014-03-13 15:41:46 +00009798 BasePath.push_back(&Base);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009799
9800 // Construct the "from" expression, which is an implicit cast to the
9801 // appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +00009802 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009803
9804 // Dereference "this".
Pavel Labath58934982013-08-30 08:52:28 +00009805 DerefBuilder DerefThis(This);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009806
9807 // Implicitly cast "this" to the appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +00009808 CastBuilder To(DerefThis,
9809 Context.getCVRQualifiedType(
9810 BaseType, MoveAssignOperator->getTypeQualifiers()),
9811 VK_LValue, BasePath);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009812
9813 // Build the move.
Richard Smith41ae3282012-11-14 00:50:40 +00009814 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath58934982013-08-30 08:52:28 +00009815 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +00009816 /*CopyingBaseSubobject=*/true,
9817 /*Copying=*/false);
9818 if (Move.isInvalid()) {
9819 Diag(CurrentLocation, diag::note_member_synthesized_at)
9820 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9821 MoveAssignOperator->setInvalidDecl();
9822 return;
9823 }
9824
9825 // Success! Record the move.
9826 Statements.push_back(Move.takeAs<Expr>());
9827 }
9828
Sebastian Redl22653ba2011-08-30 19:58:05 +00009829 // Assign non-static members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009830 for (auto *Field : ClassDecl->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +00009831 if (Field->isUnnamedBitfield())
9832 continue;
9833
Eli Friedmanc9817fd2013-06-07 01:48:56 +00009834 if (Field->isInvalidDecl()) {
9835 Invalid = true;
9836 continue;
9837 }
9838
Sebastian Redl22653ba2011-08-30 19:58:05 +00009839 // Check for members of reference type; we can't move those.
9840 if (Field->getType()->isReferenceType()) {
9841 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9842 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9843 Diag(Field->getLocation(), diag::note_declared_at);
9844 Diag(CurrentLocation, diag::note_member_synthesized_at)
9845 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9846 Invalid = true;
9847 continue;
9848 }
9849
9850 // Check for members of const-qualified, non-class type.
9851 QualType BaseType = Context.getBaseElementType(Field->getType());
9852 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9853 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9854 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9855 Diag(Field->getLocation(), diag::note_declared_at);
9856 Diag(CurrentLocation, diag::note_member_synthesized_at)
9857 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9858 Invalid = true;
9859 continue;
9860 }
9861
9862 // Suppress assigning zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +00009863 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9864 continue;
Sebastian Redl22653ba2011-08-30 19:58:05 +00009865
9866 QualType FieldType = Field->getType().getNonReferenceType();
9867 if (FieldType->isIncompleteArrayType()) {
9868 assert(ClassDecl->hasFlexibleArrayMember() &&
9869 "Incomplete array type is not valid");
9870 continue;
9871 }
9872
9873 // Build references to the field in the object we're copying from and to.
Sebastian Redl22653ba2011-08-30 19:58:05 +00009874 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9875 LookupMemberName);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009876 MemberLookup.addDecl(Field);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009877 MemberLookup.resolveKind();
Pavel Labath58934982013-08-30 08:52:28 +00009878 MemberBuilder From(MoveOther, OtherRefType,
9879 /*IsArrow=*/false, MemberLookup);
9880 MemberBuilder To(This, getCurrentThisType(),
9881 /*IsArrow=*/true, MemberLookup);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009882
Pavel Labath58934982013-08-30 08:52:28 +00009883 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
Sebastian Redl22653ba2011-08-30 19:58:05 +00009884 "Member reference with rvalue base must be rvalue except for reference "
9885 "members, which aren't allowed for move assignment.");
9886
Sebastian Redl22653ba2011-08-30 19:58:05 +00009887 // Build the move of this field.
Richard Smith41ae3282012-11-14 00:50:40 +00009888 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath58934982013-08-30 08:52:28 +00009889 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +00009890 /*CopyingBaseSubobject=*/false,
9891 /*Copying=*/false);
9892 if (Move.isInvalid()) {
9893 Diag(CurrentLocation, diag::note_member_synthesized_at)
9894 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9895 MoveAssignOperator->setInvalidDecl();
9896 return;
9897 }
Richard Smith11d19592012-11-12 23:33:00 +00009898
Sebastian Redl22653ba2011-08-30 19:58:05 +00009899 // Success! Record the copy.
9900 Statements.push_back(Move.takeAs<Stmt>());
9901 }
9902
9903 if (!Invalid) {
9904 // Add a "return *this;"
Pavel Labath58934982013-08-30 08:52:28 +00009905 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
Sebastian Redl22653ba2011-08-30 19:58:05 +00009906
9907 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
9908 if (Return.isInvalid())
9909 Invalid = true;
9910 else {
9911 Statements.push_back(Return.takeAs<Stmt>());
9912
9913 if (Trap.hasErrorOccurred()) {
9914 Diag(CurrentLocation, diag::note_member_synthesized_at)
9915 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9916 Invalid = true;
9917 }
9918 }
9919 }
9920
9921 if (Invalid) {
9922 MoveAssignOperator->setInvalidDecl();
9923 return;
9924 }
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009925
9926 StmtResult Body;
9927 {
9928 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00009929 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009930 /*isStmtExpr=*/false);
9931 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9932 }
Sebastian Redl22653ba2011-08-30 19:58:05 +00009933 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
9934
9935 if (ASTMutationListener *L = getASTMutationListener()) {
9936 L->CompletedImplicitDefinition(MoveAssignOperator);
9937 }
9938}
9939
Richard Smithd3b5c9082012-07-27 04:22:15 +00009940Sema::ImplicitExceptionSpecification
9941Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
9942 CXXRecordDecl *ClassDecl = MD->getParent();
9943
9944 ImplicitExceptionSpecification ExceptSpec(*this);
9945 if (ClassDecl->isInvalidDecl())
9946 return ExceptSpec;
9947
9948 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00009949 assert(T->getNumParams() >= 1 && "not a copy ctor");
9950 unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers();
Richard Smithd3b5c9082012-07-27 04:22:15 +00009951
Douglas Gregor8453ddb2010-07-01 20:59:04 +00009952 // C++ [except.spec]p14:
9953 // An implicitly declared special member function (Clause 12) shall have an
9954 // exception-specification. [...]
Aaron Ballman574705e2014-03-13 15:41:46 +00009955 for (const auto &Base : ClassDecl->bases()) {
Douglas Gregor8453ddb2010-07-01 20:59:04 +00009956 // Virtual bases are handled below.
Aaron Ballman574705e2014-03-13 15:41:46 +00009957 if (Base.isVirtual())
Douglas Gregor8453ddb2010-07-01 20:59:04 +00009958 continue;
9959
Douglas Gregora6d69502010-07-02 23:41:54 +00009960 CXXRecordDecl *BaseClassDecl
Aaron Ballman574705e2014-03-13 15:41:46 +00009961 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +00009962 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +00009963 LookupCopyingConstructor(BaseClassDecl, Quals))
Aaron Ballman574705e2014-03-13 15:41:46 +00009964 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +00009965 }
Aaron Ballman445a9392014-03-13 16:15:17 +00009966 for (const auto &Base : ClassDecl->vbases()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00009967 CXXRecordDecl *BaseClassDecl
Aaron Ballman445a9392014-03-13 16:15:17 +00009968 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +00009969 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +00009970 LookupCopyingConstructor(BaseClassDecl, Quals))
Aaron Ballman445a9392014-03-13 16:15:17 +00009971 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +00009972 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009973 for (const auto *Field : ClassDecl->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00009974 QualType FieldType = Context.getBaseElementType(Field->getType());
Alexis Hunt899bd442011-06-10 04:44:37 +00009975 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9976 if (CXXConstructorDecl *CopyConstructor =
Richard Smith1c6461e2012-07-18 03:36:00 +00009977 LookupCopyingConstructor(FieldClassDecl,
9978 Quals | FieldType.getCVRQualifiers()))
Richard Smithf623c962012-04-17 00:58:00 +00009979 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +00009980 }
9981 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00009982
Richard Smithd3b5c9082012-07-27 04:22:15 +00009983 return ExceptSpec;
Alexis Hunt913820d2011-05-13 06:10:58 +00009984}
9985
9986CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
9987 CXXRecordDecl *ClassDecl) {
9988 // C++ [class.copy]p4:
9989 // If the class definition does not explicitly declare a copy
9990 // constructor, one is declared implicitly.
Richard Smith2be35f52012-12-01 02:35:44 +00009991 assert(ClassDecl->needsImplicitCopyConstructor());
Alexis Hunt913820d2011-05-13 06:10:58 +00009992
Richard Smith8bf22e52012-11-29 01:34:07 +00009993 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
9994 if (DSM.isAlreadyBeingDeclared())
9995 return 0;
9996
Alexis Hunt913820d2011-05-13 06:10:58 +00009997 QualType ClassType = Context.getTypeDeclType(ClassDecl);
9998 QualType ArgType = ClassType;
Richard Smith1c33fe82012-11-28 06:23:12 +00009999 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
Alexis Hunt913820d2011-05-13 06:10:58 +000010000 if (Const)
10001 ArgType = ArgType.withConst();
10002 ArgType = Context.getLValueReferenceType(ArgType);
Alexis Hunt913820d2011-05-13 06:10:58 +000010003
Richard Smithb5800092012-06-10 05:43:50 +000010004 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10005 CXXCopyConstructor,
10006 Const);
10007
Douglas Gregor54be3392010-07-01 17:57:27 +000010008 DeclarationName Name
10009 = Context.DeclarationNames.getCXXConstructorName(
10010 Context.getCanonicalType(ClassType));
Abramo Bagnaradff19302011-03-08 08:55:46 +000010011 SourceLocation ClassLoc = ClassDecl->getLocation();
10012 DeclarationNameInfo NameInfo(Name, ClassLoc);
Alexis Hunt913820d2011-05-13 06:10:58 +000010013
10014 // An implicitly-declared copy constructor is an inline public
Richard Smithcc36f692011-12-22 02:22:31 +000010015 // member of its class.
10016 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
Richard Smithd3b5c9082012-07-27 04:22:15 +000010017 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smithcc36f692011-12-22 02:22:31 +000010018 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smithb5800092012-06-10 05:43:50 +000010019 Constexpr);
Douglas Gregor54be3392010-07-01 17:57:27 +000010020 CopyConstructor->setAccess(AS_public);
Alexis Hunt913820d2011-05-13 06:10:58 +000010021 CopyConstructor->setDefaulted();
Richard Smithcc36f692011-12-22 02:22:31 +000010022
Richard Smithd3b5c9082012-07-27 04:22:15 +000010023 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000010024 FunctionProtoType::ExtProtoInfo EPI =
10025 getImplicitMethodEPI(*this, CopyConstructor);
Richard Smithd3b5c9082012-07-27 04:22:15 +000010026 CopyConstructor->setType(
Jordan Rose5c382722013-03-08 21:51:21 +000010027 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000010028
Douglas Gregor54be3392010-07-01 17:57:27 +000010029 // Add the parameter to the constructor.
10030 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaradff19302011-03-08 08:55:46 +000010031 ClassLoc, ClassLoc,
Douglas Gregor54be3392010-07-01 17:57:27 +000010032 /*IdentifierInfo=*/0,
10033 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +000010034 SC_None, 0);
David Blaikie9c70e042011-09-21 18:16:56 +000010035 CopyConstructor->setParams(FromParam);
Alexis Hunt913820d2011-05-13 06:10:58 +000010036
Richard Smith6b02d462012-12-08 08:32:28 +000010037 CopyConstructor->setTrivial(
10038 ClassDecl->needsOverloadResolutionForCopyConstructor()
10039 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
10040 : ClassDecl->hasTrivialCopyConstructor());
Alexis Hunte77a28f2011-05-18 03:41:58 +000010041
Richard Smith852265f2012-03-30 20:53:28 +000010042 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Richard Smithb4d2a152013-04-02 19:38:47 +000010043 SetDeclDeleted(CopyConstructor, ClassLoc);
Richard Smith852265f2012-03-30 20:53:28 +000010044
Richard Smith6b02d462012-12-08 08:32:28 +000010045 // Note that we have declared this constructor.
10046 ++ASTContext::NumImplicitCopyConstructorsDeclared;
10047
10048 if (Scope *S = getScopeForContext(ClassDecl))
10049 PushOnScopeChains(CopyConstructor, S, false);
10050 ClassDecl->addDecl(CopyConstructor);
10051
Douglas Gregor54be3392010-07-01 17:57:27 +000010052 return CopyConstructor;
10053}
10054
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010055void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Alexis Hunt913820d2011-05-13 06:10:58 +000010056 CXXConstructorDecl *CopyConstructor) {
10057 assert((CopyConstructor->isDefaulted() &&
10058 CopyConstructor->isCopyConstructor() &&
Richard Smith273c4e92012-02-26 07:51:39 +000010059 !CopyConstructor->doesThisDeclarationHaveABody() &&
10060 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010061 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +000010062
Anders Carlsson7a0ffdb2010-04-23 16:24:12 +000010063 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010064 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010065
Richard Smithd577fbb2013-06-13 03:23:42 +000010066 // C++11 [class.copy]p7:
Benjamin Kramer60509af2013-09-09 14:48:42 +000010067 // The [definition of an implicitly declared copy constructor] is
Richard Smithd577fbb2013-06-13 03:23:42 +000010068 // deprecated if the class has a user-declared copy assignment operator
10069 // or a user-declared destructor.
10070 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
10071 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
10072
Eli Friedmaneaf34142012-10-18 20:14:08 +000010073 SynthesizedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +000010074 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010075
David Blaikie3fc2f912013-01-17 05:26:25 +000010076 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +000010077 Trap.hasErrorOccurred()) {
Anders Carlsson79111502010-05-01 16:39:01 +000010078 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregor94f9a482010-05-05 05:51:00 +000010079 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson79111502010-05-01 16:39:01 +000010080 CopyConstructor->setInvalidDecl();
Douglas Gregor94f9a482010-05-05 05:51:00 +000010081 } else {
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010082 Sema::CompoundScopeRAII CompoundScope(*this);
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +000010083 CopyConstructor->setBody(ActOnCompoundStmt(
10084 CopyConstructor->getLocation(), CopyConstructor->getLocation(), None,
10085 /*isStmtExpr=*/ false).takeAs<Stmt>());
Anders Carlsson53e1ba92010-04-25 00:52:09 +000010086 }
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +000010087
Eli Friedman276dd182013-09-05 00:02:25 +000010088 CopyConstructor->markUsed(Context);
Sebastian Redlab238a72011-04-24 16:28:06 +000010089 if (ASTMutationListener *L = getASTMutationListener()) {
10090 L->CompletedImplicitDefinition(CopyConstructor);
10091 }
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010092}
10093
Sebastian Redl22653ba2011-08-30 19:58:05 +000010094Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +000010095Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
10096 CXXRecordDecl *ClassDecl = MD->getParent();
10097
Sebastian Redl22653ba2011-08-30 19:58:05 +000010098 // C++ [except.spec]p14:
10099 // An implicitly declared special member function (Clause 12) shall have an
10100 // exception-specification. [...]
Richard Smithf623c962012-04-17 00:58:00 +000010101 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010102 if (ClassDecl->isInvalidDecl())
10103 return ExceptSpec;
10104
10105 // Direct base-class constructors.
Aaron Ballman574705e2014-03-13 15:41:46 +000010106 for (const auto &B : ClassDecl->bases()) {
10107 if (B.isVirtual()) // Handled below.
Sebastian Redl22653ba2011-08-30 19:58:05 +000010108 continue;
10109
Aaron Ballman574705e2014-03-13 15:41:46 +000010110 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000010111 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith1c6461e2012-07-18 03:36:00 +000010112 CXXConstructorDecl *Constructor =
10113 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010114 // If this is a deleted function, add it anyway. This might be conformant
10115 // with the standard. This might not. I'm not sure. It might not matter.
10116 if (Constructor)
Aaron Ballman574705e2014-03-13 15:41:46 +000010117 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010118 }
10119 }
10120
10121 // Virtual base-class constructors.
Aaron Ballman445a9392014-03-13 16:15:17 +000010122 for (const auto &B : ClassDecl->vbases()) {
10123 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000010124 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith1c6461e2012-07-18 03:36:00 +000010125 CXXConstructorDecl *Constructor =
10126 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010127 // If this is a deleted function, add it anyway. This might be conformant
10128 // with the standard. This might not. I'm not sure. It might not matter.
10129 if (Constructor)
Aaron Ballman445a9392014-03-13 16:15:17 +000010130 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010131 }
10132 }
10133
10134 // Field constructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010135 for (const auto *F : ClassDecl->fields()) {
Richard Smith1c6461e2012-07-18 03:36:00 +000010136 QualType FieldType = Context.getBaseElementType(F->getType());
10137 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
10138 CXXConstructorDecl *Constructor =
10139 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010140 // If this is a deleted function, add it anyway. This might be conformant
10141 // with the standard. This might not. I'm not sure. It might not matter.
10142 // In particular, the problem is that this function never gets called. It
10143 // might just be ill-formed because this function attempts to refer to
10144 // a deleted function here.
10145 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +000010146 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010147 }
10148 }
10149
10150 return ExceptSpec;
10151}
10152
10153CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
10154 CXXRecordDecl *ClassDecl) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +000010155 assert(ClassDecl->needsImplicitMoveConstructor());
10156
Richard Smith8bf22e52012-11-29 01:34:07 +000010157 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
10158 if (DSM.isAlreadyBeingDeclared())
10159 return 0;
10160
Sebastian Redl22653ba2011-08-30 19:58:05 +000010161 QualType ClassType = Context.getTypeDeclType(ClassDecl);
10162 QualType ArgType = Context.getRValueReferenceType(ClassType);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010163
Richard Smithb5800092012-06-10 05:43:50 +000010164 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10165 CXXMoveConstructor,
10166 false);
10167
Sebastian Redl22653ba2011-08-30 19:58:05 +000010168 DeclarationName Name
10169 = Context.DeclarationNames.getCXXConstructorName(
10170 Context.getCanonicalType(ClassType));
10171 SourceLocation ClassLoc = ClassDecl->getLocation();
10172 DeclarationNameInfo NameInfo(Name, ClassLoc);
10173
Richard Smith99005e62013-05-07 03:19:20 +000010174 // C++11 [class.copy]p11:
Sebastian Redl22653ba2011-08-30 19:58:05 +000010175 // An implicitly-declared copy/move constructor is an inline public
Richard Smithcc36f692011-12-22 02:22:31 +000010176 // member of its class.
10177 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
Richard Smithd3b5c9082012-07-27 04:22:15 +000010178 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smithcc36f692011-12-22 02:22:31 +000010179 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smithb5800092012-06-10 05:43:50 +000010180 Constexpr);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010181 MoveConstructor->setAccess(AS_public);
10182 MoveConstructor->setDefaulted();
Richard Smithcc36f692011-12-22 02:22:31 +000010183
Richard Smithd3b5c9082012-07-27 04:22:15 +000010184 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000010185 FunctionProtoType::ExtProtoInfo EPI =
10186 getImplicitMethodEPI(*this, MoveConstructor);
Richard Smithd3b5c9082012-07-27 04:22:15 +000010187 MoveConstructor->setType(
Jordan Rose5c382722013-03-08 21:51:21 +000010188 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000010189
Sebastian Redl22653ba2011-08-30 19:58:05 +000010190 // Add the parameter to the constructor.
10191 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
10192 ClassLoc, ClassLoc,
10193 /*IdentifierInfo=*/0,
10194 ArgType, /*TInfo=*/0,
Sebastian Redl22653ba2011-08-30 19:58:05 +000010195 SC_None, 0);
David Blaikie9c70e042011-09-21 18:16:56 +000010196 MoveConstructor->setParams(FromParam);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010197
Richard Smith6b02d462012-12-08 08:32:28 +000010198 MoveConstructor->setTrivial(
10199 ClassDecl->needsOverloadResolutionForMoveConstructor()
10200 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
10201 : ClassDecl->hasTrivialMoveConstructor());
10202
Alexis Hunt77c1f9f2011-10-11 06:43:29 +000010203 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Richard Smith8b86f2d2013-11-04 01:48:18 +000010204 ClassDecl->setImplicitMoveConstructorIsDeleted();
10205 SetDeclDeleted(MoveConstructor, ClassLoc);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010206 }
10207
10208 // Note that we have declared this constructor.
10209 ++ASTContext::NumImplicitMoveConstructorsDeclared;
10210
10211 if (Scope *S = getScopeForContext(ClassDecl))
10212 PushOnScopeChains(MoveConstructor, S, false);
10213 ClassDecl->addDecl(MoveConstructor);
10214
10215 return MoveConstructor;
10216}
10217
10218void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
10219 CXXConstructorDecl *MoveConstructor) {
10220 assert((MoveConstructor->isDefaulted() &&
10221 MoveConstructor->isMoveConstructor() &&
Richard Smith273c4e92012-02-26 07:51:39 +000010222 !MoveConstructor->doesThisDeclarationHaveABody() &&
10223 !MoveConstructor->isDeleted()) &&
Sebastian Redl22653ba2011-08-30 19:58:05 +000010224 "DefineImplicitMoveConstructor - call it for implicit move ctor");
10225
10226 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
10227 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
10228
Eli Friedmaneaf34142012-10-18 20:14:08 +000010229 SynthesizedFunctionScope Scope(*this, MoveConstructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010230 DiagnosticErrorTrap Trap(Diags);
10231
David Blaikie3fc2f912013-01-17 05:26:25 +000010232 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
Sebastian Redl22653ba2011-08-30 19:58:05 +000010233 Trap.hasErrorOccurred()) {
10234 Diag(CurrentLocation, diag::note_member_synthesized_at)
10235 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
10236 MoveConstructor->setInvalidDecl();
10237 } else {
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010238 Sema::CompoundScopeRAII CompoundScope(*this);
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +000010239 MoveConstructor->setBody(ActOnCompoundStmt(
10240 MoveConstructor->getLocation(), MoveConstructor->getLocation(), None,
10241 /*isStmtExpr=*/ false).takeAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010242 }
10243
Eli Friedman276dd182013-09-05 00:02:25 +000010244 MoveConstructor->markUsed(Context);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010245
10246 if (ASTMutationListener *L = getASTMutationListener()) {
10247 L->CompletedImplicitDefinition(MoveConstructor);
10248 }
10249}
10250
Douglas Gregor74f7d502012-02-15 19:33:52 +000010251bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
Eli Friedmanebea0f22013-07-18 23:29:14 +000010252 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
Douglas Gregor74f7d502012-02-15 19:33:52 +000010253}
Douglas Gregord3b672c2012-02-16 01:06:16 +000010254
10255void Sema::DefineImplicitLambdaToFunctionPointerConversion(
Faisal Vali571df122013-09-29 08:45:24 +000010256 SourceLocation CurrentLocation,
10257 CXXConversionDecl *Conv) {
10258 CXXRecordDecl *Lambda = Conv->getParent();
10259 CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
10260 // If we are defining a specialization of a conversion to function-ptr
10261 // cache the deduced template arguments for this specialization
10262 // so that we can use them to retrieve the corresponding call-operator
10263 // and static-invoker.
10264 const TemplateArgumentList *DeducedTemplateArgs = 0;
10265
Douglas Gregor355efbb2012-02-17 03:02:34 +000010266
Faisal Vali571df122013-09-29 08:45:24 +000010267 // Retrieve the corresponding call-operator specialization.
10268 if (Lambda->isGenericLambda()) {
10269 assert(Conv->isFunctionTemplateSpecialization());
10270 FunctionTemplateDecl *CallOpTemplate =
10271 CallOp->getDescribedFunctionTemplate();
10272 DeducedTemplateArgs = Conv->getTemplateSpecializationArgs();
10273 void *InsertPos = 0;
10274 FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization(
10275 DeducedTemplateArgs->data(),
10276 DeducedTemplateArgs->size(),
10277 InsertPos);
10278 assert(CallOpSpec &&
10279 "Conversion operator must have a corresponding call operator");
10280 CallOp = cast<CXXMethodDecl>(CallOpSpec);
10281 }
10282 // Mark the call operator referenced (and add to pending instantiations
10283 // if necessary).
10284 // For both the conversion and static-invoker template specializations
10285 // we construct their body's in this function, so no need to add them
10286 // to the PendingInstantiations.
10287 MarkFunctionReferenced(CurrentLocation, CallOp);
10288
Eli Friedmaneaf34142012-10-18 20:14:08 +000010289 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregord3b672c2012-02-16 01:06:16 +000010290 DiagnosticErrorTrap Trap(Diags);
Faisal Vali571df122013-09-29 08:45:24 +000010291
Alp Tokerf6a24ce2013-12-05 16:25:25 +000010292 // Retrieve the static invoker...
Faisal Vali571df122013-09-29 08:45:24 +000010293 CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker();
10294 // ... and get the corresponding specialization for a generic lambda.
10295 if (Lambda->isGenericLambda()) {
10296 assert(DeducedTemplateArgs &&
10297 "Must have deduced template arguments from Conversion Operator");
10298 FunctionTemplateDecl *InvokeTemplate =
10299 Invoker->getDescribedFunctionTemplate();
10300 void *InsertPos = 0;
10301 FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization(
10302 DeducedTemplateArgs->data(),
10303 DeducedTemplateArgs->size(),
10304 InsertPos);
10305 assert(InvokeSpec &&
10306 "Must have a corresponding static invoker specialization");
10307 Invoker = cast<CXXMethodDecl>(InvokeSpec);
10308 }
10309 // Construct the body of the conversion function { return __invoke; }.
10310 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
10311 VK_LValue, Conv->getLocation()).take();
10312 assert(FunctionRef && "Can't refer to __invoke function?");
10313 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
10314 Conv->setBody(new (Context) CompoundStmt(Context, Return,
10315 Conv->getLocation(),
10316 Conv->getLocation()));
10317
10318 Conv->markUsed(Context);
10319 Conv->setReferenced();
Douglas Gregord3b672c2012-02-16 01:06:16 +000010320
Faisal Vali571df122013-09-29 08:45:24 +000010321 // Fill in the __invoke function with a dummy implementation. IR generation
10322 // will fill in the actual details.
10323 Invoker->markUsed(Context);
10324 Invoker->setReferenced();
10325 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
10326
Douglas Gregord3b672c2012-02-16 01:06:16 +000010327 if (ASTMutationListener *L = getASTMutationListener()) {
10328 L->CompletedImplicitDefinition(Conv);
Faisal Vali571df122013-09-29 08:45:24 +000010329 L->CompletedImplicitDefinition(Invoker);
10330 }
Douglas Gregord3b672c2012-02-16 01:06:16 +000010331}
10332
Faisal Vali571df122013-09-29 08:45:24 +000010333
10334
Douglas Gregord3b672c2012-02-16 01:06:16 +000010335void Sema::DefineImplicitLambdaToBlockPointerConversion(
10336 SourceLocation CurrentLocation,
10337 CXXConversionDecl *Conv)
10338{
Faisal Vali850da1a2013-09-29 17:08:32 +000010339 assert(!Conv->getParent()->isGenericLambda());
Faisal Vali571df122013-09-29 08:45:24 +000010340
Eli Friedman276dd182013-09-05 00:02:25 +000010341 Conv->markUsed(Context);
Douglas Gregord3b672c2012-02-16 01:06:16 +000010342
Eli Friedmaneaf34142012-10-18 20:14:08 +000010343 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregord3b672c2012-02-16 01:06:16 +000010344 DiagnosticErrorTrap Trap(Diags);
10345
Douglas Gregored90df32012-02-22 05:02:47 +000010346 // Copy-initialize the lambda object as needed to capture it.
Douglas Gregord3b672c2012-02-16 01:06:16 +000010347 Expr *This = ActOnCXXThis(CurrentLocation).take();
10348 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
Douglas Gregord3b672c2012-02-16 01:06:16 +000010349
Eli Friedman98b01ed2012-03-01 04:01:32 +000010350 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
10351 Conv->getLocation(),
10352 Conv, DerefThis);
10353
10354 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
10355 // behavior. Note that only the general conversion function does this
10356 // (since it's unusable otherwise); in the case where we inline the
10357 // block literal, it has block literal lifetime semantics.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010358 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman98b01ed2012-03-01 04:01:32 +000010359 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
10360 CK_CopyAndAutoreleaseBlockObject,
10361 BuildBlock.get(), 0, VK_RValue);
10362
10363 if (BuildBlock.isInvalid()) {
Douglas Gregord3b672c2012-02-16 01:06:16 +000010364 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregored90df32012-02-22 05:02:47 +000010365 Conv->setInvalidDecl();
10366 return;
Douglas Gregord3b672c2012-02-16 01:06:16 +000010367 }
Douglas Gregored90df32012-02-22 05:02:47 +000010368
Douglas Gregored90df32012-02-22 05:02:47 +000010369 // Create the return statement that returns the block from the conversion
10370 // function.
Eli Friedman98b01ed2012-03-01 04:01:32 +000010371 StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregored90df32012-02-22 05:02:47 +000010372 if (Return.isInvalid()) {
10373 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
10374 Conv->setInvalidDecl();
10375 return;
10376 }
10377
10378 // Set the body of the conversion function.
10379 Stmt *ReturnS = Return.take();
Nico Webera2a0eb92012-12-29 20:03:39 +000010380 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
Douglas Gregored90df32012-02-22 05:02:47 +000010381 Conv->getLocation(),
Douglas Gregord3b672c2012-02-16 01:06:16 +000010382 Conv->getLocation()));
10383
Douglas Gregored90df32012-02-22 05:02:47 +000010384 // We're done; notify the mutation listener, if any.
Douglas Gregord3b672c2012-02-16 01:06:16 +000010385 if (ASTMutationListener *L = getASTMutationListener()) {
10386 L->CompletedImplicitDefinition(Conv);
10387 }
10388}
10389
Douglas Gregord2f70072012-03-10 06:53:13 +000010390/// \brief Determine whether the given list arguments contains exactly one
10391/// "real" (non-default) argument.
10392static bool hasOneRealArgument(MultiExprArg Args) {
10393 switch (Args.size()) {
10394 case 0:
10395 return false;
10396
10397 default:
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010398 if (!Args[1]->isDefaultArgument())
Douglas Gregord2f70072012-03-10 06:53:13 +000010399 return false;
10400
10401 // fall through
10402 case 1:
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010403 return !Args[0]->isDefaultArgument();
Douglas Gregord2f70072012-03-10 06:53:13 +000010404 }
10405
10406 return false;
10407}
10408
John McCalldadc5752010-08-24 06:29:42 +000010409ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +000010410Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +000010411 CXXConstructorDecl *Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +000010412 MultiExprArg ExprArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010413 bool HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000010414 bool IsListInitialization,
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010415 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +000010416 unsigned ConstructKind,
10417 SourceRange ParenRange) {
Anders Carlsson250aada2009-08-16 05:13:48 +000010418 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +000010419
Douglas Gregor45cf7e32010-04-02 18:24:57 +000010420 // C++0x [class.copy]p34:
10421 // When certain criteria are met, an implementation is allowed to
10422 // omit the copy/move construction of a class object, even if the
10423 // copy/move constructor and/or destructor for the object have
10424 // side effects. [...]
10425 // - when a temporary class object that has not been bound to a
10426 // reference (12.2) would be copied/moved to a class object
10427 // with the same cv-unqualified type, the copy/move operation
10428 // can be omitted by constructing the temporary object
10429 // directly into the target of the omitted copy/move
John McCall7a626f62010-09-15 10:14:12 +000010430 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregord2f70072012-03-10 06:53:13 +000010431 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000010432 Expr *SubExpr = ExprArgs[0];
John McCall7a626f62010-09-15 10:14:12 +000010433 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson250aada2009-08-16 05:13:48 +000010434 }
Mike Stump11289f42009-09-09 15:08:12 +000010435
10436 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010437 Elidable, ExprArgs, HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000010438 IsListInitialization, RequiresZeroInit,
10439 ConstructKind, ParenRange);
Anders Carlsson250aada2009-08-16 05:13:48 +000010440}
10441
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +000010442/// BuildCXXConstructExpr - Creates a complete call to a constructor,
10443/// including handling of its default argument expressions.
John McCalldadc5752010-08-24 06:29:42 +000010444ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +000010445Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
10446 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor4f4b1862009-12-16 18:50:27 +000010447 MultiExprArg ExprArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010448 bool HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000010449 bool IsListInitialization,
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010450 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +000010451 unsigned ConstructKind,
10452 SourceRange ParenRange) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010453 MarkFunctionReferenced(ConstructLoc, Constructor);
Douglas Gregor85dabae2009-12-16 01:38:02 +000010454 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Benjamin Kramerc215e762012-08-24 11:54:20 +000010455 Constructor, Elidable, ExprArgs,
Richard Smithd59b8322012-12-19 01:39:02 +000010456 HadMultipleCandidates,
10457 IsListInitialization, RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +000010458 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
10459 ParenRange));
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +000010460}
10461
John McCall03c48482010-02-02 09:10:11 +000010462void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth86d17d32011-03-27 21:26:48 +000010463 if (VD->isInvalidDecl()) return;
10464
John McCall03c48482010-02-02 09:10:11 +000010465 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth86d17d32011-03-27 21:26:48 +000010466 if (ClassDecl->isInvalidDecl()) return;
Richard Smitheec915d62012-02-18 04:13:32 +000010467 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth86d17d32011-03-27 21:26:48 +000010468 if (ClassDecl->isDependentContext()) return;
John McCall47e40932010-08-01 20:20:59 +000010469
Chandler Carruth86d17d32011-03-27 21:26:48 +000010470 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedmanfa0df832012-02-02 03:46:19 +000010471 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth86d17d32011-03-27 21:26:48 +000010472 CheckDestructorAccess(VD->getLocation(), Destructor,
10473 PDiag(diag::err_access_dtor_var)
10474 << VD->getDeclName()
10475 << VD->getType());
Richard Smitheec915d62012-02-18 04:13:32 +000010476 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson98766db2011-03-24 01:01:41 +000010477
Chandler Carruth86d17d32011-03-27 21:26:48 +000010478 if (!VD->hasGlobalStorage()) return;
10479
10480 // Emit warning for non-trivial dtor in global scope (a real global,
10481 // class-static, function-static).
10482 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
10483
10484 // TODO: this should be re-enabled for static locals by !CXAAtExit
10485 if (!VD->isStaticLocal())
10486 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +000010487}
10488
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010489/// \brief Given a constructor and the set of arguments provided for the
10490/// constructor, convert the arguments and add any required default arguments
10491/// to form a proper call to this constructor.
10492///
10493/// \returns true if an error occurred, false otherwise.
10494bool
10495Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
10496 MultiExprArg ArgsPtr,
Richard Smith55ce3522012-06-25 20:30:08 +000010497 SourceLocation Loc,
Benjamin Kramerf0623432012-08-23 22:51:59 +000010498 SmallVectorImpl<Expr*> &ConvertedArgs,
Richard Smith6b216962013-02-05 05:52:24 +000010499 bool AllowExplicit,
10500 bool IsListInitialization) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010501 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
10502 unsigned NumArgs = ArgsPtr.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000010503 Expr **Args = ArgsPtr.data();
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010504
10505 const FunctionProtoType *Proto
10506 = Constructor->getType()->getAs<FunctionProtoType>();
10507 assert(Proto && "Constructor without a prototype?");
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000010508 unsigned NumParams = Proto->getNumParams();
Alp Toker9cacbab2014-01-20 20:26:09 +000010509
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010510 // If too few arguments are available, we'll fill in the rest with defaults.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000010511 if (NumArgs < NumParams)
10512 ConvertedArgs.reserve(NumParams);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000010513 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010514 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000010515
10516 VariadicCallType CallType =
10517 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010518 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000010519 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010520 Proto, 0,
10521 llvm::makeArrayRef(Args, NumArgs),
10522 AllArgs,
Richard Smith6b216962013-02-05 05:52:24 +000010523 CallType, AllowExplicit,
10524 IsListInitialization);
Benjamin Kramer8001f742012-02-14 12:06:21 +000010525 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmanff4b4072012-02-18 04:48:30 +000010526
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010527 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
Eli Friedmanff4b4072012-02-18 04:48:30 +000010528
Dmitri Gribenko765396f2013-01-13 20:46:02 +000010529 CheckConstructorCall(Constructor,
10530 llvm::makeArrayRef<const Expr *>(AllArgs.data(),
10531 AllArgs.size()),
Richard Smith55ce3522012-06-25 20:30:08 +000010532 Proto, Loc);
Eli Friedmanff4b4072012-02-18 04:48:30 +000010533
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000010534 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +000010535}
10536
Anders Carlssone363c8e2009-12-12 00:32:00 +000010537static inline bool
10538CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
10539 const FunctionDecl *FnDecl) {
Sebastian Redl50c68252010-08-31 00:36:30 +000010540 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlssone363c8e2009-12-12 00:32:00 +000010541 if (isa<NamespaceDecl>(DC)) {
10542 return SemaRef.Diag(FnDecl->getLocation(),
10543 diag::err_operator_new_delete_declared_in_namespace)
10544 << FnDecl->getDeclName();
10545 }
10546
10547 if (isa<TranslationUnitDecl>(DC) &&
John McCall8e7d6562010-08-26 03:08:43 +000010548 FnDecl->getStorageClass() == SC_Static) {
Anders Carlssone363c8e2009-12-12 00:32:00 +000010549 return SemaRef.Diag(FnDecl->getLocation(),
10550 diag::err_operator_new_delete_declared_static)
10551 << FnDecl->getDeclName();
10552 }
10553
Anders Carlsson60659a82009-12-12 02:43:16 +000010554 return false;
Anders Carlssone363c8e2009-12-12 00:32:00 +000010555}
10556
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010557static inline bool
10558CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
10559 CanQualType ExpectedResultType,
10560 CanQualType ExpectedFirstParamType,
10561 unsigned DependentParamTypeDiag,
10562 unsigned InvalidParamTypeDiag) {
Alp Toker314cc812014-01-25 16:55:45 +000010563 QualType ResultType =
10564 FnDecl->getType()->getAs<FunctionType>()->getReturnType();
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010565
10566 // Check that the result type is not dependent.
10567 if (ResultType->isDependentType())
10568 return SemaRef.Diag(FnDecl->getLocation(),
10569 diag::err_operator_new_delete_dependent_result_type)
10570 << FnDecl->getDeclName() << ExpectedResultType;
10571
10572 // Check that the result type is what we expect.
10573 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
10574 return SemaRef.Diag(FnDecl->getLocation(),
10575 diag::err_operator_new_delete_invalid_result_type)
10576 << FnDecl->getDeclName() << ExpectedResultType;
10577
10578 // A function template must have at least 2 parameters.
10579 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
10580 return SemaRef.Diag(FnDecl->getLocation(),
10581 diag::err_operator_new_delete_template_too_few_parameters)
10582 << FnDecl->getDeclName();
10583
10584 // The function decl must have at least 1 parameter.
10585 if (FnDecl->getNumParams() == 0)
10586 return SemaRef.Diag(FnDecl->getLocation(),
10587 diag::err_operator_new_delete_too_few_parameters)
10588 << FnDecl->getDeclName();
10589
Sylvestre Ledru830885c2012-07-23 08:59:39 +000010590 // Check the first parameter type is not dependent.
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010591 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
10592 if (FirstParamType->isDependentType())
10593 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
10594 << FnDecl->getDeclName() << ExpectedFirstParamType;
10595
10596 // Check that the first parameter type is what we expect.
Douglas Gregor684d7bd2009-12-22 23:42:49 +000010597 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010598 ExpectedFirstParamType)
10599 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
10600 << FnDecl->getDeclName() << ExpectedFirstParamType;
10601
10602 return false;
10603}
10604
Anders Carlsson12308f42009-12-11 23:23:22 +000010605static bool
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010606CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlssone363c8e2009-12-12 00:32:00 +000010607 // C++ [basic.stc.dynamic.allocation]p1:
10608 // A program is ill-formed if an allocation function is declared in a
10609 // namespace scope other than global scope or declared static in global
10610 // scope.
10611 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10612 return true;
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010613
10614 CanQualType SizeTy =
10615 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
10616
10617 // C++ [basic.stc.dynamic.allocation]p1:
10618 // The return type shall be void*. The first parameter shall have type
10619 // std::size_t.
10620 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
10621 SizeTy,
10622 diag::err_operator_new_dependent_param_type,
10623 diag::err_operator_new_param_type))
10624 return true;
10625
10626 // C++ [basic.stc.dynamic.allocation]p1:
10627 // The first parameter shall not have an associated default argument.
10628 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlsson22f443f2009-12-12 00:26:23 +000010629 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010630 diag::err_operator_new_default_arg)
10631 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
10632
10633 return false;
Anders Carlsson22f443f2009-12-12 00:26:23 +000010634}
10635
10636static bool
Richard Smith66f3ac92012-10-20 08:26:51 +000010637CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
Anders Carlsson12308f42009-12-11 23:23:22 +000010638 // C++ [basic.stc.dynamic.deallocation]p1:
10639 // A program is ill-formed if deallocation functions are declared in a
10640 // namespace scope other than global scope or declared static in global
10641 // scope.
Anders Carlssone363c8e2009-12-12 00:32:00 +000010642 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10643 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +000010644
10645 // C++ [basic.stc.dynamic.deallocation]p2:
10646 // Each deallocation function shall return void and its first parameter
10647 // shall be void*.
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010648 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
10649 SemaRef.Context.VoidPtrTy,
10650 diag::err_operator_delete_dependent_param_type,
10651 diag::err_operator_delete_param_type))
10652 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +000010653
Anders Carlsson12308f42009-12-11 23:23:22 +000010654 return false;
10655}
10656
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010657/// CheckOverloadedOperatorDeclaration - Check whether the declaration
10658/// of this overloaded operator is well-formed. If so, returns false;
10659/// otherwise, emits appropriate diagnostics and returns true.
10660bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +000010661 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010662 "Expected an overloaded operator declaration");
10663
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010664 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
10665
Mike Stump11289f42009-09-09 15:08:12 +000010666 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010667 // The allocation and deallocation functions, operator new,
10668 // operator new[], operator delete and operator delete[], are
10669 // described completely in 3.7.3. The attributes and restrictions
10670 // found in the rest of this subclause do not apply to them unless
10671 // explicitly stated in 3.7.3.
Anders Carlssonf1f46952009-12-11 23:31:21 +000010672 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson12308f42009-12-11 23:23:22 +000010673 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanian4e088942009-11-10 23:47:18 +000010674
Anders Carlsson22f443f2009-12-12 00:26:23 +000010675 if (Op == OO_New || Op == OO_Array_New)
10676 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010677
10678 // C++ [over.oper]p6:
10679 // An operator function shall either be a non-static member
10680 // function or be a non-member function and have at least one
10681 // parameter whose type is a class, a reference to a class, an
10682 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +000010683 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
10684 if (MethodDecl->isStatic())
10685 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000010686 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010687 } else {
10688 bool ClassOrEnumParam = false;
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000010689 for (auto Param : FnDecl->params()) {
10690 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +000010691 if (ParamType->isDependentType() || ParamType->isRecordType() ||
10692 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010693 ClassOrEnumParam = true;
10694 break;
10695 }
10696 }
10697
Douglas Gregord69246b2008-11-17 16:14:12 +000010698 if (!ClassOrEnumParam)
10699 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +000010700 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000010701 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010702 }
10703
10704 // C++ [over.oper]p8:
10705 // An operator function cannot have default arguments (8.3.6),
10706 // except where explicitly stated below.
10707 //
Mike Stump11289f42009-09-09 15:08:12 +000010708 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010709 // (C++ [over.call]p1).
10710 if (Op != OO_Call) {
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000010711 for (auto Param : FnDecl->params()) {
10712 if (Param->hasDefaultArg())
10713 return Diag(Param->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +000010714 diag::err_operator_overload_default_arg)
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000010715 << FnDecl->getDeclName() << Param->getDefaultArgRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010716 }
10717 }
10718
Douglas Gregor6cf08062008-11-10 13:38:07 +000010719 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
10720 { false, false, false }
10721#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
10722 , { Unary, Binary, MemberOnly }
10723#include "clang/Basic/OperatorKinds.def"
10724 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010725
Douglas Gregor6cf08062008-11-10 13:38:07 +000010726 bool CanBeUnaryOperator = OperatorUses[Op][0];
10727 bool CanBeBinaryOperator = OperatorUses[Op][1];
10728 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010729
10730 // C++ [over.oper]p8:
10731 // [...] Operator functions cannot have more or fewer parameters
10732 // than the number required for the corresponding operator, as
10733 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +000010734 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +000010735 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010736 if (Op != OO_Call &&
10737 ((NumParams == 1 && !CanBeUnaryOperator) ||
10738 (NumParams == 2 && !CanBeBinaryOperator) ||
10739 (NumParams < 1) || (NumParams > 2))) {
10740 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000010741 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +000010742 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000010743 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +000010744 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000010745 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +000010746 } else {
Chris Lattner2b786902008-11-21 07:50:02 +000010747 assert(CanBeBinaryOperator &&
10748 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000010749 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +000010750 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010751
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000010752 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000010753 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010754 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +000010755
Douglas Gregord69246b2008-11-17 16:14:12 +000010756 // Overloaded operators other than operator() cannot be variadic.
10757 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +000010758 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +000010759 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000010760 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010761 }
10762
10763 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +000010764 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
10765 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +000010766 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000010767 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010768 }
10769
10770 // C++ [over.inc]p1:
10771 // The user-defined function called operator++ implements the
10772 // prefix and postfix ++ operator. If this function is a member
10773 // function with no parameters, or a non-member function with one
10774 // parameter of class or enumeration type, it defines the prefix
10775 // increment operator ++ for objects of that type. If the function
10776 // is a member function with one parameter (which shall be of type
10777 // int) or a non-member function with two parameters (the second
10778 // of which shall be of type int), it defines the postfix
10779 // increment operator ++ for objects of that type.
10780 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
10781 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
Richard Smith538b52a2014-01-30 22:24:05 +000010782 QualType ParamType = LastParam->getType();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010783
Richard Smith538b52a2014-01-30 22:24:05 +000010784 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
10785 !ParamType->isDependentType())
Chris Lattner2b786902008-11-21 07:50:02 +000010786 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +000010787 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +000010788 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010789 }
10790
Douglas Gregord69246b2008-11-17 16:14:12 +000010791 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010792}
Chris Lattner3b024a32008-12-17 07:09:26 +000010793
Alexis Huntc88db062010-01-13 09:01:02 +000010794/// CheckLiteralOperatorDeclaration - Check whether the declaration
10795/// of this literal operator function is well-formed. If so, returns
10796/// false; otherwise, emits appropriate diagnostics and returns true.
10797bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smith5731c752012-03-10 22:18:57 +000010798 if (isa<CXXMethodDecl>(FnDecl)) {
Alexis Huntc88db062010-01-13 09:01:02 +000010799 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
10800 << FnDecl->getDeclName();
10801 return true;
10802 }
10803
Richard Smith72eebee2012-03-04 09:41:16 +000010804 if (FnDecl->isExternC()) {
10805 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
10806 return true;
10807 }
10808
Alexis Huntc88db062010-01-13 09:01:02 +000010809 bool Valid = false;
10810
Richard Smithbcc22fc2012-03-09 08:00:36 +000010811 // This might be the definition of a literal operator template.
10812 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
10813 // This might be a specialization of a literal operator template.
10814 if (!TpDecl)
10815 TpDecl = FnDecl->getPrimaryTemplate();
10816
Richard Smithb8b41d32013-10-07 19:57:58 +000010817 // template <char...> type operator "" name() and
10818 // template <class T, T...> type operator "" name() are the only valid
10819 // template signatures, and the only valid signatures with no parameters.
Richard Smithbcc22fc2012-03-09 08:00:36 +000010820 if (TpDecl) {
Richard Smith72eebee2012-03-04 09:41:16 +000010821 if (FnDecl->param_size() == 0) {
Richard Smithb8b41d32013-10-07 19:57:58 +000010822 // Must have one or two template parameters
Alexis Hunt7dd26172010-04-07 23:11:06 +000010823 TemplateParameterList *Params = TpDecl->getTemplateParameters();
10824 if (Params->size() == 1) {
10825 NonTypeTemplateParmDecl *PmDecl =
Richard Smithed943022012-08-03 21:14:57 +000010826 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Alexis Huntc88db062010-01-13 09:01:02 +000010827
Alexis Hunt7dd26172010-04-07 23:11:06 +000010828 // The template parameter must be a char parameter pack.
Alexis Hunt7dd26172010-04-07 23:11:06 +000010829 if (PmDecl && PmDecl->isTemplateParameterPack() &&
10830 Context.hasSameType(PmDecl->getType(), Context.CharTy))
10831 Valid = true;
Richard Smithb8b41d32013-10-07 19:57:58 +000010832 } else if (Params->size() == 2) {
10833 TemplateTypeParmDecl *PmType =
10834 dyn_cast<TemplateTypeParmDecl>(Params->getParam(0));
10835 NonTypeTemplateParmDecl *PmArgs =
10836 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
10837
10838 // The second template parameter must be a parameter pack with the
10839 // first template parameter as its type.
10840 if (PmType && PmArgs &&
10841 !PmType->isTemplateParameterPack() &&
10842 PmArgs->isTemplateParameterPack()) {
10843 const TemplateTypeParmType *TArgs =
10844 PmArgs->getType()->getAs<TemplateTypeParmType>();
10845 if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
10846 TArgs->getIndex() == PmType->getIndex()) {
10847 Valid = true;
10848 if (ActiveTemplateInstantiations.empty())
10849 Diag(FnDecl->getLocation(),
10850 diag::ext_string_literal_operator_template);
10851 }
10852 }
Alexis Hunt7dd26172010-04-07 23:11:06 +000010853 }
10854 }
Richard Smith72eebee2012-03-04 09:41:16 +000010855 } else if (FnDecl->param_size()) {
Alexis Huntc88db062010-01-13 09:01:02 +000010856 // Check the first parameter
Alexis Hunt7dd26172010-04-07 23:11:06 +000010857 FunctionDecl::param_iterator Param = FnDecl->param_begin();
10858
Richard Smith72eebee2012-03-04 09:41:16 +000010859 QualType T = (*Param)->getType().getUnqualifiedType();
Alexis Huntc88db062010-01-13 09:01:02 +000010860
Alexis Hunt079a6f72010-04-07 22:57:35 +000010861 // unsigned long long int, long double, and any character type are allowed
10862 // as the only parameters.
Alexis Huntc88db062010-01-13 09:01:02 +000010863 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
10864 Context.hasSameType(T, Context.LongDoubleTy) ||
10865 Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg0d81e012013-05-10 10:08:40 +000010866 Context.hasSameType(T, Context.WideCharTy) ||
Alexis Huntc88db062010-01-13 09:01:02 +000010867 Context.hasSameType(T, Context.Char16Ty) ||
10868 Context.hasSameType(T, Context.Char32Ty)) {
10869 if (++Param == FnDecl->param_end())
10870 Valid = true;
10871 goto FinishedParams;
10872 }
10873
Alexis Hunt079a6f72010-04-07 22:57:35 +000010874 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Alexis Huntc88db062010-01-13 09:01:02 +000010875 const PointerType *PT = T->getAs<PointerType>();
10876 if (!PT)
10877 goto FinishedParams;
10878 T = PT->getPointeeType();
Richard Smith72eebee2012-03-04 09:41:16 +000010879 if (!T.isConstQualified() || T.isVolatileQualified())
Alexis Huntc88db062010-01-13 09:01:02 +000010880 goto FinishedParams;
10881 T = T.getUnqualifiedType();
10882
10883 // Move on to the second parameter;
10884 ++Param;
10885
10886 // If there is no second parameter, the first must be a const char *
10887 if (Param == FnDecl->param_end()) {
10888 if (Context.hasSameType(T, Context.CharTy))
10889 Valid = true;
10890 goto FinishedParams;
10891 }
10892
10893 // const char *, const wchar_t*, const char16_t*, and const char32_t*
10894 // are allowed as the first parameter to a two-parameter function
10895 if (!(Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg0d81e012013-05-10 10:08:40 +000010896 Context.hasSameType(T, Context.WideCharTy) ||
Alexis Huntc88db062010-01-13 09:01:02 +000010897 Context.hasSameType(T, Context.Char16Ty) ||
10898 Context.hasSameType(T, Context.Char32Ty)))
10899 goto FinishedParams;
10900
10901 // The second and final parameter must be an std::size_t
10902 T = (*Param)->getType().getUnqualifiedType();
10903 if (Context.hasSameType(T, Context.getSizeType()) &&
10904 ++Param == FnDecl->param_end())
10905 Valid = true;
10906 }
10907
10908 // FIXME: This diagnostic is absolutely terrible.
10909FinishedParams:
10910 if (!Valid) {
10911 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
10912 << FnDecl->getDeclName();
10913 return true;
10914 }
10915
Richard Smith768cecc2012-03-09 08:16:22 +000010916 // A parameter-declaration-clause containing a default argument is not
10917 // equivalent to any of the permitted forms.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000010918 for (auto Param : FnDecl->params()) {
10919 if (Param->hasDefaultArg()) {
10920 Diag(Param->getDefaultArgRange().getBegin(),
Richard Smith768cecc2012-03-09 08:16:22 +000010921 diag::err_literal_operator_default_argument)
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000010922 << Param->getDefaultArgRange();
Richard Smith768cecc2012-03-09 08:16:22 +000010923 break;
10924 }
10925 }
10926
Richard Smith0df56f42012-03-08 02:39:21 +000010927 StringRef LiteralName
Douglas Gregor86325ad2011-08-30 22:40:35 +000010928 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
10929 if (LiteralName[0] != '_') {
Richard Smith0df56f42012-03-08 02:39:21 +000010930 // C++11 [usrlit.suffix]p1:
10931 // Literal suffix identifiers that do not start with an underscore
10932 // are reserved for future standardization.
Richard Smithf4198b72013-07-23 08:14:48 +000010933 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
10934 << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
Douglas Gregor86325ad2011-08-30 22:40:35 +000010935 }
Richard Smith0df56f42012-03-08 02:39:21 +000010936
Alexis Huntc88db062010-01-13 09:01:02 +000010937 return false;
10938}
10939
Douglas Gregor07665a62009-01-05 19:45:36 +000010940/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
10941/// linkage specification, including the language and (if present)
Richard Smith4ee696d2014-02-17 23:25:27 +000010942/// the '{'. ExternLoc is the location of the 'extern', Lang is the
10943/// language string literal. LBraceLoc, if valid, provides the location of
Douglas Gregor07665a62009-01-05 19:45:36 +000010944/// the '{' brace. Otherwise, this linkage specification does not
10945/// have any braces.
Chris Lattner8ea64422010-11-09 20:15:55 +000010946Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
Richard Smith4ee696d2014-02-17 23:25:27 +000010947 Expr *LangStr,
Chris Lattner8ea64422010-11-09 20:15:55 +000010948 SourceLocation LBraceLoc) {
Richard Smith4ee696d2014-02-17 23:25:27 +000010949 StringLiteral *Lit = cast<StringLiteral>(LangStr);
10950 if (!Lit->isAscii()) {
10951 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
10952 << LangStr->getSourceRange();
10953 return 0;
10954 }
10955
10956 StringRef Lang = Lit->getString();
Chris Lattner438e5012008-12-17 07:13:27 +000010957 LinkageSpecDecl::LanguageIDs Language;
Richard Smith4ee696d2014-02-17 23:25:27 +000010958 if (Lang == "C")
Chris Lattner438e5012008-12-17 07:13:27 +000010959 Language = LinkageSpecDecl::lang_c;
Richard Smith4ee696d2014-02-17 23:25:27 +000010960 else if (Lang == "C++")
Chris Lattner438e5012008-12-17 07:13:27 +000010961 Language = LinkageSpecDecl::lang_cxx;
10962 else {
Richard Smith4ee696d2014-02-17 23:25:27 +000010963 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
10964 << LangStr->getSourceRange();
John McCall48871652010-08-21 09:40:31 +000010965 return 0;
Chris Lattner438e5012008-12-17 07:13:27 +000010966 }
Mike Stump11289f42009-09-09 15:08:12 +000010967
Chris Lattner438e5012008-12-17 07:13:27 +000010968 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +000010969
Richard Smith4ee696d2014-02-17 23:25:27 +000010970 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
10971 LangStr->getExprLoc(), Language,
Rafael Espindola327be3c2013-04-26 01:30:23 +000010972 LBraceLoc.isValid());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000010973 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +000010974 PushDeclContext(S, D);
John McCall48871652010-08-21 09:40:31 +000010975 return D;
Chris Lattner438e5012008-12-17 07:13:27 +000010976}
10977
Abramo Bagnaraed5b6892010-07-30 16:47:02 +000010978/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor07665a62009-01-05 19:45:36 +000010979/// the C++ linkage specification LinkageSpec. If RBraceLoc is
10980/// valid, it's the position of the closing '}' brace in a linkage
10981/// specification that uses braces.
John McCall48871652010-08-21 09:40:31 +000010982Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara4a8cda82011-03-03 14:52:38 +000010983 Decl *LinkageSpec,
10984 SourceLocation RBraceLoc) {
Richard Smith4ee696d2014-02-17 23:25:27 +000010985 if (RBraceLoc.isValid()) {
10986 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
10987 LSDecl->setRBraceLoc(RBraceLoc);
Abramo Bagnara4a8cda82011-03-03 14:52:38 +000010988 }
Richard Smith4ee696d2014-02-17 23:25:27 +000010989 PopDeclContext();
Douglas Gregor07665a62009-01-05 19:45:36 +000010990 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +000010991}
10992
Michael Han84324352013-02-22 17:15:32 +000010993Decl *Sema::ActOnEmptyDeclaration(Scope *S,
10994 AttributeList *AttrList,
10995 SourceLocation SemiLoc) {
10996 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
10997 // Attribute declarations appertain to empty declaration so we handle
10998 // them here.
10999 if (AttrList)
11000 ProcessDeclAttributeList(S, ED, AttrList);
Richard Smith54ecd982013-02-20 19:22:51 +000011001
Michael Han84324352013-02-22 17:15:32 +000011002 CurContext->addDecl(ED);
11003 return ED;
Richard Smith54ecd982013-02-20 19:22:51 +000011004}
11005
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011006/// \brief Perform semantic analysis for the variable declaration that
11007/// occurs within a C++ catch clause, returning the newly-created
11008/// variable.
Abramo Bagnaradff19302011-03-08 08:55:46 +000011009VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCallbcd03502009-12-07 02:54:59 +000011010 TypeSourceInfo *TInfo,
Abramo Bagnaradff19302011-03-08 08:55:46 +000011011 SourceLocation StartLoc,
11012 SourceLocation Loc,
11013 IdentifierInfo *Name) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011014 bool Invalid = false;
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000011015 QualType ExDeclType = TInfo->getType();
11016
Sebastian Redl54c04d42008-12-22 19:15:10 +000011017 // Arrays and functions decay.
11018 if (ExDeclType->isArrayType())
11019 ExDeclType = Context.getArrayDecayedType(ExDeclType);
11020 else if (ExDeclType->isFunctionType())
11021 ExDeclType = Context.getPointerType(ExDeclType);
11022
11023 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
11024 // The exception-declaration shall not denote a pointer or reference to an
11025 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +000011026 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +000011027 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000011028 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlb28b4072009-03-22 23:49:27 +000011029 Invalid = true;
11030 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011031
Sebastian Redl54c04d42008-12-22 19:15:10 +000011032 QualType BaseType = ExDeclType;
11033 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +000011034 unsigned DK = diag::err_catch_incomplete;
Ted Kremenekc23c7e62009-07-29 21:53:49 +000011035 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000011036 BaseType = Ptr->getPointeeType();
11037 Mode = 1;
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000011038 DK = diag::err_catch_incomplete_ptr;
Mike Stump11289f42009-09-09 15:08:12 +000011039 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +000011040 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +000011041 BaseType = Ref->getPointeeType();
11042 Mode = 2;
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000011043 DK = diag::err_catch_incomplete_ref;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011044 }
Sebastian Redlb28b4072009-03-22 23:49:27 +000011045 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000011046 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl54c04d42008-12-22 19:15:10 +000011047 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011048
Mike Stump11289f42009-09-09 15:08:12 +000011049 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011050 RequireNonAbstractType(Loc, ExDeclType,
11051 diag::err_abstract_type_in_decl,
11052 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +000011053 Invalid = true;
11054
John McCall2ca705e2010-07-24 00:37:23 +000011055 // Only the non-fragile NeXT runtime currently supports C++ catches
11056 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011057 if (!Invalid && getLangOpts().ObjC1) {
John McCall2ca705e2010-07-24 00:37:23 +000011058 QualType T = ExDeclType;
11059 if (const ReferenceType *RT = T->getAs<ReferenceType>())
11060 T = RT->getPointeeType();
11061
11062 if (T->isObjCObjectType()) {
11063 Diag(Loc, diag::err_objc_object_catch);
11064 Invalid = true;
11065 } else if (T->isObjCObjectPointerType()) {
John McCall5fb5df92012-06-20 06:18:46 +000011066 // FIXME: should this be a test for macosx-fragile specifically?
11067 if (getLangOpts().ObjCRuntime.isFragile())
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +000011068 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall2ca705e2010-07-24 00:37:23 +000011069 }
11070 }
11071
Abramo Bagnaradff19302011-03-08 08:55:46 +000011072 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
Rafael Espindola6ae7e502013-04-03 19:27:57 +000011073 ExDeclType, TInfo, SC_None);
Douglas Gregor3f324d562010-05-03 18:51:14 +000011074 ExDecl->setExceptionVariable(true);
11075
Douglas Gregor8ca0c642011-12-10 01:22:52 +000011076 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011077 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor8ca0c642011-12-10 01:22:52 +000011078 Invalid = true;
11079
Douglas Gregor750734c2011-07-06 18:14:43 +000011080 if (!Invalid && !ExDeclType->isDependentType()) {
John McCall1bf58462011-02-16 08:02:54 +000011081 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
John McCalleaef89b2013-03-22 02:10:40 +000011082 // Insulate this from anything else we might currently be parsing.
11083 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
11084
Douglas Gregor6de584c2010-03-05 23:38:39 +000011085 // C++ [except.handle]p16:
Nick Lewycky0f292892013-09-22 10:06:57 +000011086 // The object declared in an exception-declaration or, if the
11087 // exception-declaration does not specify a name, a temporary (12.2) is
Douglas Gregor6de584c2010-03-05 23:38:39 +000011088 // copy-initialized (8.5) from the exception object. [...]
11089 // The object is destroyed when the handler exits, after the destruction
11090 // of any automatic objects initialized within the handler.
11091 //
Nick Lewycky0f292892013-09-22 10:06:57 +000011092 // We just pretend to initialize the object with itself, then make sure
Douglas Gregor6de584c2010-03-05 23:38:39 +000011093 // it can be destroyed later.
John McCall1bf58462011-02-16 08:02:54 +000011094 QualType initType = ExDeclType;
11095
11096 InitializedEntity entity =
11097 InitializedEntity::InitializeVariable(ExDecl);
11098 InitializationKind initKind =
11099 InitializationKind::CreateCopy(Loc, SourceLocation());
11100
11101 Expr *opaqueValue =
11102 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +000011103 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
11104 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
John McCall1bf58462011-02-16 08:02:54 +000011105 if (result.isInvalid())
Douglas Gregor6de584c2010-03-05 23:38:39 +000011106 Invalid = true;
John McCall1bf58462011-02-16 08:02:54 +000011107 else {
11108 // If the constructor used was non-trivial, set this as the
11109 // "initializer".
Nick Lewycky0f292892013-09-22 10:06:57 +000011110 CXXConstructExpr *construct = result.takeAs<CXXConstructExpr>();
John McCall1bf58462011-02-16 08:02:54 +000011111 if (!construct->getConstructor()->isTrivial()) {
11112 Expr *init = MaybeCreateExprWithCleanups(construct);
11113 ExDecl->setInit(init);
11114 }
11115
11116 // And make sure it's destructable.
11117 FinalizeVarWithDestructor(ExDecl, recordType);
11118 }
Douglas Gregor6de584c2010-03-05 23:38:39 +000011119 }
11120 }
11121
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011122 if (Invalid)
11123 ExDecl->setInvalidDecl();
11124
11125 return ExDecl;
11126}
11127
11128/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
11129/// handler.
John McCall48871652010-08-21 09:40:31 +000011130Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCall8cb7bdf2010-06-04 23:28:52 +000011131 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregor72772f62010-12-16 17:48:04 +000011132 bool Invalid = D.isInvalidType();
11133
11134 // Check for unexpanded parameter packs.
Jordan Rosed03d99d2013-03-05 01:27:54 +000011135 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
11136 UPPC_ExceptionType)) {
Douglas Gregor72772f62010-12-16 17:48:04 +000011137 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
11138 D.getIdentifierLoc());
11139 Invalid = true;
11140 }
11141
Sebastian Redl54c04d42008-12-22 19:15:10 +000011142 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +000011143 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +000011144 LookupOrdinaryName,
11145 ForRedeclaration)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000011146 // The scope should be freshly made just for us. There is just no way
11147 // it contains any previous declaration.
John McCall48871652010-08-21 09:40:31 +000011148 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl54c04d42008-12-22 19:15:10 +000011149 if (PrevDecl->isTemplateParameter()) {
11150 // Maybe we will complain about the shadowed template parameter.
11151 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregorf4ef4d22011-10-20 17:58:49 +000011152 PrevDecl = 0;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011153 }
11154 }
11155
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011156 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000011157 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
11158 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011159 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011160 }
11161
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000011162 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011163 D.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +000011164 D.getIdentifierLoc(),
11165 D.getIdentifier());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011166 if (Invalid)
11167 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +000011168
Sebastian Redl54c04d42008-12-22 19:15:10 +000011169 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +000011170 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011171 PushOnScopeChains(ExDecl, S);
11172 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011173 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +000011174
Douglas Gregor758a8692009-06-17 21:51:59 +000011175 ProcessDeclAttributes(S, ExDecl, D);
John McCall48871652010-08-21 09:40:31 +000011176 return ExDecl;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011177}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000011178
Abramo Bagnaraea947882011-03-08 16:41:52 +000011179Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCallb268a282010-08-23 23:25:46 +000011180 Expr *AssertExpr,
Richard Smithded9c2e2012-07-11 22:37:56 +000011181 Expr *AssertMessageExpr,
Abramo Bagnaraea947882011-03-08 16:41:52 +000011182 SourceLocation RParenLoc) {
Richard Smithded9c2e2012-07-11 22:37:56 +000011183 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr);
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000011184
Richard Smithded9c2e2012-07-11 22:37:56 +000011185 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
11186 return 0;
11187
11188 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
11189 AssertMessage, RParenLoc, false);
11190}
11191
11192Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
11193 Expr *AssertExpr,
11194 StringLiteral *AssertMessage,
11195 SourceLocation RParenLoc,
11196 bool Failed) {
11197 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
11198 !Failed) {
Richard Smithf4c51d92012-02-04 09:53:13 +000011199 // In a static_assert-declaration, the constant-expression shall be a
11200 // constant expression that can be contextually converted to bool.
11201 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
11202 if (Converted.isInvalid())
Richard Smithded9c2e2012-07-11 22:37:56 +000011203 Failed = true;
Richard Smithf4c51d92012-02-04 09:53:13 +000011204
Richard Smith902ca212011-12-14 23:32:26 +000011205 llvm::APSInt Cond;
Richard Smithded9c2e2012-07-11 22:37:56 +000011206 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregore2b37442012-05-04 22:38:52 +000011207 diag::err_static_assert_expression_is_not_constant,
Richard Smithf4c51d92012-02-04 09:53:13 +000011208 /*AllowFold=*/false).isInvalid())
Richard Smithded9c2e2012-07-11 22:37:56 +000011209 Failed = true;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000011210
Richard Smithded9c2e2012-07-11 22:37:56 +000011211 if (!Failed && !Cond) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011212 SmallString<256> MsgBuffer;
Richard Smithf506eaf2012-03-05 23:20:05 +000011213 llvm::raw_svector_ostream Msg(MsgBuffer);
Richard Smith235341b2012-08-16 03:56:14 +000011214 AssertMessage->printPretty(Msg, 0, getPrintingPolicy());
Abramo Bagnaraea947882011-03-08 16:41:52 +000011215 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smithf506eaf2012-03-05 23:20:05 +000011216 << Msg.str() << AssertExpr->getSourceRange();
Richard Smithded9c2e2012-07-11 22:37:56 +000011217 Failed = true;
Richard Smithf506eaf2012-03-05 23:20:05 +000011218 }
Anders Carlsson54b26982009-03-14 00:33:21 +000011219 }
Mike Stump11289f42009-09-09 15:08:12 +000011220
Abramo Bagnaraea947882011-03-08 16:41:52 +000011221 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
Richard Smithded9c2e2012-07-11 22:37:56 +000011222 AssertExpr, AssertMessage, RParenLoc,
11223 Failed);
Mike Stump11289f42009-09-09 15:08:12 +000011224
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011225 CurContext->addDecl(Decl);
John McCall48871652010-08-21 09:40:31 +000011226 return Decl;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000011227}
Sebastian Redlf769df52009-03-24 22:27:57 +000011228
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011229/// \brief Perform semantic analysis of the given friend type declaration.
11230///
11231/// \returns A friend declaration that.
Richard Smitha31a89a2012-09-20 01:31:00 +000011232FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
Abramo Bagnara254b6302011-10-29 20:52:52 +000011233 SourceLocation FriendLoc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011234 TypeSourceInfo *TSInfo) {
11235 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
11236
11237 QualType T = TSInfo->getType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +000011238 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011239
Richard Smithc8239732011-10-18 21:39:00 +000011240 // C++03 [class.friend]p2:
11241 // An elaborated-type-specifier shall be used in a friend declaration
11242 // for a class.*
11243 //
11244 // * The class-key of the elaborated-type-specifier is required.
11245 if (!ActiveTemplateInstantiations.empty()) {
11246 // Do not complain about the form of friend template types during
11247 // template instantiation; we will already have complained when the
11248 // template was declared.
Nick Lewycky36722d22013-02-06 05:59:33 +000011249 } else {
11250 if (!T->isElaboratedTypeSpecifier()) {
11251 // If we evaluated the type to a record type, suggest putting
11252 // a tag in front.
11253 if (const RecordType *RT = T->getAs<RecordType>()) {
11254 RecordDecl *RD = RT->getDecl();
Richard Smithc8239732011-10-18 21:39:00 +000011255
Nick Lewycky36722d22013-02-06 05:59:33 +000011256 std::string InsertionText = std::string(" ") + RD->getKindName();
Richard Smithc8239732011-10-18 21:39:00 +000011257
Nick Lewycky36722d22013-02-06 05:59:33 +000011258 Diag(TypeRange.getBegin(),
11259 getLangOpts().CPlusPlus11 ?
11260 diag::warn_cxx98_compat_unelaborated_friend_type :
11261 diag::ext_unelaborated_friend_type)
11262 << (unsigned) RD->getTagKind()
11263 << T
11264 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
11265 InsertionText);
11266 } else {
11267 Diag(FriendLoc,
11268 getLangOpts().CPlusPlus11 ?
11269 diag::warn_cxx98_compat_nonclass_type_friend :
11270 diag::ext_nonclass_type_friend)
11271 << T
11272 << TypeRange;
11273 }
11274 } else if (T->getAs<EnumType>()) {
Richard Smithc8239732011-10-18 21:39:00 +000011275 Diag(FriendLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011276 getLangOpts().CPlusPlus11 ?
Nick Lewycky36722d22013-02-06 05:59:33 +000011277 diag::warn_cxx98_compat_enum_friend :
11278 diag::ext_enum_friend)
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011279 << T
Richard Smitha31a89a2012-09-20 01:31:00 +000011280 << TypeRange;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011281 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011282
Nick Lewycky36722d22013-02-06 05:59:33 +000011283 // C++11 [class.friend]p3:
11284 // A friend declaration that does not declare a function shall have one
11285 // of the following forms:
11286 // friend elaborated-type-specifier ;
11287 // friend simple-type-specifier ;
11288 // friend typename-specifier ;
11289 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
11290 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
11291 }
Richard Smitha31a89a2012-09-20 01:31:00 +000011292
Douglas Gregor3b4abb62010-04-07 17:57:12 +000011293 // If the type specifier in a friend declaration designates a (possibly
Richard Smitha31a89a2012-09-20 01:31:00 +000011294 // cv-qualified) class type, that class is declared as a friend; otherwise,
Douglas Gregor3b4abb62010-04-07 17:57:12 +000011295 // the friend declaration is ignored.
Richard Smitha31a89a2012-09-20 01:31:00 +000011296 return FriendDecl::Create(Context, CurContext, LocStart, TSInfo, FriendLoc);
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011297}
11298
John McCallace48cd2010-10-19 01:40:49 +000011299/// Handle a friend tag declaration where the scope specifier was
11300/// templated.
11301Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
11302 unsigned TagSpec, SourceLocation TagLoc,
11303 CXXScopeSpec &SS,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000011304 IdentifierInfo *Name,
11305 SourceLocation NameLoc,
John McCallace48cd2010-10-19 01:40:49 +000011306 AttributeList *Attr,
11307 MultiTemplateParamsArg TempParamLists) {
11308 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
11309
11310 bool isExplicitSpecialization = false;
John McCallace48cd2010-10-19 01:40:49 +000011311 bool Invalid = false;
11312
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +000011313 if (TemplateParameterList *TemplateParams =
11314 MatchTemplateParametersToScopeSpecifier(
11315 TagLoc, NameLoc, SS, TempParamLists, /*friend*/ true,
11316 isExplicitSpecialization, Invalid)) {
John McCallace48cd2010-10-19 01:40:49 +000011317 if (TemplateParams->size() > 0) {
11318 // This is a declaration of a class template.
11319 if (Invalid)
11320 return 0;
Abramo Bagnara0adf29a2011-03-10 13:28:31 +000011321
Eric Christopher6f228b52011-07-21 05:34:24 +000011322 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
11323 SS, Name, NameLoc, Attr,
11324 TemplateParams, AS_public,
Douglas Gregor2820e692011-09-09 19:05:14 +000011325 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher6f228b52011-07-21 05:34:24 +000011326 TempParamLists.size() - 1,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000011327 TempParamLists.data()).take();
John McCallace48cd2010-10-19 01:40:49 +000011328 } else {
11329 // The "template<>" header is extraneous.
11330 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
11331 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
11332 isExplicitSpecialization = true;
11333 }
11334 }
11335
11336 if (Invalid) return 0;
11337
John McCallace48cd2010-10-19 01:40:49 +000011338 bool isAllExplicitSpecializations = true;
Abramo Bagnara60804e12011-03-18 15:16:37 +000011339 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011340 if (TempParamLists[I]->size()) {
John McCallace48cd2010-10-19 01:40:49 +000011341 isAllExplicitSpecializations = false;
11342 break;
11343 }
11344 }
11345
11346 // FIXME: don't ignore attributes.
11347
11348 // If it's explicit specializations all the way down, just forget
11349 // about the template header and build an appropriate non-templated
11350 // friend. TODO: for source fidelity, remember the headers.
11351 if (isAllExplicitSpecializations) {
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011352 if (SS.isEmpty()) {
11353 bool Owned = false;
11354 bool IsDependent = false;
11355 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
Richard Smith649c7b062014-01-08 00:56:48 +000011356 Attr, AS_public,
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011357 /*ModulePrivateLoc=*/SourceLocation(),
Richard Smith649c7b062014-01-08 00:56:48 +000011358 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smith0f8ee222012-01-10 01:33:14 +000011359 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011360 /*ScopedEnumUsesClassTag=*/false,
Richard Smith649c7b062014-01-08 00:56:48 +000011361 /*UnderlyingType=*/TypeResult(),
11362 /*IsTypeSpecifier=*/false);
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011363 }
Richard Smith649c7b062014-01-08 00:56:48 +000011364
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000011365 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallace48cd2010-10-19 01:40:49 +000011366 ElaboratedTypeKeyword Keyword
11367 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000011368 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +000011369 *Name, NameLoc);
John McCallace48cd2010-10-19 01:40:49 +000011370 if (T.isNull())
11371 return 0;
11372
11373 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
11374 if (isa<DependentNameType>(T)) {
David Blaikie6adc78e2013-02-18 22:06:02 +000011375 DependentNameTypeLoc TL =
11376 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000011377 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000011378 TL.setQualifierLoc(QualifierLoc);
John McCallace48cd2010-10-19 01:40:49 +000011379 TL.setNameLoc(NameLoc);
11380 } else {
David Blaikie6adc78e2013-02-18 22:06:02 +000011381 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000011382 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +000011383 TL.setQualifierLoc(QualifierLoc);
David Blaikie6adc78e2013-02-18 22:06:02 +000011384 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
John McCallace48cd2010-10-19 01:40:49 +000011385 }
11386
11387 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000011388 TSI, FriendLoc, TempParamLists);
John McCallace48cd2010-10-19 01:40:49 +000011389 Friend->setAccess(AS_public);
11390 CurContext->addDecl(Friend);
11391 return Friend;
11392 }
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011393
11394 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
11395
11396
John McCallace48cd2010-10-19 01:40:49 +000011397
11398 // Handle the case of a templated-scope friend class. e.g.
11399 // template <class T> class A<T>::B;
11400 // FIXME: we don't support these right now.
Richard Smithcd556eb2013-11-08 18:59:56 +000011401 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
11402 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
John McCallace48cd2010-10-19 01:40:49 +000011403 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
11404 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
11405 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
David Blaikie6adc78e2013-02-18 22:06:02 +000011406 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000011407 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000011408 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCallace48cd2010-10-19 01:40:49 +000011409 TL.setNameLoc(NameLoc);
11410
11411 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000011412 TSI, FriendLoc, TempParamLists);
John McCallace48cd2010-10-19 01:40:49 +000011413 Friend->setAccess(AS_public);
11414 Friend->setUnsupportedFriend(true);
11415 CurContext->addDecl(Friend);
11416 return Friend;
11417}
11418
11419
John McCall11083da2009-09-16 22:47:08 +000011420/// Handle a friend type declaration. This works in tandem with
11421/// ActOnTag.
11422///
11423/// Notes on friend class templates:
11424///
11425/// We generally treat friend class declarations as if they were
11426/// declaring a class. So, for example, the elaborated type specifier
11427/// in a friend declaration is required to obey the restrictions of a
11428/// class-head (i.e. no typedefs in the scope chain), template
11429/// parameters are required to match up with simple template-ids, &c.
11430/// However, unlike when declaring a template specialization, it's
11431/// okay to refer to a template specialization without an empty
11432/// template parameter declaration, e.g.
11433/// friend class A<T>::B<unsigned>;
11434/// We permit this as a special case; if there are any template
11435/// parameters present at all, require proper matching, i.e.
James Dennettf14a6e52012-06-15 22:23:43 +000011436/// template <> template \<class T> friend class A<int>::B;
John McCall48871652010-08-21 09:40:31 +000011437Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallc9739e32010-10-16 07:23:36 +000011438 MultiTemplateParamsArg TempParams) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011439 SourceLocation Loc = DS.getLocStart();
John McCall07e91c02009-08-06 02:15:43 +000011440
11441 assert(DS.isFriendSpecified());
11442 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11443
John McCall11083da2009-09-16 22:47:08 +000011444 // Try to convert the decl specifier to a type. This works for
11445 // friend templates because ActOnTag never produces a ClassTemplateDecl
11446 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +000011447 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +000011448 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
11449 QualType T = TSI->getType();
Chris Lattner1fb66f42009-10-25 17:47:27 +000011450 if (TheDeclarator.isInvalidType())
John McCall48871652010-08-21 09:40:31 +000011451 return 0;
John McCall07e91c02009-08-06 02:15:43 +000011452
Douglas Gregor6c110f32010-12-16 01:14:37 +000011453 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
11454 return 0;
11455
John McCall11083da2009-09-16 22:47:08 +000011456 // This is definitely an error in C++98. It's probably meant to
11457 // be forbidden in C++0x, too, but the specification is just
11458 // poorly written.
11459 //
11460 // The problem is with declarations like the following:
11461 // template <T> friend A<T>::foo;
11462 // where deciding whether a class C is a friend or not now hinges
11463 // on whether there exists an instantiation of A that causes
11464 // 'foo' to equal C. There are restrictions on class-heads
11465 // (which we declare (by fiat) elaborated friend declarations to
11466 // be) that makes this tractable.
11467 //
11468 // FIXME: handle "template <> friend class A<T>;", which
11469 // is possibly well-formed? Who even knows?
Douglas Gregore677daf2010-03-31 22:19:08 +000011470 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCall11083da2009-09-16 22:47:08 +000011471 Diag(Loc, diag::err_tagless_friend_type_template)
11472 << DS.getSourceRange();
John McCall48871652010-08-21 09:40:31 +000011473 return 0;
John McCall11083da2009-09-16 22:47:08 +000011474 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011475
John McCallaa74a0c2009-08-28 07:59:38 +000011476 // C++98 [class.friend]p1: A friend of a class is a function
11477 // or class that is not a member of the class . . .
John McCall463e10c2009-12-22 00:59:39 +000011478 // This is fixed in DR77, which just barely didn't make the C++03
11479 // deadline. It's also a very silly restriction that seriously
11480 // affects inner classes and which nobody else seems to implement;
11481 // thus we never diagnose it, not even in -pedantic.
John McCall15ad0962010-03-25 18:04:51 +000011482 //
11483 // But note that we could warn about it: it's always useless to
11484 // friend one of your own members (it's not, however, worthless to
11485 // friend a member of an arbitrary specialization of your template).
John McCallaa74a0c2009-08-28 07:59:38 +000011486
John McCall11083da2009-09-16 22:47:08 +000011487 Decl *D;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011488 if (unsigned NumTempParamLists = TempParams.size())
John McCall11083da2009-09-16 22:47:08 +000011489 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011490 NumTempParamLists,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000011491 TempParams.data(),
John McCall15ad0962010-03-25 18:04:51 +000011492 TSI,
John McCall11083da2009-09-16 22:47:08 +000011493 DS.getFriendSpecLoc());
11494 else
Abramo Bagnara254b6302011-10-29 20:52:52 +000011495 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011496
11497 if (!D)
John McCall48871652010-08-21 09:40:31 +000011498 return 0;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011499
John McCall11083da2009-09-16 22:47:08 +000011500 D->setAccess(AS_public);
11501 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +000011502
John McCall48871652010-08-21 09:40:31 +000011503 return D;
John McCallaa74a0c2009-08-28 07:59:38 +000011504}
11505
Rafael Espindola0a67e2f2013-01-08 20:44:06 +000011506NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
11507 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +000011508 const DeclSpec &DS = D.getDeclSpec();
11509
11510 assert(DS.isFriendSpecified());
11511 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11512
11513 SourceLocation Loc = D.getIdentifierLoc();
John McCall8cb7bdf2010-06-04 23:28:52 +000011514 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall07e91c02009-08-06 02:15:43 +000011515
11516 // C++ [class.friend]p1
11517 // A friend of a class is a function or class....
11518 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +000011519 // It *doesn't* see through dependent types, which is correct
11520 // according to [temp.arg.type]p3:
11521 // If a declaration acquires a function type through a
11522 // type dependent on a template-parameter and this causes
11523 // a declaration that does not use the syntactic form of a
11524 // function declarator to have a function type, the program
11525 // is ill-formed.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011526 if (!TInfo->getType()->isFunctionType()) {
John McCall07e91c02009-08-06 02:15:43 +000011527 Diag(Loc, diag::err_unexpected_friend);
11528
11529 // It might be worthwhile to try to recover by creating an
11530 // appropriate declaration.
John McCall48871652010-08-21 09:40:31 +000011531 return 0;
John McCall07e91c02009-08-06 02:15:43 +000011532 }
11533
11534 // C++ [namespace.memdef]p3
11535 // - If a friend declaration in a non-local class first declares a
11536 // class or function, the friend class or function is a member
11537 // of the innermost enclosing namespace.
11538 // - The name of the friend is not found by simple name lookup
11539 // until a matching declaration is provided in that namespace
11540 // scope (either before or after the class declaration granting
11541 // friendship).
11542 // - If a friend function is called, its name may be found by the
11543 // name lookup that considers functions from namespaces and
11544 // classes associated with the types of the function arguments.
11545 // - When looking for a prior declaration of a class or a function
11546 // declared as a friend, scopes outside the innermost enclosing
11547 // namespace scope are not considered.
11548
John McCallde3fd222010-10-12 23:13:28 +000011549 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011550 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
11551 DeclarationName Name = NameInfo.getName();
John McCall07e91c02009-08-06 02:15:43 +000011552 assert(Name);
11553
Douglas Gregor6c110f32010-12-16 01:14:37 +000011554 // Check for unexpanded parameter packs.
11555 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
11556 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
11557 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
11558 return 0;
11559
John McCall07e91c02009-08-06 02:15:43 +000011560 // The context we found the declaration in, or in which we should
11561 // create the declaration.
11562 DeclContext *DC;
John McCallccbc0322010-10-13 06:22:15 +000011563 Scope *DCScope = S;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011564 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +000011565 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +000011566
Richard Smith114394f2013-08-09 04:35:01 +000011567 // There are five cases here.
11568 // - There's no scope specifier and we're in a local class. Only look
11569 // for functions declared in the immediately-enclosing block scope.
11570 // We recover from invalid scope qualifiers as if they just weren't there.
11571 FunctionDecl *FunctionContainingLocalClass = 0;
11572 if ((SS.isInvalid() || !SS.isSet()) &&
11573 (FunctionContainingLocalClass =
11574 cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
11575 // C++11 [class.friend]p11:
John McCallf7cfb222010-10-13 05:45:15 +000011576 // If a friend declaration appears in a local class and the name
11577 // specified is an unqualified name, a prior declaration is
11578 // looked up without considering scopes that are outside the
11579 // innermost enclosing non-class scope. For a friend function
11580 // declaration, if there is no prior declaration, the program is
11581 // ill-formed.
Richard Smith114394f2013-08-09 04:35:01 +000011582
11583 // Find the innermost enclosing non-class scope. This is the block
11584 // scope containing the local class definition (or for a nested class,
11585 // the outer local class).
11586 DCScope = S->getFnParent();
11587
11588 // Look up the function name in the scope.
11589 Previous.clear(LookupLocalFriendName);
11590 LookupName(Previous, S, /*AllowBuiltinCreation*/false);
11591
11592 if (!Previous.empty()) {
11593 // All possible previous declarations must have the same context:
11594 // either they were declared at block scope or they are members of
11595 // one of the enclosing local classes.
11596 DC = Previous.getRepresentativeDecl()->getDeclContext();
11597 } else {
11598 // This is ill-formed, but provide the context that we would have
11599 // declared the function in, if we were permitted to, for error recovery.
11600 DC = FunctionContainingLocalClass;
11601 }
Richard Smith541b38b2013-09-20 01:15:31 +000011602 adjustContextForLocalExternDecl(DC);
Richard Smith114394f2013-08-09 04:35:01 +000011603
11604 // C++ [class.friend]p6:
11605 // A function can be defined in a friend declaration of a class if and
11606 // only if the class is a non-local class (9.8), the function name is
11607 // unqualified, and the function has namespace scope.
11608 if (D.isFunctionDefinition()) {
11609 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
11610 }
11611
11612 // - There's no scope specifier, in which case we just go to the
11613 // appropriate scope and look for a function or function template
11614 // there as appropriate.
11615 } else if (SS.isInvalid() || !SS.isSet()) {
11616 // C++11 [namespace.memdef]p3:
11617 // If the name in a friend declaration is neither qualified nor
11618 // a template-id and the declaration is a function or an
11619 // elaborated-type-specifier, the lookup to determine whether
11620 // the entity has been previously declared shall not consider
11621 // any scopes outside the innermost enclosing namespace.
John McCallf4776592010-10-14 22:22:28 +000011622 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall07e91c02009-08-06 02:15:43 +000011623
John McCallf7cfb222010-10-13 05:45:15 +000011624 // Find the appropriate context according to the above.
John McCall07e91c02009-08-06 02:15:43 +000011625 DC = CurContext;
John McCall07e91c02009-08-06 02:15:43 +000011626
Rafael Espindola3626b7e2013-04-25 20:12:36 +000011627 // Skip class contexts. If someone can cite chapter and verse
11628 // for this behavior, that would be nice --- it's what GCC and
11629 // EDG do, and it seems like a reasonable intent, but the spec
11630 // really only says that checks for unqualified existing
11631 // declarations should stop at the nearest enclosing namespace,
11632 // not that they should only consider the nearest enclosing
11633 // namespace.
11634 while (DC->isRecord())
11635 DC = DC->getParent();
11636
11637 DeclContext *LookupDC = DC;
11638 while (LookupDC->isTransparentContext())
11639 LookupDC = LookupDC->getParent();
11640
11641 while (true) {
11642 LookupQualifiedName(Previous, LookupDC);
John McCall07e91c02009-08-06 02:15:43 +000011643
Rafael Espindola3626b7e2013-04-25 20:12:36 +000011644 if (!Previous.empty()) {
11645 DC = LookupDC;
11646 break;
John McCallf4776592010-10-14 22:22:28 +000011647 }
Rafael Espindola3626b7e2013-04-25 20:12:36 +000011648
11649 if (isTemplateId) {
11650 if (isa<TranslationUnitDecl>(LookupDC)) break;
11651 } else {
11652 if (LookupDC->isFileContext()) break;
11653 }
11654 LookupDC = LookupDC->getParent();
John McCall07e91c02009-08-06 02:15:43 +000011655 }
11656
John McCallccbc0322010-10-13 06:22:15 +000011657 DCScope = getScopeForDeclContext(S, DC);
Richard Smith114394f2013-08-09 04:35:01 +000011658
John McCallde3fd222010-10-12 23:13:28 +000011659 // - There's a non-dependent scope specifier, in which case we
11660 // compute it and do a previous lookup there for a function
11661 // or function template.
11662 } else if (!SS.getScopeRep()->isDependent()) {
11663 DC = computeDeclContext(SS);
11664 if (!DC) return 0;
11665
11666 if (RequireCompleteDeclContext(SS, DC)) return 0;
11667
11668 LookupQualifiedName(Previous, DC);
11669
11670 // Ignore things found implicitly in the wrong scope.
11671 // TODO: better diagnostics for this case. Suggesting the right
11672 // qualified scope would be nice...
11673 LookupResult::Filter F = Previous.makeFilter();
11674 while (F.hasNext()) {
11675 NamedDecl *D = F.next();
11676 if (!DC->InEnclosingNamespaceSetOf(
11677 D->getDeclContext()->getRedeclContext()))
11678 F.erase();
11679 }
11680 F.done();
11681
11682 if (Previous.empty()) {
11683 D.setInvalidType();
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011684 Diag(Loc, diag::err_qualified_friend_not_found)
11685 << Name << TInfo->getType();
John McCallde3fd222010-10-12 23:13:28 +000011686 return 0;
11687 }
11688
11689 // C++ [class.friend]p1: A friend of a class is a function or
11690 // class that is not a member of the class . . .
Richard Smith0bf8a4922011-10-18 20:49:44 +000011691 if (DC->Equals(CurContext))
11692 Diag(DS.getFriendSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011693 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +000011694 diag::warn_cxx98_compat_friend_is_member :
11695 diag::err_friend_is_member);
Douglas Gregor16e65612011-10-10 01:11:59 +000011696
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011697 if (D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000011698 // C++ [class.friend]p6:
11699 // A function can be defined in a friend declaration of a class if and
11700 // only if the class is a non-local class (9.8), the function name is
11701 // unqualified, and the function has namespace scope.
11702 SemaDiagnosticBuilder DB
11703 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
11704
11705 DB << SS.getScopeRep();
11706 if (DC->isFileContext())
11707 DB << FixItHint::CreateRemoval(SS.getRange());
11708 SS.clear();
11709 }
John McCallde3fd222010-10-12 23:13:28 +000011710
11711 // - There's a scope specifier that does not match any template
11712 // parameter lists, in which case we use some arbitrary context,
11713 // create a method or method template, and wait for instantiation.
11714 // - There's a scope specifier that does match some template
11715 // parameter lists, which we don't handle right now.
11716 } else {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011717 if (D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000011718 // C++ [class.friend]p6:
11719 // A function can be defined in a friend declaration of a class if and
11720 // only if the class is a non-local class (9.8), the function name is
11721 // unqualified, and the function has namespace scope.
11722 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
11723 << SS.getScopeRep();
11724 }
11725
John McCallde3fd222010-10-12 23:13:28 +000011726 DC = CurContext;
11727 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall07e91c02009-08-06 02:15:43 +000011728 }
Douglas Gregor16e65612011-10-10 01:11:59 +000011729
John McCallf7cfb222010-10-13 05:45:15 +000011730 if (!DC->isRecord()) {
John McCall07e91c02009-08-06 02:15:43 +000011731 // This implies that it has to be an operator or function.
Douglas Gregor7861a802009-11-03 01:35:08 +000011732 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
11733 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
11734 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall07e91c02009-08-06 02:15:43 +000011735 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor7861a802009-11-03 01:35:08 +000011736 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
11737 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall48871652010-08-21 09:40:31 +000011738 return 0;
John McCall07e91c02009-08-06 02:15:43 +000011739 }
John McCall07e91c02009-08-06 02:15:43 +000011740 }
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011741
Douglas Gregordd847ba2011-11-03 16:37:14 +000011742 // FIXME: This is an egregious hack to cope with cases where the scope stack
11743 // does not contain the declaration context, i.e., in an out-of-line
11744 // definition of a class.
11745 Scope FakeDCScope(S, Scope::DeclScope, Diags);
11746 if (!DCScope) {
11747 FakeDCScope.setEntity(DC);
11748 DCScope = &FakeDCScope;
11749 }
Richard Smith114394f2013-08-09 04:35:01 +000011750
Francois Pichet00c7e6c2011-08-14 03:52:19 +000011751 bool AddToScope = true;
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011752 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011753 TemplateParams, AddToScope);
John McCall48871652010-08-21 09:40:31 +000011754 if (!ND) return 0;
John McCall759e32b2009-08-31 22:39:49 +000011755
Douglas Gregora29a3ff2009-09-28 00:08:27 +000011756 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +000011757
Richard Smith114394f2013-08-09 04:35:01 +000011758 // If we performed typo correction, we might have added a scope specifier
11759 // and changed the decl context.
11760 DC = ND->getDeclContext();
11761
John McCall759e32b2009-08-31 22:39:49 +000011762 // Add the function declaration to the appropriate lookup tables,
11763 // adjusting the redeclarations list as necessary. We don't
11764 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +000011765 //
John McCall759e32b2009-08-31 22:39:49 +000011766 // Also update the scope-based lookup if the target context's
11767 // lookup context is in lexical scope.
11768 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +000011769 DC = DC->getRedeclContext();
Richard Smith05afe5e2012-03-13 03:12:56 +000011770 DC->makeDeclVisibleInContext(ND);
John McCall759e32b2009-08-31 22:39:49 +000011771 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +000011772 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +000011773 }
John McCallaa74a0c2009-08-28 07:59:38 +000011774
11775 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +000011776 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +000011777 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +000011778 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +000011779 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +000011780
John McCalla0a96892012-08-10 03:15:35 +000011781 if (ND->isInvalidDecl()) {
John McCallde3fd222010-10-12 23:13:28 +000011782 FrD->setInvalidDecl();
John McCalla0a96892012-08-10 03:15:35 +000011783 } else {
11784 if (DC->isRecord()) CheckFriendAccess(ND);
11785
John McCall2c2eb122010-10-16 06:59:13 +000011786 FunctionDecl *FD;
11787 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
11788 FD = FTD->getTemplatedDecl();
11789 else
11790 FD = cast<FunctionDecl>(ND);
11791
David Majnemer502b0ed2013-06-25 23:09:30 +000011792 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
11793 // default argument expression, that declaration shall be a definition
11794 // and shall be the only declaration of the function or function
11795 // template in the translation unit.
11796 if (functionDeclHasDefaultArgument(FD)) {
11797 if (FunctionDecl *OldFD = FD->getPreviousDecl()) {
11798 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
11799 Diag(OldFD->getLocation(), diag::note_previous_declaration);
11800 } else if (!D.isFunctionDefinition())
11801 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
11802 }
11803
John McCall2c2eb122010-10-16 06:59:13 +000011804 // Mark templated-scope function declarations as unsupported.
11805 if (FD->getNumTemplateParameterLists())
11806 FrD->setUnsupportedFriend(true);
11807 }
John McCallde3fd222010-10-12 23:13:28 +000011808
John McCall48871652010-08-21 09:40:31 +000011809 return ND;
Anders Carlsson38811702009-05-11 22:55:49 +000011810}
11811
John McCall48871652010-08-21 09:40:31 +000011812void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
11813 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +000011814
Aaron Ballmanf96361e2013-01-16 23:39:10 +000011815 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
Sebastian Redlf769df52009-03-24 22:27:57 +000011816 if (!Fn) {
11817 Diag(DelLoc, diag::err_deleted_non_function);
11818 return;
11819 }
Richard Smithb4d2a152013-04-02 19:38:47 +000011820
Douglas Gregorec9fd132012-01-14 16:38:05 +000011821 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
David Blaikie36805522012-06-25 21:55:30 +000011822 // Don't consider the implicit declaration we generate for explicit
11823 // specializations. FIXME: Do not generate these implicit declarations.
Richard Smithbdd14642014-02-04 01:14:30 +000011824 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
11825 Prev->getPreviousDecl()) &&
11826 !Prev->isDefined()) {
David Blaikie36805522012-06-25 21:55:30 +000011827 Diag(DelLoc, diag::err_deleted_decl_not_first);
Richard Smithbdd14642014-02-04 01:14:30 +000011828 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
11829 Prev->isImplicit() ? diag::note_previous_implicit_declaration
11830 : diag::note_previous_declaration);
David Blaikie36805522012-06-25 21:55:30 +000011831 }
Sebastian Redlf769df52009-03-24 22:27:57 +000011832 // If the declaration wasn't the first, we delete the function anyway for
11833 // recovery.
Richard Smithb4d2a152013-04-02 19:38:47 +000011834 Fn = Fn->getCanonicalDecl();
Sebastian Redlf769df52009-03-24 22:27:57 +000011835 }
Richard Smithb4d2a152013-04-02 19:38:47 +000011836
11837 if (Fn->isDeleted())
11838 return;
11839
11840 // See if we're deleting a function which is already known to override a
11841 // non-deleted virtual function.
11842 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
11843 bool IssuedDiagnostic = false;
11844 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
11845 E = MD->end_overridden_methods();
11846 I != E; ++I) {
11847 if (!(*MD->begin_overridden_methods())->isDeleted()) {
11848 if (!IssuedDiagnostic) {
11849 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
11850 IssuedDiagnostic = true;
11851 }
11852 Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
11853 }
11854 }
11855 }
11856
Richard Smithb63b6ee2014-01-22 01:43:19 +000011857 // C++11 [basic.start.main]p3:
11858 // A program that defines main as deleted [...] is ill-formed.
11859 if (Fn->isMain())
11860 Diag(DelLoc, diag::err_deleted_main);
11861
Alexis Hunt4a8ea102011-05-06 20:44:56 +000011862 Fn->setDeletedAsWritten();
Sebastian Redlf769df52009-03-24 22:27:57 +000011863}
Sebastian Redl4c018662009-04-27 21:33:24 +000011864
Alexis Hunt5a7fa252011-05-12 06:15:49 +000011865void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
Aaron Ballmanf96361e2013-01-16 23:39:10 +000011866 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000011867
11868 if (MD) {
Alexis Hunt1fb4e762011-05-23 21:07:59 +000011869 if (MD->getParent()->isDependentType()) {
11870 MD->setDefaulted();
11871 MD->setExplicitlyDefaulted();
11872 return;
11873 }
11874
Alexis Hunt5a7fa252011-05-12 06:15:49 +000011875 CXXSpecialMember Member = getSpecialMember(MD);
11876 if (Member == CXXInvalid) {
Eli Friedman84c0143e2013-07-11 23:55:07 +000011877 if (!MD->isInvalidDecl())
11878 Diag(DefaultLoc, diag::err_default_special_members);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000011879 return;
11880 }
11881
11882 MD->setDefaulted();
11883 MD->setExplicitlyDefaulted();
11884
Alexis Hunt61ae8d32011-05-23 23:14:04 +000011885 // If this definition appears within the record, do the checking when
11886 // the record is complete.
11887 const FunctionDecl *Primary = MD;
Richard Smith802c4b72012-08-23 06:16:52 +000011888 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
Alexis Hunt61ae8d32011-05-23 23:14:04 +000011889 // Find the uninstantiated declaration that actually had the '= default'
11890 // on it.
Richard Smith802c4b72012-08-23 06:16:52 +000011891 Pattern->isDefined(Primary);
Alexis Hunt61ae8d32011-05-23 23:14:04 +000011892
Richard Smith3901dfe2013-03-27 00:22:47 +000011893 // If the method was defaulted on its first declaration, we will have
11894 // already performed the checking in CheckCompletedCXXClass. Such a
11895 // declaration doesn't trigger an implicit definition.
Alexis Hunt61ae8d32011-05-23 23:14:04 +000011896 if (Primary == Primary->getCanonicalDecl())
Alexis Hunt5a7fa252011-05-12 06:15:49 +000011897 return;
11898
Richard Smithd3b5c9082012-07-27 04:22:15 +000011899 CheckExplicitlyDefaultedSpecialMember(MD);
11900
Richard Smithbd305122012-12-11 01:14:52 +000011901 // The exception specification is needed because we are defining the
11902 // function.
11903 ResolveExceptionSpec(DefaultLoc,
11904 MD->getType()->castAs<FunctionProtoType>());
11905
Benjamin Kramer8bf44352013-07-24 15:28:33 +000011906 if (MD->isInvalidDecl())
11907 return;
11908
Alexis Hunt5a7fa252011-05-12 06:15:49 +000011909 switch (Member) {
Benjamin Kramer8bf44352013-07-24 15:28:33 +000011910 case CXXDefaultConstructor:
11911 DefineImplicitDefaultConstructor(DefaultLoc,
11912 cast<CXXConstructorDecl>(MD));
Alexis Hunt913820d2011-05-13 06:10:58 +000011913 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000011914 case CXXCopyConstructor:
11915 DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
Alexis Hunt5a7fa252011-05-12 06:15:49 +000011916 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000011917 case CXXCopyAssignment:
11918 DefineImplicitCopyAssignment(DefaultLoc, MD);
Alexis Huntc9a55732011-05-14 05:23:28 +000011919 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000011920 case CXXDestructor:
11921 DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
Alexis Huntf91729462011-05-12 22:46:25 +000011922 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000011923 case CXXMoveConstructor:
11924 DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
Alexis Hunt119c10e2011-05-25 23:16:36 +000011925 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000011926 case CXXMoveAssignment:
11927 DefineImplicitMoveAssignment(DefaultLoc, MD);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011928 break;
Sebastian Redl22653ba2011-08-30 19:58:05 +000011929 case CXXInvalid:
David Blaikie83d382b2011-09-23 05:06:16 +000011930 llvm_unreachable("Invalid special member.");
Alexis Hunt5a7fa252011-05-12 06:15:49 +000011931 }
11932 } else {
11933 Diag(DefaultLoc, diag::err_default_special_members);
11934 }
11935}
11936
Sebastian Redl4c018662009-04-27 21:33:24 +000011937static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall8322c3a2011-02-13 04:07:26 +000011938 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl4c018662009-04-27 21:33:24 +000011939 Stmt *SubStmt = *CI;
11940 if (!SubStmt)
11941 continue;
11942 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011943 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl4c018662009-04-27 21:33:24 +000011944 diag::err_return_in_constructor_handler);
11945 if (!isa<Expr>(SubStmt))
11946 SearchForReturnInStmt(Self, SubStmt);
11947 }
11948}
11949
11950void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
11951 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
11952 CXXCatchStmt *Handler = TryBlock->getHandler(I);
11953 SearchForReturnInStmt(*this, Handler);
11954 }
11955}
Anders Carlssonf2a2e332009-05-14 01:09:04 +000011956
David Blaikie68f71a32013-01-18 23:03:15 +000011957bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
Aaron Ballman02df2e02012-12-09 17:45:41 +000011958 const CXXMethodDecl *Old) {
11959 const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
11960 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
11961
11962 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
11963
11964 // If the calling conventions match, everything is fine
11965 if (NewCC == OldCC)
11966 return false;
11967
Hans Wennborg2545efe2013-12-11 17:42:11 +000011968 // If the calling conventions mismatch because the new function is static,
11969 // suppress the calling convention mismatch error; the error about static
11970 // function override (err_static_overrides_virtual from
11971 // Sema::CheckFunctionDeclaration) is more clear.
11972 if (New->getStorageClass() == SC_Static)
11973 return false;
11974
Reid Kleckner78af0702013-08-27 23:08:25 +000011975 Diag(New->getLocation(),
11976 diag::err_conflicting_overriding_cc_attributes)
11977 << New->getDeclName() << New->getType() << Old->getType();
11978 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11979 return true;
Aaron Ballman02df2e02012-12-09 17:45:41 +000011980}
11981
Mike Stump11289f42009-09-09 15:08:12 +000011982bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +000011983 const CXXMethodDecl *Old) {
Alp Toker314cc812014-01-25 16:55:45 +000011984 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
11985 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +000011986
Chandler Carruth284bb2e2010-02-15 11:53:20 +000011987 if (Context.hasSameType(NewTy, OldTy) ||
11988 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssonf2a2e332009-05-14 01:09:04 +000011989 return false;
Mike Stump11289f42009-09-09 15:08:12 +000011990
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000011991 // Check if the return types are covariant
11992 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +000011993
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000011994 /// Both types must be pointers or references to classes.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000011995 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
11996 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000011997 NewClassTy = NewPT->getPointeeType();
11998 OldClassTy = OldPT->getPointeeType();
11999 }
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000012000 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
12001 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
12002 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
12003 NewClassTy = NewRT->getPointeeType();
12004 OldClassTy = OldRT->getPointeeType();
12005 }
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012006 }
12007 }
Mike Stump11289f42009-09-09 15:08:12 +000012008
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012009 // The return types aren't either both pointers or references to a class type.
12010 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +000012011 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012012 diag::err_different_return_type_for_overriding_virtual_function)
12013 << New->getDeclName() << NewTy << OldTy;
12014 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump11289f42009-09-09 15:08:12 +000012015
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012016 return true;
12017 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012018
Anders Carlssone60365b2009-12-31 18:34:24 +000012019 // C++ [class.virtual]p6:
12020 // If the return type of D::f differs from the return type of B::f, the
12021 // class type in the return type of D::f shall be complete at the point of
12022 // declaration of D::f or shall be the class type D.
Anders Carlsson0c9dd842009-12-31 18:54:35 +000012023 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
12024 if (!RT->isBeingDefined() &&
12025 RequireCompleteType(New->getLocation(), NewClassTy,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000012026 diag::err_covariant_return_incomplete,
12027 New->getDeclName()))
Anders Carlssone60365b2009-12-31 18:34:24 +000012028 return true;
Anders Carlsson0c9dd842009-12-31 18:54:35 +000012029 }
Anders Carlssone60365b2009-12-31 18:34:24 +000012030
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +000012031 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012032 // Check if the new class derives from the old class.
12033 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
12034 Diag(New->getLocation(),
12035 diag::err_covariant_return_not_derived)
12036 << New->getDeclName() << NewTy << OldTy;
12037 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12038 return true;
12039 }
Mike Stump11289f42009-09-09 15:08:12 +000012040
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012041 // Check if we the conversion from derived to base is valid.
John McCall1064d7e2010-03-16 05:22:47 +000012042 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlsson7afe4242010-04-24 17:11:09 +000012043 diag::err_covariant_return_inaccessible_base,
12044 diag::err_covariant_return_ambiguous_derived_to_base_conv,
12045 // FIXME: Should this point to the return type?
12046 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCallc1465822011-02-14 07:13:47 +000012047 // FIXME: this note won't trigger for delayed access control
12048 // diagnostics, and it's impossible to get an undelayed error
12049 // here from access control during the original parse because
12050 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012051 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12052 return true;
12053 }
12054 }
Mike Stump11289f42009-09-09 15:08:12 +000012055
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012056 // The qualifiers of the return types must be the same.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000012057 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012058 Diag(New->getLocation(),
12059 diag::err_covariant_return_type_different_qualifications)
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012060 << New->getDeclName() << NewTy << OldTy;
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012061 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12062 return true;
12063 };
Mike Stump11289f42009-09-09 15:08:12 +000012064
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012065
12066 // The new class type must have the same or less qualifiers as the old type.
12067 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
12068 Diag(New->getLocation(),
12069 diag::err_covariant_return_type_class_type_more_qualified)
12070 << New->getDeclName() << NewTy << OldTy;
12071 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12072 return true;
12073 };
Mike Stump11289f42009-09-09 15:08:12 +000012074
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012075 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012076}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012077
Douglas Gregor21920e372009-12-01 17:24:26 +000012078/// \brief Mark the given method pure.
12079///
12080/// \param Method the method to be marked pure.
12081///
12082/// \param InitRange the source range that covers the "0" initializer.
12083bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000012084 SourceLocation EndLoc = InitRange.getEnd();
12085 if (EndLoc.isValid())
12086 Method->setRangeEnd(EndLoc);
12087
Douglas Gregor21920e372009-12-01 17:24:26 +000012088 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
12089 Method->setPure();
Douglas Gregor21920e372009-12-01 17:24:26 +000012090 return false;
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000012091 }
Douglas Gregor21920e372009-12-01 17:24:26 +000012092
12093 if (!Method->isInvalidDecl())
12094 Diag(Method->getLocation(), diag::err_non_virtual_pure)
12095 << Method->getDeclName() << InitRange;
12096 return true;
12097}
12098
Douglas Gregor926410d2012-02-21 02:22:07 +000012099/// \brief Determine whether the given declaration is a static data member.
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012100static bool isStaticDataMember(const Decl *D) {
12101 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
12102 return Var->isStaticDataMember();
12103
12104 return false;
Douglas Gregor926410d2012-02-21 02:22:07 +000012105}
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012106
John McCall1f4ee7b2009-12-19 09:28:58 +000012107/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
12108/// an initializer for the out-of-line declaration 'Dcl'. The scope
12109/// is a fresh scope pushed for just this purpose.
12110///
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012111/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
12112/// static data member of class X, names should be looked up in the scope of
12113/// class X.
John McCall48871652010-08-21 09:40:31 +000012114void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012115 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidis8e4be0b2011-04-22 18:52:25 +000012116 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012117
Richard Smitha2302242013-12-05 07:51:02 +000012118 // We will always have a nested name specifier here, but this declaration
12119 // might not be out of line if the specifier names the current namespace:
12120 // extern int n;
12121 // int ::n = 0;
12122 if (D->isOutOfLine())
12123 EnterDeclaratorContext(S, D->getDeclContext());
12124
Douglas Gregor926410d2012-02-21 02:22:07 +000012125 // If we are parsing the initializer for a static data member, push a
12126 // new expression evaluation context that is associated with this static
12127 // data member.
12128 if (isStaticDataMember(D))
12129 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012130}
12131
12132/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall48871652010-08-21 09:40:31 +000012133/// initializer for the out-of-line declaration 'D'.
12134void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012135 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidis8e4be0b2011-04-22 18:52:25 +000012136 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012137
Douglas Gregor926410d2012-02-21 02:22:07 +000012138 if (isStaticDataMember(D))
Richard Smitha2302242013-12-05 07:51:02 +000012139 PopExpressionEvaluationContext();
Douglas Gregor926410d2012-02-21 02:22:07 +000012140
Richard Smitha2302242013-12-05 07:51:02 +000012141 if (D->isOutOfLine())
12142 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012143}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012144
12145/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
12146/// C++ if/switch/while/for statement.
12147/// e.g: "if (int x = f()) {...}"
John McCall48871652010-08-21 09:40:31 +000012148DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012149 // C++ 6.4p2:
12150 // The declarator shall not specify a function or an array.
12151 // The type-specifier-seq shall not contain typedef and shall not declare a
12152 // new class or enumeration.
12153 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
12154 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000012155
12156 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor1fe12c92011-07-05 16:13:20 +000012157 if (!Dcl)
12158 return true;
12159
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000012160 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
12161 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012162 << D.getSourceRange();
Douglas Gregor1fe12c92011-07-05 16:13:20 +000012163 return true;
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012164 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012165
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012166 return Dcl;
12167}
Anders Carlssonf98849e2009-12-02 17:15:43 +000012168
Douglas Gregor4daf6a32011-07-28 19:11:31 +000012169void Sema::LoadExternalVTableUses() {
12170 if (!ExternalSource)
12171 return;
12172
12173 SmallVector<ExternalVTableUse, 4> VTables;
12174 ExternalSource->ReadUsedVTables(VTables);
12175 SmallVector<VTableUse, 4> NewUses;
12176 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
12177 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
12178 = VTablesUsed.find(VTables[I].Record);
12179 // Even if a definition wasn't required before, it may be required now.
12180 if (Pos != VTablesUsed.end()) {
12181 if (!Pos->second && VTables[I].DefinitionRequired)
12182 Pos->second = true;
12183 continue;
12184 }
12185
12186 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
12187 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
12188 }
12189
12190 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
12191}
12192
Douglas Gregor88d292c2010-05-13 16:44:06 +000012193void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
12194 bool DefinitionRequired) {
12195 // Ignore any vtable uses in unevaluated operands or for classes that do
12196 // not have a vtable.
12197 if (!Class->isDynamicClass() || Class->isDependentContext() ||
John McCallf413f5e2013-05-03 00:10:13 +000012198 CurContext->isDependentContext() || isUnevaluatedContext())
Rafael Espindolae7113ca2010-03-10 02:19:29 +000012199 return;
12200
Douglas Gregor88d292c2010-05-13 16:44:06 +000012201 // Try to insert this class into the map.
Douglas Gregor4daf6a32011-07-28 19:11:31 +000012202 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000012203 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
12204 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
12205 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
12206 if (!Pos.second) {
Daniel Dunbar53217762010-05-25 00:33:13 +000012207 // If we already had an entry, check to see if we are promoting this vtable
12208 // to required a definition. If so, we need to reappend to the VTableUses
12209 // list, since we may have already processed the first entry.
12210 if (DefinitionRequired && !Pos.first->second) {
12211 Pos.first->second = true;
12212 } else {
12213 // Otherwise, we can early exit.
12214 return;
12215 }
Hans Wennborg3d791542014-02-24 15:58:24 +000012216 } else {
12217 // The Microsoft ABI requires that we perform the destructor body
12218 // checks (i.e. operator delete() lookup) when the vtable is marked used, as
12219 // the deleting destructor is emitted with the vtable, not with the
12220 // destructor definition as in the Itanium ABI.
12221 // If it has a definition, we do the check at that point instead.
12222 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12223 Class->hasUserDeclaredDestructor() &&
12224 !Class->getDestructor()->isDefined() &&
12225 !Class->getDestructor()->isDeleted()) {
12226 CheckDestructor(Class->getDestructor());
12227 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000012228 }
12229
12230 // Local classes need to have their virtual members marked
12231 // immediately. For all other classes, we mark their virtual members
12232 // at the end of the translation unit.
12233 if (Class->isLocalClass())
12234 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar0547ad32010-05-11 21:32:35 +000012235 else
Douglas Gregor88d292c2010-05-13 16:44:06 +000012236 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregor0c4aad12010-05-11 20:24:17 +000012237}
12238
Douglas Gregor88d292c2010-05-13 16:44:06 +000012239bool Sema::DefineUsedVTables() {
Douglas Gregor4daf6a32011-07-28 19:11:31 +000012240 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000012241 if (VTableUses.empty())
Anders Carlsson82fccd02009-12-07 08:24:59 +000012242 return false;
Chandler Carruth88bfa5e2010-12-12 21:36:11 +000012243
Douglas Gregor88d292c2010-05-13 16:44:06 +000012244 // Note: The VTableUses vector could grow as a result of marking
12245 // the members of a class as "used", so we check the size each
Richard Smithd3b5c9082012-07-27 04:22:15 +000012246 // time through the loop and prefer indices (which are stable) to
Douglas Gregor88d292c2010-05-13 16:44:06 +000012247 // iterators (which are not).
Douglas Gregor97509692011-04-22 22:25:37 +000012248 bool DefinedAnything = false;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012249 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbar105ce6d2010-05-25 00:32:58 +000012250 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor88d292c2010-05-13 16:44:06 +000012251 if (!Class)
12252 continue;
12253
12254 SourceLocation Loc = VTableUses[I].second;
12255
Richard Smithd3b5c9082012-07-27 04:22:15 +000012256 bool DefineVTable = true;
12257
Douglas Gregor88d292c2010-05-13 16:44:06 +000012258 // If this class has a key function, but that key function is
12259 // defined in another translation unit, we don't need to emit the
12260 // vtable even though we're using it.
John McCall6bd2a892013-01-25 22:31:03 +000012261 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +000012262 if (KeyFunction && !KeyFunction->hasBody()) {
Rafael Espindolaef7fe1f2013-08-26 23:23:21 +000012263 // The key function is in another translation unit.
12264 DefineVTable = false;
12265 TemplateSpecializationKind TSK =
12266 KeyFunction->getTemplateSpecializationKind();
12267 assert(TSK != TSK_ExplicitInstantiationDefinition &&
12268 TSK != TSK_ImplicitInstantiation &&
12269 "Instantiations don't have key functions");
12270 (void)TSK;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012271 } else if (!KeyFunction) {
12272 // If we have a class with no key function that is the subject
12273 // of an explicit instantiation declaration, suppress the
12274 // vtable; it will live with the explicit instantiation
12275 // definition.
12276 bool IsExplicitInstantiationDeclaration
12277 = Class->getTemplateSpecializationKind()
12278 == TSK_ExplicitInstantiationDeclaration;
Aaron Ballman86c93902014-03-06 23:45:36 +000012279 for (auto R : Class->redecls()) {
Douglas Gregor88d292c2010-05-13 16:44:06 +000012280 TemplateSpecializationKind TSK
Aaron Ballman86c93902014-03-06 23:45:36 +000012281 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
Douglas Gregor88d292c2010-05-13 16:44:06 +000012282 if (TSK == TSK_ExplicitInstantiationDeclaration)
12283 IsExplicitInstantiationDeclaration = true;
12284 else if (TSK == TSK_ExplicitInstantiationDefinition) {
12285 IsExplicitInstantiationDeclaration = false;
12286 break;
12287 }
12288 }
12289
12290 if (IsExplicitInstantiationDeclaration)
Richard Smithd3b5c9082012-07-27 04:22:15 +000012291 DefineVTable = false;
12292 }
12293
12294 // The exception specifications for all virtual members may be needed even
12295 // if we are not providing an authoritative form of the vtable in this TU.
12296 // We may choose to emit it available_externally anyway.
12297 if (!DefineVTable) {
12298 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
12299 continue;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012300 }
12301
12302 // Mark all of the virtual members of this class as referenced, so
12303 // that we can build a vtable. Then, tell the AST consumer that a
12304 // vtable for this class is required.
Douglas Gregor97509692011-04-22 22:25:37 +000012305 DefinedAnything = true;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012306 MarkVirtualMembersReferenced(Loc, Class);
12307 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
12308 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
12309
12310 // Optionally warn if we're emitting a weak vtable.
Rafael Espindola3ae00052013-05-13 00:12:11 +000012311 if (Class->isExternallyVisible() &&
Douglas Gregor88d292c2010-05-13 16:44:06 +000012312 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Douglas Gregor34bc6e52011-09-23 19:04:03 +000012313 const FunctionDecl *KeyFunctionDef = 0;
12314 if (!KeyFunction ||
12315 (KeyFunction->hasBody(KeyFunctionDef) &&
12316 KeyFunctionDef->isInlined()))
David Blaikie72b61202011-12-09 18:32:50 +000012317 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
12318 TSK_ExplicitInstantiationDefinition
12319 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
12320 << Class;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012321 }
Anders Carlssonf98849e2009-12-02 17:15:43 +000012322 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000012323 VTableUses.clear();
12324
Douglas Gregor97509692011-04-22 22:25:37 +000012325 return DefinedAnything;
Anders Carlssonf98849e2009-12-02 17:15:43 +000012326}
Anders Carlsson82fccd02009-12-07 08:24:59 +000012327
Richard Smithd3b5c9082012-07-27 04:22:15 +000012328void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
12329 const CXXRecordDecl *RD) {
Aaron Ballman2b124d12014-03-13 16:36:16 +000012330 for (const auto *I : RD->methods())
12331 if (I->isVirtual() && !I->isPure())
12332 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
Richard Smithd3b5c9082012-07-27 04:22:15 +000012333}
12334
Rafael Espindola5b334082010-03-26 00:36:59 +000012335void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
12336 const CXXRecordDecl *RD) {
Richard Smith4ff9ff92012-07-07 06:59:51 +000012337 // Mark all functions which will appear in RD's vtable as used.
12338 CXXFinalOverriderMap FinalOverriders;
12339 RD->getFinalOverriders(FinalOverriders);
12340 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
12341 E = FinalOverriders.end();
12342 I != E; ++I) {
12343 for (OverridingMethods::const_iterator OI = I->second.begin(),
12344 OE = I->second.end();
12345 OI != OE; ++OI) {
12346 assert(OI->second.size() > 0 && "no final overrider");
12347 CXXMethodDecl *Overrider = OI->second.front().Method;
Anders Carlsson82fccd02009-12-07 08:24:59 +000012348
Richard Smith4ff9ff92012-07-07 06:59:51 +000012349 // C++ [basic.def.odr]p2:
12350 // [...] A virtual member function is used if it is not pure. [...]
12351 if (!Overrider->isPure())
12352 MarkFunctionReferenced(Loc, Overrider);
12353 }
Anders Carlsson82fccd02009-12-07 08:24:59 +000012354 }
Rafael Espindola5b334082010-03-26 00:36:59 +000012355
12356 // Only classes that have virtual bases need a VTT.
12357 if (RD->getNumVBases() == 0)
12358 return;
12359
Aaron Ballman574705e2014-03-13 15:41:46 +000012360 for (const auto &I : RD->bases()) {
Rafael Espindola5b334082010-03-26 00:36:59 +000012361 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +000012362 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Rafael Espindola5b334082010-03-26 00:36:59 +000012363 if (Base->getNumVBases() == 0)
12364 continue;
12365 MarkVirtualMembersReferenced(Loc, Base);
12366 }
Anders Carlsson82fccd02009-12-07 08:24:59 +000012367}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012368
12369/// SetIvarInitializers - This routine builds initialization ASTs for the
12370/// Objective-C implementation whose ivars need be initialized.
12371void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000012372 if (!getLangOpts().CPlusPlus)
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012373 return;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +000012374 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000012375 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012376 CollectIvarsToConstructOrDestruct(OID, ivars);
12377 if (ivars.empty())
12378 return;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000012379 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012380 for (unsigned i = 0; i < ivars.size(); i++) {
12381 FieldDecl *Field = ivars[i];
Douglas Gregor527786e2010-05-20 02:24:22 +000012382 if (Field->isInvalidDecl())
12383 continue;
12384
Alexis Hunt1d792652011-01-08 20:30:50 +000012385 CXXCtorInitializer *Member;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012386 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
12387 InitializationKind InitKind =
12388 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
Dmitri Gribenko78852e92013-05-05 20:40:26 +000012389
12390 InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
12391 ExprResult MemberInit =
12392 InitSeq.Perform(*this, InitEntity, InitKind, None);
Douglas Gregora40433a2010-12-07 00:41:46 +000012393 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012394 // Note, MemberInit could actually come back empty if no initialization
12395 // is required (e.g., because it would call a trivial default constructor)
12396 if (!MemberInit.get() || MemberInit.isInvalid())
12397 continue;
John McCallacf0ee52010-10-08 02:01:28 +000012398
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012399 Member =
Alexis Hunt1d792652011-01-08 20:30:50 +000012400 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
12401 SourceLocation(),
12402 MemberInit.takeAs<Expr>(),
12403 SourceLocation());
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012404 AllToInit.push_back(Member);
Douglas Gregor527786e2010-05-20 02:24:22 +000012405
12406 // Be sure that the destructor is accessible and is marked as referenced.
12407 if (const RecordType *RecordTy
12408 = Context.getBaseElementType(Field->getType())
12409 ->getAs<RecordType>()) {
12410 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregore71edda2010-07-01 22:47:18 +000012411 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000012412 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor527786e2010-05-20 02:24:22 +000012413 CheckDestructorAccess(Field->getLocation(), Destructor,
12414 PDiag(diag::err_access_dtor_ivar)
12415 << Context.getBaseElementType(Field->getType()));
12416 }
12417 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012418 }
12419 ObjCImplementation->setIvarInitializers(Context,
12420 AllToInit.data(), AllToInit.size());
12421 }
12422}
Alexis Hunt6118d662011-05-04 05:57:24 +000012423
Alexis Hunt27a761d2011-05-04 23:29:54 +000012424static
12425void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
12426 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
12427 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
12428 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
12429 Sema &S) {
Alexis Hunt27a761d2011-05-04 23:29:54 +000012430 if (Ctor->isInvalidDecl())
12431 return;
12432
Richard Smith802c4b72012-08-23 06:16:52 +000012433 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
12434
12435 // Target may not be determinable yet, for instance if this is a dependent
12436 // call in an uninstantiated template.
12437 if (Target) {
12438 const FunctionDecl *FNTarget = 0;
12439 (void)Target->hasBody(FNTarget);
12440 Target = const_cast<CXXConstructorDecl*>(
12441 cast_or_null<CXXConstructorDecl>(FNTarget));
12442 }
Alexis Hunt27a761d2011-05-04 23:29:54 +000012443
12444 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
12445 // Avoid dereferencing a null pointer here.
12446 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
12447
12448 if (!Current.insert(Canonical))
12449 return;
12450
12451 // We know that beyond here, we aren't chaining into a cycle.
12452 if (!Target || !Target->isDelegatingConstructor() ||
12453 Target->isInvalidDecl() || Valid.count(TCanonical)) {
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012454 Valid.insert(Current.begin(), Current.end());
Alexis Hunt27a761d2011-05-04 23:29:54 +000012455 Current.clear();
12456 // We've hit a cycle.
12457 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
12458 Current.count(TCanonical)) {
12459 // If we haven't diagnosed this cycle yet, do so now.
12460 if (!Invalid.count(TCanonical)) {
12461 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Alexis Hunte2622992011-05-05 00:05:47 +000012462 diag::warn_delegating_ctor_cycle)
Alexis Hunt27a761d2011-05-04 23:29:54 +000012463 << Ctor;
12464
Richard Smith802c4b72012-08-23 06:16:52 +000012465 // Don't add a note for a function delegating directly to itself.
Alexis Hunt27a761d2011-05-04 23:29:54 +000012466 if (TCanonical != Canonical)
12467 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
12468
12469 CXXConstructorDecl *C = Target;
12470 while (C->getCanonicalDecl() != Canonical) {
Richard Smith802c4b72012-08-23 06:16:52 +000012471 const FunctionDecl *FNTarget = 0;
Alexis Hunt27a761d2011-05-04 23:29:54 +000012472 (void)C->getTargetConstructor()->hasBody(FNTarget);
12473 assert(FNTarget && "Ctor cycle through bodiless function");
12474
Richard Smith802c4b72012-08-23 06:16:52 +000012475 C = const_cast<CXXConstructorDecl*>(
12476 cast<CXXConstructorDecl>(FNTarget));
Alexis Hunt27a761d2011-05-04 23:29:54 +000012477 S.Diag(C->getLocation(), diag::note_which_delegates_to);
12478 }
12479 }
12480
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012481 Invalid.insert(Current.begin(), Current.end());
Alexis Hunt27a761d2011-05-04 23:29:54 +000012482 Current.clear();
12483 } else {
12484 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
12485 }
12486}
12487
12488
Alexis Hunt6118d662011-05-04 05:57:24 +000012489void Sema::CheckDelegatingCtorCycles() {
12490 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
12491
Douglas Gregorbae31202011-07-27 21:57:17 +000012492 for (DelegatingCtorDeclsType::iterator
12493 I = DelegatingCtorDecls.begin(ExternalSource),
Alexis Hunt27a761d2011-05-04 23:29:54 +000012494 E = DelegatingCtorDecls.end();
Richard Smith802c4b72012-08-23 06:16:52 +000012495 I != E; ++I)
12496 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Alexis Hunt27a761d2011-05-04 23:29:54 +000012497
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012498 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
12499 CE = Invalid.end();
12500 CI != CE; ++CI)
Alexis Hunt27a761d2011-05-04 23:29:54 +000012501 (*CI)->setInvalidDecl();
Alexis Hunt6118d662011-05-04 05:57:24 +000012502}
Peter Collingbourne7277fe82011-10-02 23:49:40 +000012503
Douglas Gregor3024f072012-04-16 07:05:22 +000012504namespace {
12505 /// \brief AST visitor that finds references to the 'this' expression.
12506 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
12507 Sema &S;
12508
12509 public:
12510 explicit FindCXXThisExpr(Sema &S) : S(S) { }
12511
12512 bool VisitCXXThisExpr(CXXThisExpr *E) {
12513 S.Diag(E->getLocation(), diag::err_this_static_member_func)
12514 << E->isImplicit();
12515 return false;
12516 }
12517 };
12518}
12519
12520bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
12521 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12522 if (!TSInfo)
12523 return false;
12524
12525 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +000012526 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor3024f072012-04-16 07:05:22 +000012527 if (!ProtoTL)
12528 return false;
12529
12530 // C++11 [expr.prim.general]p3:
12531 // [The expression this] shall not appear before the optional
12532 // cv-qualifier-seq and it shall not appear within the declaration of a
12533 // static member function (although its type and value category are defined
12534 // within a static member function as they are within a non-static member
12535 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumi40edb2a2012-04-21 09:40:04 +000012536 // until the complete declarator is known. - end note ]
David Blaikie6adc78e2013-02-18 22:06:02 +000012537 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor3024f072012-04-16 07:05:22 +000012538 FindCXXThisExpr Finder(*this);
12539
12540 // If the return type came after the cv-qualifier-seq, check it now.
12541 if (Proto->hasTrailingReturn() &&
Alp Toker42a16a62014-01-25 23:51:36 +000012542 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
Douglas Gregor3024f072012-04-16 07:05:22 +000012543 return true;
12544
12545 // Check the exception specification.
Douglas Gregor433e0532012-04-16 18:27:27 +000012546 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
12547 return true;
12548
12549 return checkThisInStaticMemberFunctionAttributes(Method);
12550}
12551
12552bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
12553 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12554 if (!TSInfo)
12555 return false;
12556
12557 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +000012558 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor433e0532012-04-16 18:27:27 +000012559 if (!ProtoTL)
12560 return false;
12561
David Blaikie6adc78e2013-02-18 22:06:02 +000012562 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor433e0532012-04-16 18:27:27 +000012563 FindCXXThisExpr Finder(*this);
12564
Douglas Gregor3024f072012-04-16 07:05:22 +000012565 switch (Proto->getExceptionSpecType()) {
Richard Smithf623c962012-04-17 00:58:00 +000012566 case EST_Uninstantiated:
Richard Smithd3b5c9082012-07-27 04:22:15 +000012567 case EST_Unevaluated:
Douglas Gregor3024f072012-04-16 07:05:22 +000012568 case EST_BasicNoexcept:
Douglas Gregor3024f072012-04-16 07:05:22 +000012569 case EST_DynamicNone:
12570 case EST_MSAny:
12571 case EST_None:
12572 break;
Douglas Gregor433e0532012-04-16 18:27:27 +000012573
Douglas Gregor3024f072012-04-16 07:05:22 +000012574 case EST_ComputedNoexcept:
12575 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
12576 return true;
Douglas Gregor433e0532012-04-16 18:27:27 +000012577
Douglas Gregor3024f072012-04-16 07:05:22 +000012578 case EST_Dynamic:
12579 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
Douglas Gregor433e0532012-04-16 18:27:27 +000012580 EEnd = Proto->exception_end();
Douglas Gregor3024f072012-04-16 07:05:22 +000012581 E != EEnd; ++E) {
12582 if (!Finder.TraverseType(*E))
12583 return true;
12584 }
12585 break;
12586 }
Douglas Gregor433e0532012-04-16 18:27:27 +000012587
12588 return false;
Douglas Gregor3024f072012-04-16 07:05:22 +000012589}
12590
12591bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
12592 FindCXXThisExpr Finder(*this);
12593
12594 // Check attributes.
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012595 for (const auto *A : Method->attrs()) {
Douglas Gregor3024f072012-04-16 07:05:22 +000012596 // FIXME: This should be emitted by tblgen.
12597 Expr *Arg = 0;
12598 ArrayRef<Expr *> Args;
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012599 if (const auto *G = dyn_cast<GuardedByAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000012600 Arg = G->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012601 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000012602 Arg = G->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012603 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000012604 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012605 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000012606 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012607 else if (const auto *ELF = dyn_cast<ExclusiveLockFunctionAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000012608 Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012609 else if (const auto *SLF = dyn_cast<SharedLockFunctionAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000012610 Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012611 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
Douglas Gregor3024f072012-04-16 07:05:22 +000012612 Arg = ETLF->getSuccessValue();
12613 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012614 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
Douglas Gregor3024f072012-04-16 07:05:22 +000012615 Arg = STLF->getSuccessValue();
12616 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012617 } else if (const auto *UF = dyn_cast<UnlockFunctionAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000012618 Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012619 else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000012620 Arg = LR->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012621 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000012622 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012623 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
Aaron Ballmanefe348e2014-02-18 17:36:50 +000012624 Args = ArrayRef<Expr *>(RC->args_begin(), RC->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012625 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
Aaron Ballman9e9d1842014-02-21 21:05:14 +000012626 Args = ArrayRef<Expr *>(AC->args_begin(), AC->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012627 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
12628 Args = ArrayRef<Expr *>(AC->args_begin(), AC->args_size());
12629 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
Aaron Ballman9e9d1842014-02-21 21:05:14 +000012630 Args = ArrayRef<Expr *>(RC->args_begin(), RC->args_size());
Douglas Gregor3024f072012-04-16 07:05:22 +000012631
12632 if (Arg && !Finder.TraverseStmt(Arg))
12633 return true;
12634
12635 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
12636 if (!Finder.TraverseStmt(Args[I]))
12637 return true;
12638 }
12639 }
12640
12641 return false;
12642}
12643
Douglas Gregor433e0532012-04-16 18:27:27 +000012644void
12645Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
12646 ArrayRef<ParsedType> DynamicExceptions,
12647 ArrayRef<SourceRange> DynamicExceptionRanges,
12648 Expr *NoexceptExpr,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000012649 SmallVectorImpl<QualType> &Exceptions,
Douglas Gregor433e0532012-04-16 18:27:27 +000012650 FunctionProtoType::ExtProtoInfo &EPI) {
12651 Exceptions.clear();
12652 EPI.ExceptionSpecType = EST;
12653 if (EST == EST_Dynamic) {
12654 Exceptions.reserve(DynamicExceptions.size());
12655 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
12656 // FIXME: Preserve type source info.
12657 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
12658
12659 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
12660 collectUnexpandedParameterPacks(ET, Unexpanded);
12661 if (!Unexpanded.empty()) {
12662 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
12663 UPPC_ExceptionType,
12664 Unexpanded);
12665 continue;
12666 }
12667
12668 // Check that the type is valid for an exception spec, and
12669 // drop it if not.
12670 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
12671 Exceptions.push_back(ET);
12672 }
12673 EPI.NumExceptions = Exceptions.size();
12674 EPI.Exceptions = Exceptions.data();
12675 return;
12676 }
12677
12678 if (EST == EST_ComputedNoexcept) {
12679 // If an error occurred, there's no expression here.
12680 if (NoexceptExpr) {
12681 assert((NoexceptExpr->isTypeDependent() ||
12682 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
12683 Context.BoolTy) &&
12684 "Parser should have made sure that the expression is boolean");
12685 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
12686 EPI.ExceptionSpecType = EST_BasicNoexcept;
12687 return;
12688 }
12689
12690 if (!NoexceptExpr->isValueDependent())
12691 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0,
Douglas Gregore2b37442012-05-04 22:38:52 +000012692 diag::err_noexcept_needs_constant_expression,
Douglas Gregor433e0532012-04-16 18:27:27 +000012693 /*AllowFold*/ false).take();
12694 EPI.NoexceptExpr = NoexceptExpr;
12695 }
12696 return;
12697 }
12698}
12699
Peter Collingbourne7277fe82011-10-02 23:49:40 +000012700/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
12701Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
12702 // Implicitly declared functions (e.g. copy constructors) are
12703 // __host__ __device__
12704 if (D->isImplicit())
12705 return CFT_HostDevice;
12706
12707 if (D->hasAttr<CUDAGlobalAttr>())
12708 return CFT_Global;
12709
12710 if (D->hasAttr<CUDADeviceAttr>()) {
12711 if (D->hasAttr<CUDAHostAttr>())
12712 return CFT_HostDevice;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012713 return CFT_Device;
Peter Collingbourne7277fe82011-10-02 23:49:40 +000012714 }
12715
12716 return CFT_Host;
12717}
12718
12719bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
12720 CUDAFunctionTarget CalleeTarget) {
12721 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
12722 // Callable from the device only."
12723 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
12724 return true;
12725
12726 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
12727 // Callable from the host only."
12728 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
12729 // Callable from the host only."
12730 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
12731 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
12732 return true;
12733
12734 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
12735 return true;
12736
12737 return false;
12738}
John McCall5e77d762013-04-16 07:28:30 +000012739
12740/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
12741///
12742MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
12743 SourceLocation DeclStart,
12744 Declarator &D, Expr *BitWidth,
12745 InClassInitStyle InitStyle,
12746 AccessSpecifier AS,
12747 AttributeList *MSPropertyAttr) {
12748 IdentifierInfo *II = D.getIdentifier();
12749 if (!II) {
12750 Diag(DeclStart, diag::err_anonymous_property);
12751 return NULL;
12752 }
12753 SourceLocation Loc = D.getIdentifierLoc();
12754
12755 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12756 QualType T = TInfo->getType();
12757 if (getLangOpts().CPlusPlus) {
12758 CheckExtraCXXDefaultArguments(D);
12759
12760 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
12761 UPPC_DataMemberType)) {
12762 D.setInvalidType();
12763 T = Context.IntTy;
12764 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
12765 }
12766 }
12767
12768 DiagnoseFunctionSpecifiers(D.getDeclSpec());
12769
12770 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
12771 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
12772 diag::err_invalid_thread)
12773 << DeclSpec::getSpecifierName(TSCS);
12774
12775 // Check to see if this name was declared as a member previously
12776 NamedDecl *PrevDecl = 0;
12777 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
12778 LookupName(Previous, S);
12779 switch (Previous.getResultKind()) {
12780 case LookupResult::Found:
12781 case LookupResult::FoundUnresolvedValue:
12782 PrevDecl = Previous.getAsSingle<NamedDecl>();
12783 break;
12784
12785 case LookupResult::FoundOverloaded:
12786 PrevDecl = Previous.getRepresentativeDecl();
12787 break;
12788
12789 case LookupResult::NotFound:
12790 case LookupResult::NotFoundInCurrentInstantiation:
12791 case LookupResult::Ambiguous:
12792 break;
12793 }
12794
12795 if (PrevDecl && PrevDecl->isTemplateParameter()) {
12796 // Maybe we will complain about the shadowed template parameter.
12797 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12798 // Just pretend that we didn't see the previous declaration.
12799 PrevDecl = 0;
12800 }
12801
12802 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
12803 PrevDecl = 0;
12804
12805 SourceLocation TSSL = D.getLocStart();
John McCall5e77d762013-04-16 07:28:30 +000012806 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
Richard Smithf7981722013-11-22 09:01:48 +000012807 MSPropertyDecl *NewPD = MSPropertyDecl::Create(
12808 Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId);
John McCall5e77d762013-04-16 07:28:30 +000012809 ProcessDeclAttributes(TUScope, NewPD, D);
12810 NewPD->setAccess(AS);
12811
12812 if (NewPD->isInvalidDecl())
12813 Record->setInvalidDecl();
12814
12815 if (D.getDeclSpec().isModulePrivateSpecified())
12816 NewPD->setModulePrivate();
12817
12818 if (NewPD->isInvalidDecl() && PrevDecl) {
12819 // Don't introduce NewFD into scope; there's already something
12820 // with the same name in the same scope.
12821 } else if (II) {
12822 PushOnScopeChains(NewPD, S);
12823 } else
12824 Record->addDecl(NewPD);
12825
12826 return NewPD;
12827}