blob: 1ee4d53ab0caccd6139b08ce7ebc9550a15f9727 [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"
Richard Trieu4fc85362012-06-14 23:11:34 +000021#include "clang/AST/EvaluatedExprVisitor.h"
Alexis Huntc5575cc2011-02-26 19:13:13 +000022#include "clang/AST/ExprCXX.h"
Douglas Gregorb139cd52010-05-01 20:49:11 +000023#include "clang/AST/RecordLayout.h"
Douglas Gregor3024f072012-04-16 07:05:22 +000024#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregorb139cd52010-05-01 20:49:11 +000025#include "clang/AST/StmtVisitor.h"
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +000026#include "clang/AST/TypeLoc.h"
Douglas Gregordff6a8e2008-10-22 21:13:31 +000027#include "clang/AST/TypeOrdering.h"
Anders Carlssond624e162009-08-26 23:45:07 +000028#include "clang/Basic/PartialDiagnostic.h"
Aaron Ballman02df2e02012-12-09 17:45:41 +000029#include "clang/Basic/TargetInfo.h"
Richard Smithf4198b72013-07-23 08:14:48 +000030#include "clang/Lex/LiteralSupport.h"
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +000031#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000032#include "clang/Sema/CXXFieldCollector.h"
33#include "clang/Sema/DeclSpec.h"
34#include "clang/Sema/Initialization.h"
35#include "clang/Sema/Lookup.h"
36#include "clang/Sema/ParsedTemplate.h"
37#include "clang/Sema/Scope.h"
38#include "clang/Sema/ScopeInfo.h"
Reid Klecknerd60b82f2014-11-17 23:36:45 +000039#include "clang/Sema/Template.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.
Aaron Ballmanb088fbe2014-03-17 15:38:09 +0000215 for (const auto &E : Proto->exceptions())
David Blaikie82e95a32014-11-19 07:49:47 +0000216 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
Aaron Ballmanb088fbe2014-03-17 15:38:09 +0000217 Exceptions.push_back(E);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000218}
219
Richard Smith938f40b2011-06-11 17:19:42 +0000220void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
Richard Smithd3b5c9082012-07-27 04:22:15 +0000221 if (!E || ComputedEST == EST_MSAny)
Richard Smith938f40b2011-06-11 17:19:42 +0000222 return;
223
224 // FIXME:
225 //
226 // C++0x [except.spec]p14:
NAKAMURA Takumi53648472011-06-21 03:19:28 +0000227 // [An] implicit exception-specification specifies the type-id T if and
228 // only if T is allowed by the exception-specification of a function directly
229 // invoked by f's implicit definition; f shall allow all exceptions if any
Richard Smith938f40b2011-06-11 17:19:42 +0000230 // function it directly invokes allows all exceptions, and f shall allow no
231 // exceptions if every function it directly invokes allows no exceptions.
232 //
233 // Note in particular that if an implicit exception-specification is generated
234 // for a function containing a throw-expression, that specification can still
235 // be noexcept(true).
236 //
237 // Note also that 'directly invoked' is not defined in the standard, and there
238 // is no indication that we should only consider potentially-evaluated calls.
239 //
240 // Ultimately we should implement the intent of the standard: the exception
241 // specification should be the set of exceptions which can be thrown by the
242 // implicit definition. For now, we assume that any non-nothrow expression can
243 // throw any exception.
244
Richard Smithf623c962012-04-17 00:58:00 +0000245 if (Self->canThrow(E))
Richard Smith938f40b2011-06-11 17:19:42 +0000246 ComputedEST = EST_None;
247}
248
Anders Carlssonc80a1272009-08-25 02:29:20 +0000249bool
John McCallb268a282010-08-23 23:25:46 +0000250Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump11289f42009-09-09 15:08:12 +0000251 SourceLocation EqualLoc) {
Anders Carlsson114056f2009-08-25 13:46:13 +0000252 if (RequireCompleteType(Param->getLocation(), Param->getType(),
253 diag::err_typecheck_decl_incomplete_type)) {
254 Param->setInvalidDecl();
255 return true;
256 }
257
Anders Carlssonc80a1272009-08-25 02:29:20 +0000258 // C++ [dcl.fct.default]p5
259 // A default argument expression is implicitly converted (clause
260 // 4) to the parameter type. The default argument expression has
261 // the same semantic constraints as the initializer expression in
262 // a declaration of a variable of the parameter type, using the
263 // copy-initialization semantics (8.5).
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +0000264 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
265 Param);
Douglas Gregor85dabae2009-12-16 01:38:02 +0000266 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
267 EqualLoc);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +0000268 InitializationSequence InitSeq(*this, Entity, Kind, Arg);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000269 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
Eli Friedman5f101b92009-12-22 02:46:13 +0000270 if (Result.isInvalid())
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000271 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000272 Arg = Result.getAs<Expr>();
Anders Carlssonc80a1272009-08-25 02:29:20 +0000273
Richard Smithc406cb72013-01-17 01:17:56 +0000274 CheckCompletedExpr(Arg, EqualLoc);
John McCall5d413782010-12-06 08:20:24 +0000275 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000276
Anders Carlssonc80a1272009-08-25 02:29:20 +0000277 // Okay: add the default argument to the parameter
278 Param->setDefaultArg(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000279
Douglas Gregor758cb672010-10-12 18:23:32 +0000280 // We have already instantiated this parameter; provide each of the
281 // instantiations with the uninstantiated default argument.
282 UnparsedDefaultArgInstantiationsMap::iterator InstPos
283 = UnparsedDefaultArgInstantiations.find(Param);
284 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
285 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
286 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
287
288 // We're done tracking this parameter's instantiations.
289 UnparsedDefaultArgInstantiations.erase(InstPos);
290 }
291
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000292 return false;
Anders Carlssonc80a1272009-08-25 02:29:20 +0000293}
294
Chris Lattner58258242008-04-10 02:22:51 +0000295/// ActOnParamDefaultArgument - Check whether the default argument
296/// provided for a function parameter is well-formed. If so, attach it
297/// to the parameter declaration.
Chris Lattner199abbc2008-04-08 05:04:30 +0000298void
John McCall48871652010-08-21 09:40:31 +0000299Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCallb268a282010-08-23 23:25:46 +0000300 Expr *DefaultArg) {
301 if (!param || !DefaultArg)
Douglas Gregor71a57182009-06-22 23:20:33 +0000302 return;
Mike Stump11289f42009-09-09 15:08:12 +0000303
John McCall48871652010-08-21 09:40:31 +0000304 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson84613c42009-06-12 16:51:40 +0000305 UnparsedDefaultArgLocs.erase(Param);
306
Chris Lattner199abbc2008-04-08 05:04:30 +0000307 // Default arguments are only permitted in C++
David Blaikiebbafb8a2012-03-11 07:00:24 +0000308 if (!getLangOpts().CPlusPlus) {
Chris Lattner3b054132008-11-19 05:08:23 +0000309 Diag(EqualLoc, diag::err_param_default_argument)
310 << DefaultArg->getSourceRange();
Douglas Gregor4d87df52008-12-16 21:30:33 +0000311 Param->setInvalidDecl();
Chris Lattner199abbc2008-04-08 05:04:30 +0000312 return;
313 }
314
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000315 // Check for unexpanded parameter packs.
316 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
317 Param->setInvalidDecl();
318 return;
319 }
320
Anders Carlssonf1c26952009-08-25 01:02:06 +0000321 // Check that the default argument is well-formed
John McCallb268a282010-08-23 23:25:46 +0000322 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
323 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlssonf1c26952009-08-25 01:02:06 +0000324 Param->setInvalidDecl();
325 return;
326 }
Mike Stump11289f42009-09-09 15:08:12 +0000327
John McCallb268a282010-08-23 23:25:46 +0000328 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner199abbc2008-04-08 05:04:30 +0000329}
330
Douglas Gregor58354032008-12-24 00:01:03 +0000331/// ActOnParamUnparsedDefaultArgument - We've seen a default
332/// argument for a function parameter, but we can't parse it yet
333/// because we're inside a class definition. Note that this default
334/// argument will be parsed later.
John McCall48871652010-08-21 09:40:31 +0000335void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson84613c42009-06-12 16:51:40 +0000336 SourceLocation EqualLoc,
337 SourceLocation ArgLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000338 if (!param)
339 return;
Mike Stump11289f42009-09-09 15:08:12 +0000340
John McCall48871652010-08-21 09:40:31 +0000341 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Nick Lewycky0f292892013-09-22 10:06:57 +0000342 Param->setUnparsedDefaultArg();
Anders Carlsson84613c42009-06-12 16:51:40 +0000343 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor58354032008-12-24 00:01:03 +0000344}
345
Douglas Gregor4d87df52008-12-16 21:30:33 +0000346/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
347/// the default argument for the parameter param failed.
Serge Pavlovb4b35782014-07-22 01:54:49 +0000348void Sema::ActOnParamDefaultArgumentError(Decl *param,
349 SourceLocation EqualLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000350 if (!param)
351 return;
Mike Stump11289f42009-09-09 15:08:12 +0000352
John McCall48871652010-08-21 09:40:31 +0000353 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson84613c42009-06-12 16:51:40 +0000354 Param->setInvalidDecl();
Anders Carlsson84613c42009-06-12 16:51:40 +0000355 UnparsedDefaultArgLocs.erase(Param);
Serge Pavlovb4b35782014-07-22 01:54:49 +0000356 Param->setDefaultArg(new(Context)
Fariborz Jahanian7bd22e92014-10-01 18:03:51 +0000357 OpaqueValueExpr(EqualLoc,
358 Param->getType().getNonReferenceType(),
359 VK_RValue));
Douglas Gregor4d87df52008-12-16 21:30:33 +0000360}
361
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000362/// CheckExtraCXXDefaultArguments - Check for any extra default
363/// arguments in the declarator, which is not a function declaration
364/// or definition and therefore is not permitted to have default
365/// arguments. This routine should be invoked for every declarator
366/// that is not a function declaration or definition.
367void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
368 // C++ [dcl.fct.default]p3
369 // A default argument expression shall be specified only in the
370 // parameter-declaration-clause of a function declaration or in a
371 // template-parameter (14.1). It shall not be specified for a
372 // parameter pack. If it is specified in a
373 // parameter-declaration-clause, it shall not occur within a
374 // declarator or abstract-declarator of a parameter-declaration.
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000375 bool MightBeFunction = D.isFunctionDeclarationContext();
Chris Lattner83f095c2009-03-28 19:18:32 +0000376 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000377 DeclaratorChunk &chunk = D.getTypeObject(i);
378 if (chunk.Kind == DeclaratorChunk::Function) {
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000379 if (MightBeFunction) {
380 // This is a function declaration. It can have default arguments, but
381 // keep looking in case its return type is a function type with default
382 // arguments.
383 MightBeFunction = false;
384 continue;
385 }
Alp Tokerc5350722014-02-26 22:27:52 +0000386 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
387 ++argIdx) {
388 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
Douglas Gregor58354032008-12-24 00:01:03 +0000389 if (Param->hasUnparsedDefaultArg()) {
Alp Tokerc5350722014-02-26 22:27:52 +0000390 CachedTokens *Toks = chunk.Fun.Params[argIdx].DefaultArgTokens;
David Majnemerb3c6d522015-01-13 07:42:33 +0000391 SourceRange SR;
392 if (Toks->size() > 1)
393 SR = SourceRange((*Toks)[1].getLocation(),
394 Toks->back().getLocation());
395 else
396 SR = UnparsedDefaultArgLocs[Param];
Douglas Gregor4d87df52008-12-16 21:30:33 +0000397 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
David Majnemerb3c6d522015-01-13 07:42:33 +0000398 << SR;
Douglas Gregor4d87df52008-12-16 21:30:33 +0000399 delete Toks;
Craig Topperc3ec1492014-05-26 06:22:03 +0000400 chunk.Fun.Params[argIdx].DefaultArgTokens = nullptr;
Douglas Gregor58354032008-12-24 00:01:03 +0000401 } else if (Param->getDefaultArg()) {
402 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
403 << Param->getDefaultArg()->getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +0000404 Param->setDefaultArg(nullptr);
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000405 }
406 }
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000407 } else if (chunk.Kind != DeclaratorChunk::Paren) {
408 MightBeFunction = false;
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000409 }
410 }
411}
412
David Majnemer502b0ed2013-06-25 23:09:30 +0000413static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
414 for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
415 const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
416 if (!PVD->hasDefaultArg())
417 return false;
418 if (!PVD->hasInheritedDefaultArg())
419 return true;
420 }
421 return false;
422}
423
Craig Toppere4794282012-09-21 04:33:26 +0000424/// MergeCXXFunctionDecl - Merge two declarations of the same C++
425/// function, once we already know that they have the same
426/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
427/// error, false otherwise.
James Molloye9430032012-03-13 08:55:35 +0000428bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
429 Scope *S) {
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000430 bool Invalid = false;
431
Chris Lattner199abbc2008-04-08 05:04:30 +0000432 // C++ [dcl.fct.default]p4:
Chris Lattner199abbc2008-04-08 05:04:30 +0000433 // For non-template functions, default arguments can be added in
434 // later declarations of a function in the same
435 // scope. Declarations in different scopes have completely
436 // distinct sets of default arguments. That is, declarations in
437 // inner scopes do not acquire default arguments from
438 // declarations in outer scopes, and vice versa. In a given
439 // function declaration, all parameters subsequent to a
440 // parameter with a default argument shall have default
441 // arguments supplied in this or previous declarations. A
442 // default argument shall not be redefined by a later
443 // declaration (not even to the same value).
Douglas Gregorc732aba2009-09-11 18:44:32 +0000444 //
445 // C++ [dcl.fct.default]p6:
Richard Smith541b38b2013-09-20 01:15:31 +0000446 // Except for member functions of class templates, the default arguments
447 // in a member function definition that appears outside of the class
448 // definition are added to the set of default arguments provided by the
Douglas Gregorc732aba2009-09-11 18:44:32 +0000449 // member function declaration in the class definition.
Chris Lattner199abbc2008-04-08 05:04:30 +0000450 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
451 ParmVarDecl *OldParam = Old->getParamDecl(p);
452 ParmVarDecl *NewParam = New->getParamDecl(p);
453
James Molloye9430032012-03-13 08:55:35 +0000454 bool OldParamHasDfl = OldParam->hasDefaultArg();
455 bool NewParamHasDfl = NewParam->hasDefaultArg();
456
Richard Smith541b38b2013-09-20 01:15:31 +0000457 // The declaration context corresponding to the scope is the semantic
458 // parent, unless this is a local function declaration, in which case
459 // it is that surrounding function.
Richard Smith5971e8c2014-08-27 22:31:34 +0000460 DeclContext *ScopeDC = New->isLocalExternDecl()
461 ? New->getLexicalDeclContext()
462 : New->getDeclContext();
463 if (S && !isDeclInScope(Old, ScopeDC, S) &&
Richard Smith541b38b2013-09-20 01:15:31 +0000464 !New->getDeclContext()->isRecord())
James Molloye9430032012-03-13 08:55:35 +0000465 // Ignore default parameters of old decl if they are not in
Richard Smith541b38b2013-09-20 01:15:31 +0000466 // the same scope and this is not an out-of-line definition of
467 // a member function.
James Molloye9430032012-03-13 08:55:35 +0000468 OldParamHasDfl = false;
Richard Smith5971e8c2014-08-27 22:31:34 +0000469 if (New->isLocalExternDecl() != Old->isLocalExternDecl())
470 // If only one of these is a local function declaration, then they are
471 // declared in different scopes, even though isDeclInScope may think
472 // they're in the same scope. (If both are local, the scope check is
473 // sufficent, and if neither is local, then they are in the same scope.)
474 OldParamHasDfl = false;
James Molloye9430032012-03-13 08:55:35 +0000475
476 if (OldParamHasDfl && NewParamHasDfl) {
Francois Pichet8cb243a2011-04-10 04:58:30 +0000477
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000478 unsigned DiagDefaultParamID =
479 diag::err_param_default_argument_redefinition;
480
481 // MSVC accepts that default parameters be redefined for member functions
482 // of template class. The new default parameter's value is ignored.
483 Invalid = true;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000484 if (getLangOpts().MicrosoftExt) {
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000485 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
486 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cb243a2011-04-10 04:58:30 +0000487 // Merge the old default argument into the new parameter.
488 NewParam->setHasInheritedDefaultArg();
489 if (OldParam->hasUninstantiatedDefaultArg())
490 NewParam->setUninstantiatedDefaultArg(
491 OldParam->getUninstantiatedDefaultArg());
492 else
493 NewParam->setDefaultArg(OldParam->getInit());
Richard Smith1b98ccc2014-07-19 01:39:17 +0000494 DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000495 Invalid = false;
496 }
497 }
Douglas Gregor08dc5842010-01-13 00:12:48 +0000498
Francois Pichet8cb243a2011-04-10 04:58:30 +0000499 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
500 // hint here. Alternatively, we could walk the type-source information
501 // for NewParam to find the last source location in the type... but it
502 // isn't worth the effort right now. This is the kind of test case that
503 // is hard to get right:
Douglas Gregor08dc5842010-01-13 00:12:48 +0000504 // int f(int);
505 // void g(int (*fp)(int) = f);
506 // void g(int (*fp)(int) = &f);
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000507 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor08dc5842010-01-13 00:12:48 +0000508 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000509
510 // Look for the function declaration where the default argument was
511 // actually written, which may be a declaration prior to Old.
Nathan Sidwell55d53fe2015-01-30 14:21:35 +0000512 for (auto Older = Old; OldParam->hasInheritedDefaultArg();) {
513 Older = Older->getPreviousDecl();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000514 OldParam = Older->getParamDecl(p);
Nathan Sidwell55d53fe2015-01-30 14:21:35 +0000515 }
516
Douglas Gregorc732aba2009-09-11 18:44:32 +0000517 Diag(OldParam->getLocation(), diag::note_previous_definition)
518 << OldParam->getDefaultArgRange();
James Molloye9430032012-03-13 08:55:35 +0000519 } else if (OldParamHasDfl) {
John McCalle61b02b2010-05-04 01:53:42 +0000520 // Merge the old default argument into the new parameter.
521 // It's important to use getInit() here; getDefaultArg()
John McCall5d413782010-12-06 08:20:24 +0000522 // strips off any top-level ExprWithCleanups.
John McCallf3cd6652010-03-12 18:31:32 +0000523 NewParam->setHasInheritedDefaultArg();
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000524 if (OldParam->hasUninstantiatedDefaultArg())
525 NewParam->setUninstantiatedDefaultArg(
526 OldParam->getUninstantiatedDefaultArg());
527 else
John McCalle61b02b2010-05-04 01:53:42 +0000528 NewParam->setDefaultArg(OldParam->getInit());
James Molloye9430032012-03-13 08:55:35 +0000529 } else if (NewParamHasDfl) {
Douglas Gregorc732aba2009-09-11 18:44:32 +0000530 if (New->getDescribedFunctionTemplate()) {
531 // Paragraph 4, quoted above, only applies to non-template functions.
532 Diag(NewParam->getLocation(),
533 diag::err_param_default_argument_template_redecl)
534 << NewParam->getDefaultArgRange();
535 Diag(Old->getLocation(), diag::note_template_prev_declaration)
536 << false;
Douglas Gregor62e10f02009-10-13 17:02:54 +0000537 } else if (New->getTemplateSpecializationKind()
538 != TSK_ImplicitInstantiation &&
539 New->getTemplateSpecializationKind() != TSK_Undeclared) {
540 // C++ [temp.expr.spec]p21:
541 // Default function arguments shall not be specified in a declaration
542 // or a definition for one of the following explicit specializations:
543 // - the explicit specialization of a function template;
Douglas Gregor3362bde2009-10-13 23:52:38 +0000544 // - the explicit specialization of a member function template;
545 // - the explicit specialization of a member function of a class
Douglas Gregor62e10f02009-10-13 17:02:54 +0000546 // template where the class template specialization to which the
547 // member function specialization belongs is implicitly
548 // instantiated.
549 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
550 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
551 << New->getDeclName()
552 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000553 } else if (New->getDeclContext()->isDependentContext()) {
554 // C++ [dcl.fct.default]p6 (DR217):
555 // Default arguments for a member function of a class template shall
556 // be specified on the initial declaration of the member function
557 // within the class template.
558 //
559 // Reading the tea leaves a bit in DR217 and its reference to DR205
560 // leads me to the conclusion that one cannot add default function
561 // arguments for an out-of-line definition of a member function of a
562 // dependent type.
563 int WhichKind = 2;
564 if (CXXRecordDecl *Record
565 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
566 if (Record->getDescribedClassTemplate())
567 WhichKind = 0;
568 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
569 WhichKind = 1;
570 else
571 WhichKind = 2;
572 }
573
574 Diag(NewParam->getLocation(),
575 diag::err_param_default_argument_member_template_redecl)
576 << WhichKind
577 << NewParam->getDefaultArgRange();
578 }
Chris Lattner199abbc2008-04-08 05:04:30 +0000579 }
580 }
581
Richard Smith58c3cc12012-11-28 03:45:24 +0000582 // DR1344: If a default argument is added outside a class definition and that
583 // default argument makes the function a special member function, the program
584 // is ill-formed. This can only happen for constructors.
585 if (isa<CXXConstructorDecl>(New) &&
586 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
587 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
588 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
589 if (NewSM != OldSM) {
590 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
591 assert(NewParam->hasDefaultArg());
592 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
593 << NewParam->getDefaultArgRange() << NewSM;
594 Diag(Old->getLocation(), diag::note_previous_declaration);
595 }
596 }
597
David Majnemeree4f4022014-03-30 06:44:54 +0000598 const FunctionDecl *Def;
Richard Smith5b8b3db2012-02-20 23:28:05 +0000599 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
Richard Smitheb3c10c2011-10-01 02:31:28 +0000600 // template has a constexpr specifier then all its declarations shall
Richard Smith5b8b3db2012-02-20 23:28:05 +0000601 // contain the constexpr specifier.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000602 if (New->isConstexpr() != Old->isConstexpr()) {
603 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
604 << New << New->isConstexpr();
605 Diag(Old->getLocation(), diag::note_previous_declaration);
606 Invalid = true;
David Majnemeree4f4022014-03-30 06:44:54 +0000607 } else if (!Old->isInlined() && New->isInlined() && Old->isDefined(Def)) {
608 // C++11 [dcl.fcn.spec]p4:
609 // If the definition of a function appears in a translation unit before its
610 // first declaration as inline, the program is ill-formed.
611 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
612 Diag(Def->getLocation(), diag::note_previous_definition);
613 Invalid = true;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000614 }
615
David Majnemer502b0ed2013-06-25 23:09:30 +0000616 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
NAKAMURA Takumi3e7db842013-07-17 17:57:52 +0000617 // argument expression, that declaration shall be a definition and shall be
David Majnemer502b0ed2013-06-25 23:09:30 +0000618 // the only declaration of the function or function template in the
619 // translation unit.
620 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
621 functionDeclHasDefaultArgument(Old)) {
622 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
623 Diag(Old->getLocation(), diag::note_previous_declaration);
624 Invalid = true;
625 }
626
Douglas Gregorf40863c2010-02-12 07:32:17 +0000627 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000628 Invalid = true;
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000629
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000630 return Invalid;
Chris Lattner199abbc2008-04-08 05:04:30 +0000631}
632
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000633/// \brief Merge the exception specifications of two variable declarations.
634///
635/// This is called when there's a redeclaration of a VarDecl. The function
636/// checks if the redeclaration might have an exception specification and
637/// validates compatibility and merges the specs if necessary.
638void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
639 // Shortcut if exceptions are disabled.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000640 if (!getLangOpts().CXXExceptions)
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000641 return;
642
643 assert(Context.hasSameType(New->getType(), Old->getType()) &&
644 "Should only be called if types are otherwise the same.");
645
646 QualType NewType = New->getType();
647 QualType OldType = Old->getType();
648
649 // We're only interested in pointers and references to functions, as well
650 // as pointers to member functions.
651 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
652 NewType = R->getPointeeType();
653 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
654 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
655 NewType = P->getPointeeType();
656 OldType = OldType->getAs<PointerType>()->getPointeeType();
657 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
658 NewType = M->getPointeeType();
659 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
660 }
661
662 if (!NewType->isFunctionProtoType())
663 return;
664
665 // There's lots of special cases for functions. For function pointers, system
666 // libraries are hopefully not as broken so that we don't need these
667 // workarounds.
668 if (CheckEquivalentExceptionSpec(
669 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
670 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
671 New->setInvalidDecl();
672 }
673}
674
Chris Lattner199abbc2008-04-08 05:04:30 +0000675/// CheckCXXDefaultArguments - Verify that the default arguments for a
676/// function declaration are well-formed according to C++
677/// [dcl.fct.default].
678void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
679 unsigned NumParams = FD->getNumParams();
680 unsigned p;
681
682 // Find first parameter with a default argument
683 for (p = 0; p < NumParams; ++p) {
684 ParmVarDecl *Param = FD->getParamDecl(p);
Richard Smith3cb4c632013-04-17 16:25:20 +0000685 if (Param->hasDefaultArg())
Chris Lattner199abbc2008-04-08 05:04:30 +0000686 break;
687 }
688
689 // C++ [dcl.fct.default]p4:
690 // In a given function declaration, all parameters
691 // subsequent to a parameter with a default argument shall
692 // have default arguments supplied in this or previous
693 // declarations. A default argument shall not be redefined
694 // by a later declaration (not even to the same value).
695 unsigned LastMissingDefaultArg = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000696 for (; p < NumParams; ++p) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000697 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000698 if (!Param->hasDefaultArg()) {
Douglas Gregor4d87df52008-12-16 21:30:33 +0000699 if (Param->isInvalidDecl())
700 /* We already complained about this parameter. */;
701 else if (Param->getIdentifier())
Mike Stump11289f42009-09-09 15:08:12 +0000702 Diag(Param->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000703 diag::err_param_default_argument_missing_name)
Chris Lattnerb91fd172008-11-19 07:32:16 +0000704 << Param->getIdentifier();
Chris Lattner199abbc2008-04-08 05:04:30 +0000705 else
Mike Stump11289f42009-09-09 15:08:12 +0000706 Diag(Param->getLocation(),
Chris Lattner199abbc2008-04-08 05:04:30 +0000707 diag::err_param_default_argument_missing);
Mike Stump11289f42009-09-09 15:08:12 +0000708
Chris Lattner199abbc2008-04-08 05:04:30 +0000709 LastMissingDefaultArg = p;
710 }
711 }
712
713 if (LastMissingDefaultArg > 0) {
714 // Some default arguments were missing. Clear out all of the
715 // default arguments up to (and including) the last missing
716 // default argument, so that we leave the function parameters
717 // in a semantically valid state.
718 for (p = 0; p <= LastMissingDefaultArg; ++p) {
719 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson84613c42009-06-12 16:51:40 +0000720 if (Param->hasDefaultArg()) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000721 Param->setDefaultArg(nullptr);
Chris Lattner199abbc2008-04-08 05:04:30 +0000722 }
723 }
724 }
725}
Douglas Gregor556877c2008-04-13 21:30:24 +0000726
Richard Smitheb3c10c2011-10-01 02:31:28 +0000727// CheckConstexprParameterTypes - Check whether a function's parameter types
728// are all literal types. If so, return true. If not, produce a suitable
Richard Smith3607ffe2012-02-13 03:54:03 +0000729// diagnostic and return false.
730static bool CheckConstexprParameterTypes(Sema &SemaRef,
731 const FunctionDecl *FD) {
Richard Smitheb3c10c2011-10-01 02:31:28 +0000732 unsigned ArgIndex = 0;
733 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +0000734 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
735 e = FT->param_type_end();
736 i != e; ++i, ++ArgIndex) {
Richard Smitheb3c10c2011-10-01 02:31:28 +0000737 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
738 SourceLocation ParamLoc = PD->getLocation();
739 if (!(*i)->isDependentType() &&
Richard Smith3607ffe2012-02-13 03:54:03 +0000740 SemaRef.RequireLiteralType(ParamLoc, *i,
Douglas Gregora6c5abb2012-05-04 16:48:41 +0000741 diag::err_constexpr_non_literal_param,
742 ArgIndex+1, PD->getSourceRange(),
743 isa<CXXConstructorDecl>(FD)))
Richard Smitheb3c10c2011-10-01 02:31:28 +0000744 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000745 }
Joao Matose9a3ed42012-08-31 22:18:20 +0000746 return true;
747}
748
749/// \brief Get diagnostic %select index for tag kind for
750/// record diagnostic message.
751/// WARNING: Indexes apply to particular diagnostics only!
752///
753/// \returns diagnostic %select index.
Joao Matosa5c42e92012-09-01 00:13:24 +0000754static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
Joao Matose9a3ed42012-08-31 22:18:20 +0000755 switch (Tag) {
Joao Matosa5c42e92012-09-01 00:13:24 +0000756 case TTK_Struct: return 0;
757 case TTK_Interface: return 1;
758 case TTK_Class: return 2;
759 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
Joao Matose9a3ed42012-08-31 22:18:20 +0000760 }
Joao Matose9a3ed42012-08-31 22:18:20 +0000761}
762
763// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
764// the requirements of a constexpr function definition or a constexpr
765// constructor definition. If so, return true. If not, produce appropriate
Richard Smith3607ffe2012-02-13 03:54:03 +0000766// diagnostics and return false.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000767//
Richard Smith3607ffe2012-02-13 03:54:03 +0000768// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
769bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
Richard Smith7971b692012-01-13 04:54:00 +0000770 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
771 if (MD && MD->isInstance()) {
Richard Smith3607ffe2012-02-13 03:54:03 +0000772 // C++11 [dcl.constexpr]p4:
773 // The definition of a constexpr constructor shall satisfy the following
774 // constraints:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000775 // - the class shall not have any virtual base classes;
Joao Matose9a3ed42012-08-31 22:18:20 +0000776 const CXXRecordDecl *RD = MD->getParent();
777 if (RD->getNumVBases()) {
778 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
779 << isa<CXXConstructorDecl>(NewFD)
780 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
Aaron Ballman445a9392014-03-13 16:15:17 +0000781 for (const auto &I : RD->vbases())
782 Diag(I.getLocStart(),
783 diag::note_constexpr_virtual_base_here) << I.getSourceRange();
Richard Smitheb3c10c2011-10-01 02:31:28 +0000784 return false;
785 }
Richard Smith7971b692012-01-13 04:54:00 +0000786 }
787
788 if (!isa<CXXConstructorDecl>(NewFD)) {
789 // C++11 [dcl.constexpr]p3:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000790 // The definition of a constexpr function shall satisfy the following
791 // constraints:
792 // - it shall not be virtual;
793 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
794 if (Method && Method->isVirtual()) {
Richard Smith3607ffe2012-02-13 03:54:03 +0000795 Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000796
Richard Smith3607ffe2012-02-13 03:54:03 +0000797 // If it's not obvious why this function is virtual, find an overridden
798 // function which uses the 'virtual' keyword.
799 const CXXMethodDecl *WrittenVirtual = Method;
800 while (!WrittenVirtual->isVirtualAsWritten())
801 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
802 if (WrittenVirtual != Method)
803 Diag(WrittenVirtual->getLocation(),
804 diag::note_overridden_virtual_function);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000805 return false;
806 }
807
808 // - its return type shall be a literal type;
Alp Toker314cc812014-01-25 16:55:45 +0000809 QualType RT = NewFD->getReturnType();
Richard Smitheb3c10c2011-10-01 02:31:28 +0000810 if (!RT->isDependentType() &&
Richard Smith3607ffe2012-02-13 03:54:03 +0000811 RequireLiteralType(NewFD->getLocation(), RT,
Douglas Gregora6c5abb2012-05-04 16:48:41 +0000812 diag::err_constexpr_non_literal_return))
Richard Smitheb3c10c2011-10-01 02:31:28 +0000813 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000814 }
815
Richard Smith7971b692012-01-13 04:54:00 +0000816 // - each of its parameter types shall be a literal type;
Richard Smith3607ffe2012-02-13 03:54:03 +0000817 if (!CheckConstexprParameterTypes(*this, NewFD))
Richard Smith7971b692012-01-13 04:54:00 +0000818 return false;
819
Richard Smitheb3c10c2011-10-01 02:31:28 +0000820 return true;
821}
822
823/// Check the given declaration statement is legal within a constexpr function
Richard Smithd9f663b2013-04-22 15:31:51 +0000824/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000825///
Richard Smithd9f663b2013-04-22 15:31:51 +0000826/// \return true if the body is OK (maybe only as an extension), false if we
827/// have diagnosed a problem.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000828static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
Richard Smithd9f663b2013-04-22 15:31:51 +0000829 DeclStmt *DS, SourceLocation &Cxx1yLoc) {
830 // C++11 [dcl.constexpr]p3 and p4:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000831 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
832 // contain only
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000833 for (const auto *DclIt : DS->decls()) {
834 switch (DclIt->getKind()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +0000835 case Decl::StaticAssert:
836 case Decl::Using:
837 case Decl::UsingShadow:
838 case Decl::UsingDirective:
839 case Decl::UnresolvedUsingTypename:
Richard Smithd9f663b2013-04-22 15:31:51 +0000840 case Decl::UnresolvedUsingValue:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000841 // - static_assert-declarations
842 // - using-declarations,
843 // - using-directives,
844 continue;
845
846 case Decl::Typedef:
847 case Decl::TypeAlias: {
848 // - typedef declarations and alias-declarations that do not define
849 // classes or enumerations,
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000850 const auto *TN = cast<TypedefNameDecl>(DclIt);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000851 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
852 // Don't allow variably-modified types in constexpr functions.
853 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
854 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
855 << TL.getSourceRange() << TL.getType()
856 << isa<CXXConstructorDecl>(Dcl);
857 return false;
858 }
859 continue;
860 }
861
862 case Decl::Enum:
863 case Decl::CXXRecord:
Richard Smithd9f663b2013-04-22 15:31:51 +0000864 // C++1y allows types to be defined, not just declared.
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000865 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition())
Richard Smithd9f663b2013-04-22 15:31:51 +0000866 SemaRef.Diag(DS->getLocStart(),
Aaron Ballmandd69ef32014-08-19 15:55:55 +0000867 SemaRef.getLangOpts().CPlusPlus14
Richard Smithd9f663b2013-04-22 15:31:51 +0000868 ? diag::warn_cxx11_compat_constexpr_type_definition
869 : diag::ext_constexpr_type_definition)
Richard Smitheb3c10c2011-10-01 02:31:28 +0000870 << isa<CXXConstructorDecl>(Dcl);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000871 continue;
872
Richard Smithd9f663b2013-04-22 15:31:51 +0000873 case Decl::EnumConstant:
874 case Decl::IndirectField:
875 case Decl::ParmVar:
876 // These can only appear with other declarations which are banned in
877 // C++11 and permitted in C++1y, so ignore them.
878 continue;
879
880 case Decl::Var: {
881 // C++1y [dcl.constexpr]p3 allows anything except:
882 // a definition of a variable of non-literal type or of static or
883 // thread storage duration or for which no initialization is performed.
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000884 const auto *VD = cast<VarDecl>(DclIt);
Richard Smithd9f663b2013-04-22 15:31:51 +0000885 if (VD->isThisDeclarationADefinition()) {
886 if (VD->isStaticLocal()) {
887 SemaRef.Diag(VD->getLocation(),
888 diag::err_constexpr_local_var_static)
889 << isa<CXXConstructorDecl>(Dcl)
890 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
891 return false;
892 }
Richard Smith3da88fa2013-04-26 14:36:30 +0000893 if (!VD->getType()->isDependentType() &&
894 SemaRef.RequireLiteralType(
Richard Smithd9f663b2013-04-22 15:31:51 +0000895 VD->getLocation(), VD->getType(),
896 diag::err_constexpr_local_var_non_literal_type,
897 isa<CXXConstructorDecl>(Dcl)))
898 return false;
Richard Smithab44d5b2013-12-10 08:25:00 +0000899 if (!VD->getType()->isDependentType() &&
900 !VD->hasInit() && !VD->isCXXForRangeDecl()) {
Richard Smithd9f663b2013-04-22 15:31:51 +0000901 SemaRef.Diag(VD->getLocation(),
902 diag::err_constexpr_local_var_no_init)
903 << isa<CXXConstructorDecl>(Dcl);
904 return false;
905 }
906 }
907 SemaRef.Diag(VD->getLocation(),
Aaron Ballmandd69ef32014-08-19 15:55:55 +0000908 SemaRef.getLangOpts().CPlusPlus14
Richard Smithd9f663b2013-04-22 15:31:51 +0000909 ? diag::warn_cxx11_compat_constexpr_local_var
910 : diag::ext_constexpr_local_var)
Richard Smitheb3c10c2011-10-01 02:31:28 +0000911 << isa<CXXConstructorDecl>(Dcl);
Richard Smithd9f663b2013-04-22 15:31:51 +0000912 continue;
913 }
914
915 case Decl::NamespaceAlias:
916 case Decl::Function:
917 // These are disallowed in C++11 and permitted in C++1y. Allow them
918 // everywhere as an extension.
919 if (!Cxx1yLoc.isValid())
920 Cxx1yLoc = DS->getLocStart();
921 continue;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000922
923 default:
924 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
925 << isa<CXXConstructorDecl>(Dcl);
926 return false;
927 }
928 }
929
930 return true;
931}
932
933/// Check that the given field is initialized within a constexpr constructor.
934///
935/// \param Dcl The constexpr constructor being checked.
936/// \param Field The field being checked. This may be a member of an anonymous
937/// struct or union nested within the class being checked.
938/// \param Inits All declarations, including anonymous struct/union members and
939/// indirect members, for which any initialization was provided.
940/// \param Diagnosed Set to true if an error is produced.
941static void CheckConstexprCtorInitializer(Sema &SemaRef,
942 const FunctionDecl *Dcl,
943 FieldDecl *Field,
944 llvm::SmallSet<Decl*, 16> &Inits,
945 bool &Diagnosed) {
Eli Friedmanb13e64e2013-06-28 21:07:41 +0000946 if (Field->isInvalidDecl())
947 return;
948
Douglas Gregor556e5862011-10-10 17:22:13 +0000949 if (Field->isUnnamedBitfield())
950 return;
Richard Smith4d59eeb2012-02-09 06:40:58 +0000951
Richard Smithab44d5b2013-12-10 08:25:00 +0000952 // Anonymous unions with no variant members and empty anonymous structs do not
953 // need to be explicitly initialized. FIXME: Anonymous structs that contain no
954 // indirect fields don't need initializing.
Richard Smith4d59eeb2012-02-09 06:40:58 +0000955 if (Field->isAnonymousStructOrUnion() &&
Richard Smithab44d5b2013-12-10 08:25:00 +0000956 (Field->getType()->isUnionType()
957 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
958 : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
Richard Smith4d59eeb2012-02-09 06:40:58 +0000959 return;
960
Richard Smitheb3c10c2011-10-01 02:31:28 +0000961 if (!Inits.count(Field)) {
962 if (!Diagnosed) {
963 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
964 Diagnosed = true;
965 }
966 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
967 } else if (Field->isAnonymousStructOrUnion()) {
968 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000969 for (auto *I : RD->fields())
Richard Smitheb3c10c2011-10-01 02:31:28 +0000970 // If an anonymous union contains an anonymous struct of which any member
971 // is initialized, all members must be initialized.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000972 if (!RD->isUnion() || Inits.count(I))
973 CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000974 }
975}
976
Richard Smithd9f663b2013-04-22 15:31:51 +0000977/// Check the provided statement is allowed in a constexpr function
978/// definition.
979static bool
980CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
Robert Wilhelmb869a8f2013-08-10 12:33:24 +0000981 SmallVectorImpl<SourceLocation> &ReturnStmts,
Richard Smithd9f663b2013-04-22 15:31:51 +0000982 SourceLocation &Cxx1yLoc) {
983 // - its function-body shall be [...] a compound-statement that contains only
984 switch (S->getStmtClass()) {
985 case Stmt::NullStmtClass:
986 // - null statements,
987 return true;
988
989 case Stmt::DeclStmtClass:
990 // - static_assert-declarations
991 // - using-declarations,
992 // - using-directives,
993 // - typedef declarations and alias-declarations that do not define
994 // classes or enumerations,
995 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
996 return false;
997 return true;
998
999 case Stmt::ReturnStmtClass:
1000 // - and exactly one return statement;
1001 if (isa<CXXConstructorDecl>(Dcl)) {
1002 // C++1y allows return statements in constexpr constructors.
1003 if (!Cxx1yLoc.isValid())
1004 Cxx1yLoc = S->getLocStart();
1005 return true;
1006 }
1007
1008 ReturnStmts.push_back(S->getLocStart());
1009 return true;
1010
1011 case Stmt::CompoundStmtClass: {
1012 // C++1y allows compound-statements.
1013 if (!Cxx1yLoc.isValid())
1014 Cxx1yLoc = S->getLocStart();
1015
1016 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001017 for (auto *BodyIt : CompStmt->body()) {
1018 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
Richard Smithd9f663b2013-04-22 15:31:51 +00001019 Cxx1yLoc))
1020 return false;
1021 }
1022 return true;
1023 }
1024
1025 case Stmt::AttributedStmtClass:
1026 if (!Cxx1yLoc.isValid())
1027 Cxx1yLoc = S->getLocStart();
1028 return true;
1029
1030 case Stmt::IfStmtClass: {
1031 // C++1y allows if-statements.
1032 if (!Cxx1yLoc.isValid())
1033 Cxx1yLoc = S->getLocStart();
1034
1035 IfStmt *If = cast<IfStmt>(S);
1036 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1037 Cxx1yLoc))
1038 return false;
1039 if (If->getElse() &&
1040 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1041 Cxx1yLoc))
1042 return false;
1043 return true;
1044 }
1045
1046 case Stmt::WhileStmtClass:
1047 case Stmt::DoStmtClass:
1048 case Stmt::ForStmtClass:
1049 case Stmt::CXXForRangeStmtClass:
1050 case Stmt::ContinueStmtClass:
1051 // C++1y allows all of these. We don't allow them as extensions in C++11,
1052 // because they don't make sense without variable mutation.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001053 if (!SemaRef.getLangOpts().CPlusPlus14)
Richard Smithd9f663b2013-04-22 15:31:51 +00001054 break;
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 case Stmt::SwitchStmtClass:
1065 case Stmt::CaseStmtClass:
1066 case Stmt::DefaultStmtClass:
1067 case Stmt::BreakStmtClass:
1068 // C++1y allows switch-statements, and since they don't need variable
1069 // mutation, we can reasonably allow them in C++11 as an extension.
1070 if (!Cxx1yLoc.isValid())
1071 Cxx1yLoc = S->getLocStart();
1072 for (Stmt::child_range Children = S->children(); Children; ++Children)
1073 if (*Children &&
1074 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1075 Cxx1yLoc))
1076 return false;
1077 return true;
1078
1079 default:
1080 if (!isa<Expr>(S))
1081 break;
1082
1083 // C++1y allows expression-statements.
1084 if (!Cxx1yLoc.isValid())
1085 Cxx1yLoc = S->getLocStart();
1086 return true;
1087 }
1088
1089 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1090 << isa<CXXConstructorDecl>(Dcl);
1091 return false;
1092}
1093
Richard Smitheb3c10c2011-10-01 02:31:28 +00001094/// Check the body for the given constexpr function declaration only contains
1095/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1096///
1097/// \return true if the body is OK, false if we have diagnosed a problem.
Richard Smith3607ffe2012-02-13 03:54:03 +00001098bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001099 if (isa<CXXTryStmt>(Body)) {
Richard Smith74388b42012-02-04 00:33:54 +00001100 // C++11 [dcl.constexpr]p3:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001101 // The definition of a constexpr function shall satisfy the following
1102 // constraints: [...]
1103 // - its function-body shall be = delete, = default, or a
1104 // compound-statement
1105 //
Richard Smith74388b42012-02-04 00:33:54 +00001106 // C++11 [dcl.constexpr]p4:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001107 // In the definition of a constexpr constructor, [...]
1108 // - its function-body shall not be a function-try-block;
1109 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1110 << isa<CXXConstructorDecl>(Dcl);
1111 return false;
1112 }
1113
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001114 SmallVector<SourceLocation, 4> ReturnStmts;
Richard Smithd9f663b2013-04-22 15:31:51 +00001115
1116 // - its function-body shall be [...] a compound-statement that contains only
1117 // [... list of cases ...]
1118 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1119 SourceLocation Cxx1yLoc;
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001120 for (auto *BodyIt : CompBody->body()) {
1121 if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc))
Richard Smithd9f663b2013-04-22 15:31:51 +00001122 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001123 }
1124
Richard Smithd9f663b2013-04-22 15:31:51 +00001125 if (Cxx1yLoc.isValid())
1126 Diag(Cxx1yLoc,
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001127 getLangOpts().CPlusPlus14
Richard Smithd9f663b2013-04-22 15:31:51 +00001128 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1129 : diag::ext_constexpr_body_invalid_stmt)
1130 << isa<CXXConstructorDecl>(Dcl);
1131
Richard Smitheb3c10c2011-10-01 02:31:28 +00001132 if (const CXXConstructorDecl *Constructor
1133 = dyn_cast<CXXConstructorDecl>(Dcl)) {
1134 const CXXRecordDecl *RD = Constructor->getParent();
Richard Smith4d59eeb2012-02-09 06:40:58 +00001135 // DR1359:
1136 // - every non-variant non-static data member and base class sub-object
1137 // shall be initialized;
Richard Smithab44d5b2013-12-10 08:25:00 +00001138 // DR1460:
1139 // - if the class is a union having variant members, exactly one of them
Richard Smith4d59eeb2012-02-09 06:40:58 +00001140 // shall be initialized;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001141 if (RD->isUnion()) {
Richard Smithab44d5b2013-12-10 08:25:00 +00001142 if (Constructor->getNumCtorInitializers() == 0 &&
1143 RD->hasVariantMembers()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001144 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1145 return false;
1146 }
Richard Smithf368fb42011-10-10 16:38:04 +00001147 } else if (!Constructor->isDependentContext() &&
1148 !Constructor->isDelegatingConstructor()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001149 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1150
1151 // Skip detailed checking if we have enough initializers, and we would
1152 // allow at most one initializer per member.
1153 bool AnyAnonStructUnionMembers = false;
1154 unsigned Fields = 0;
1155 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1156 E = RD->field_end(); I != E; ++I, ++Fields) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001157 if (I->isAnonymousStructOrUnion()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001158 AnyAnonStructUnionMembers = true;
1159 break;
1160 }
1161 }
Richard Smithab44d5b2013-12-10 08:25:00 +00001162 // DR1460:
1163 // - if the class is a union-like class, but is not a union, for each of
1164 // its anonymous union members having variant members, exactly one of
1165 // them shall be initialized;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001166 if (AnyAnonStructUnionMembers ||
1167 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1168 // Check initialization of non-static data members. Base classes are
1169 // always initialized so do not need to be checked. Dependent bases
1170 // might not have initializers in the member initializer list.
1171 llvm::SmallSet<Decl*, 16> Inits;
Aaron Ballman0ad78302014-03-13 17:34:31 +00001172 for (const auto *I: Constructor->inits()) {
1173 if (FieldDecl *FD = I->getMember())
Richard Smitheb3c10c2011-10-01 02:31:28 +00001174 Inits.insert(FD);
Aaron Ballman0ad78302014-03-13 17:34:31 +00001175 else if (IndirectFieldDecl *ID = I->getIndirectMember())
Richard Smitheb3c10c2011-10-01 02:31:28 +00001176 Inits.insert(ID->chain_begin(), ID->chain_end());
1177 }
1178
1179 bool Diagnosed = false;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001180 for (auto *I : RD->fields())
1181 CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001182 if (Diagnosed)
1183 return false;
1184 }
1185 }
Richard Smitheb3c10c2011-10-01 02:31:28 +00001186 } else {
1187 if (ReturnStmts.empty()) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001188 // C++1y doesn't require constexpr functions to contain a 'return'
Richard Smith06ffb452014-04-22 23:14:23 +00001189 // statement. We still do, unless the return type might be void, because
Richard Smithd9f663b2013-04-22 15:31:51 +00001190 // otherwise if there's no return statement, the function cannot
1191 // be used in a core constant expression.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001192 bool OK = getLangOpts().CPlusPlus14 &&
Richard Smith06ffb452014-04-22 23:14:23 +00001193 (Dcl->getReturnType()->isVoidType() ||
1194 Dcl->getReturnType()->isDependentType());
Richard Smithd9f663b2013-04-22 15:31:51 +00001195 Diag(Dcl->getLocation(),
Richard Smith3da88fa2013-04-26 14:36:30 +00001196 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
1197 : diag::err_constexpr_body_no_return);
1198 return OK;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001199 }
1200 if (ReturnStmts.size() > 1) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001201 Diag(ReturnStmts.back(),
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001202 getLangOpts().CPlusPlus14
Richard Smithd9f663b2013-04-22 15:31:51 +00001203 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
1204 : diag::ext_constexpr_body_multiple_return);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001205 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
1206 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001207 }
1208 }
1209
Richard Smith74388b42012-02-04 00:33:54 +00001210 // C++11 [dcl.constexpr]p5:
1211 // if no function argument values exist such that the function invocation
1212 // substitution would produce a constant expression, the program is
1213 // ill-formed; no diagnostic required.
1214 // C++11 [dcl.constexpr]p3:
1215 // - every constructor call and implicit conversion used in initializing the
1216 // return value shall be one of those allowed in a constant expression.
1217 // C++11 [dcl.constexpr]p4:
1218 // - every constructor involved in initializing non-static data members and
1219 // base class sub-objects shall be a constexpr constructor.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001220 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith3607ffe2012-02-13 03:54:03 +00001221 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smithf86b5dc2012-12-09 05:55:43 +00001222 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
Richard Smith253c2a32012-01-27 01:14:48 +00001223 << isa<CXXConstructorDecl>(Dcl);
1224 for (size_t I = 0, N = Diags.size(); I != N; ++I)
1225 Diag(Diags[I].first, Diags[I].second);
Richard Smithf86b5dc2012-12-09 05:55:43 +00001226 // Don't return false here: we allow this for compatibility in
1227 // system headers.
Richard Smith253c2a32012-01-27 01:14:48 +00001228 }
1229
Richard Smitheb3c10c2011-10-01 02:31:28 +00001230 return true;
1231}
1232
Douglas Gregor61956c42008-10-31 09:07:45 +00001233/// isCurrentClassName - Determine whether the identifier II is the
1234/// name of the class type currently being defined. In the case of
1235/// nested classes, this will only return true if II is the name of
1236/// the innermost class.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00001237bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1238 const CXXScopeSpec *SS) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001239 assert(getLangOpts().CPlusPlus && "No class names in C!");
Douglas Gregor411e5ac2010-01-11 23:29:10 +00001240
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00001241 CXXRecordDecl *CurDecl;
Douglas Gregor52537682009-03-19 00:18:19 +00001242 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregore5bbb7d2009-08-21 22:16:40 +00001243 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00001244 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1245 } else
1246 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1247
Douglas Gregor1aa3edb2010-02-05 06:12:42 +00001248 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregor61956c42008-10-31 09:07:45 +00001249 return &II == CurDecl->getIdentifier();
Benjamin Kramer8bf44352013-07-24 15:28:33 +00001250 return false;
Douglas Gregor61956c42008-10-31 09:07:45 +00001251}
1252
Richard Smithfb8b7b92013-10-15 00:00:26 +00001253/// \brief Determine whether the identifier II is a typo for the name of
1254/// the class type currently being defined. If so, update it to the identifier
1255/// that should have been used.
1256bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
1257 assert(getLangOpts().CPlusPlus && "No class names in C!");
1258
1259 if (!getLangOpts().SpellChecking)
1260 return false;
1261
1262 CXXRecordDecl *CurDecl;
1263 if (SS && SS->isSet() && !SS->isInvalid()) {
1264 DeclContext *DC = computeDeclContext(*SS, true);
1265 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1266 } else
1267 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1268
1269 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
1270 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
1271 < II->getLength()) {
1272 II = CurDecl->getIdentifier();
1273 return true;
1274 }
1275
1276 return false;
1277}
1278
Douglas Gregordc974572012-11-10 07:24:09 +00001279/// \brief Determine whether the given class is a base class of the given
1280/// class, including looking at dependent bases.
1281static bool findCircularInheritance(const CXXRecordDecl *Class,
1282 const CXXRecordDecl *Current) {
1283 SmallVector<const CXXRecordDecl*, 8> Queue;
1284
1285 Class = Class->getCanonicalDecl();
1286 while (true) {
Aaron Ballman574705e2014-03-13 15:41:46 +00001287 for (const auto &I : Current->bases()) {
1288 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
Douglas Gregordc974572012-11-10 07:24:09 +00001289 if (!Base)
1290 continue;
1291
1292 Base = Base->getDefinition();
1293 if (!Base)
1294 continue;
1295
1296 if (Base->getCanonicalDecl() == Class)
1297 return true;
1298
1299 Queue.push_back(Base);
1300 }
1301
1302 if (Queue.empty())
1303 return false;
1304
Robert Wilhelm25284cc2013-08-23 16:11:15 +00001305 Current = Queue.pop_back_val();
Douglas Gregordc974572012-11-10 07:24:09 +00001306 }
1307
1308 return false;
Douglas Gregor62004702012-11-10 01:18:17 +00001309}
1310
Hans Wennborg9bea9cc2014-06-25 18:25:57 +00001311/// \brief Perform propagation of DLL attributes from a derived class to a
1312/// templated base class for MS compatibility.
1313static void propagateDLLAttrToBaseClassTemplate(
1314 Sema &S, CXXRecordDecl *Class, Attr *ClassAttr,
1315 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
1316 if (getDLLAttr(
1317 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
1318 // If the base class template has a DLL attribute, don't try to change it.
1319 return;
1320 }
1321
1322 if (BaseTemplateSpec->getSpecializationKind() == TSK_Undeclared) {
1323 // If the base class is not already specialized, we can do the propagation.
1324 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(S.getASTContext()));
1325 NewAttr->setInherited(true);
1326 BaseTemplateSpec->addAttr(NewAttr);
1327 return;
1328 }
1329
1330 bool DifferentAttribute = false;
1331 if (Attr *SpecializationAttr = getDLLAttr(BaseTemplateSpec)) {
1332 if (!SpecializationAttr->isInherited()) {
1333 // The template has previously been specialized or instantiated with an
1334 // explicit attribute. We should not try to change it.
1335 return;
1336 }
1337 if (SpecializationAttr->getKind() == ClassAttr->getKind()) {
1338 // The specialization already has the right attribute.
1339 return;
1340 }
1341 DifferentAttribute = true;
1342 }
1343
1344 // The template was previously instantiated or explicitly specialized without
1345 // a dll attribute, or the template was previously instantiated with a
1346 // different inherited attribute. It's too late for us to change the
1347 // attribute, so warn that this is unsupported.
1348 S.Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
1349 << BaseTemplateSpec->isExplicitSpecialization() << DifferentAttribute;
1350 S.Diag(ClassAttr->getLocation(), diag::note_attribute);
1351 if (BaseTemplateSpec->isExplicitSpecialization()) {
1352 S.Diag(BaseTemplateSpec->getLocation(),
1353 diag::note_template_class_explicit_specialization_was_here)
1354 << BaseTemplateSpec;
1355 } else {
1356 S.Diag(BaseTemplateSpec->getPointOfInstantiation(),
1357 diag::note_template_class_instantiation_was_here)
1358 << BaseTemplateSpec;
1359 }
1360}
1361
Mike Stump11289f42009-09-09 15:08:12 +00001362/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor463421d2009-03-03 04:44:36 +00001363///
1364/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1365/// and returns NULL otherwise.
1366CXXBaseSpecifier *
1367Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1368 SourceRange SpecifierRange,
1369 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +00001370 TypeSourceInfo *TInfo,
1371 SourceLocation EllipsisLoc) {
Nick Lewycky19b9f952010-07-26 16:56:01 +00001372 QualType BaseType = TInfo->getType();
1373
Douglas Gregor463421d2009-03-03 04:44:36 +00001374 // C++ [class.union]p1:
1375 // A union shall not have base classes.
1376 if (Class->isUnion()) {
1377 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1378 << SpecifierRange;
Craig Topperc3ec1492014-05-26 06:22:03 +00001379 return nullptr;
Douglas Gregor463421d2009-03-03 04:44:36 +00001380 }
1381
Douglas Gregor752a5952011-01-03 22:36:02 +00001382 if (EllipsisLoc.isValid() &&
1383 !TInfo->getType()->containsUnexpandedParameterPack()) {
1384 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1385 << TInfo->getTypeLoc().getSourceRange();
1386 EllipsisLoc = SourceLocation();
1387 }
Douglas Gregor62004702012-11-10 01:18:17 +00001388
1389 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1390
1391 if (BaseType->isDependentType()) {
1392 // Make sure that we don't have circular inheritance among our dependent
1393 // bases. For non-dependent bases, the check for completeness below handles
1394 // this.
1395 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1396 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1397 ((BaseDecl = BaseDecl->getDefinition()) &&
Douglas Gregordc974572012-11-10 07:24:09 +00001398 findCircularInheritance(Class, BaseDecl))) {
Douglas Gregor62004702012-11-10 01:18:17 +00001399 Diag(BaseLoc, diag::err_circular_inheritance)
1400 << BaseType << Context.getTypeDeclType(Class);
1401
1402 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1403 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1404 << BaseType;
Craig Topperc3ec1492014-05-26 06:22:03 +00001405
1406 return nullptr;
Douglas Gregor62004702012-11-10 01:18:17 +00001407 }
1408 }
1409
Mike Stump11289f42009-09-09 15:08:12 +00001410 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +00001411 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +00001412 Access, TInfo, EllipsisLoc);
Douglas Gregor62004702012-11-10 01:18:17 +00001413 }
Douglas Gregor463421d2009-03-03 04:44:36 +00001414
1415 // Base specifiers must be record types.
1416 if (!BaseType->isRecordType()) {
1417 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
Craig Topperc3ec1492014-05-26 06:22:03 +00001418 return nullptr;
Douglas Gregor463421d2009-03-03 04:44:36 +00001419 }
1420
1421 // C++ [class.union]p1:
1422 // A union shall not be used as a base class.
1423 if (BaseType->isUnionType()) {
1424 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
Craig Topperc3ec1492014-05-26 06:22:03 +00001425 return nullptr;
Douglas Gregor463421d2009-03-03 04:44:36 +00001426 }
1427
Hans Wennborg9bea9cc2014-06-25 18:25:57 +00001428 // For the MS ABI, propagate DLL attributes to base class templates.
1429 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
1430 if (Attr *ClassAttr = getDLLAttr(Class)) {
1431 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
1432 BaseType->getAsCXXRecordDecl())) {
1433 propagateDLLAttrToBaseClassTemplate(*this, Class, ClassAttr,
1434 BaseTemplate, BaseLoc);
1435 }
1436 }
1437 }
1438
Douglas Gregor463421d2009-03-03 04:44:36 +00001439 // C++ [class.derived]p2:
1440 // The class-name in a base-specifier shall not be an incompletely
1441 // defined class.
Mike Stump11289f42009-09-09 15:08:12 +00001442 if (RequireCompleteType(BaseLoc, BaseType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001443 diag::err_incomplete_base_class, SpecifierRange)) {
John McCall3696dcb2010-08-17 07:23:57 +00001444 Class->setInvalidDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00001445 return nullptr;
John McCall3696dcb2010-08-17 07:23:57 +00001446 }
Douglas Gregor463421d2009-03-03 04:44:36 +00001447
Eli Friedmanc96d4962009-08-15 21:55:26 +00001448 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001449 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +00001450 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001451 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor463421d2009-03-03 04:44:36 +00001452 assert(BaseDecl && "Base type is not incomplete, but has no definition");
David Majnemer626032f2013-06-22 06:43:58 +00001453 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
Eli Friedmanc96d4962009-08-15 21:55:26 +00001454 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedman89c038e2009-12-05 23:03:49 +00001455
David Majnemer9b1754d2013-11-02 12:00:36 +00001456 // A class which contains a flexible array member is not suitable for use as a
1457 // base class:
1458 // - If the layout determines that a base comes before another base,
1459 // the flexible array member would index into the subsequent base.
1460 // - If the layout determines that base comes before the derived class,
1461 // the flexible array member would index into the derived class.
1462 if (CXXBaseDecl->hasFlexibleArrayMember()) {
1463 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
1464 << CXXBaseDecl->getDeclName();
Craig Topperc3ec1492014-05-26 06:22:03 +00001465 return nullptr;
David Majnemer9b1754d2013-11-02 12:00:36 +00001466 }
1467
Anders Carlsson65c76d32011-03-25 14:55:14 +00001468 // C++ [class]p3:
David Majnemer45897602013-11-02 11:24:41 +00001469 // If a class is marked final and it appears as a base-type-specifier in
Anders Carlsson65c76d32011-03-25 14:55:14 +00001470 // base-clause, the program is ill-formed.
David Majnemera5433082013-10-18 00:33:31 +00001471 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
David Majnemer45897602013-11-02 11:24:41 +00001472 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
David Majnemera5433082013-10-18 00:33:31 +00001473 << CXXBaseDecl->getDeclName()
1474 << FA->isSpelledAsSealed();
Alp Toker2afa8782014-05-28 12:20:14 +00001475 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
1476 << CXXBaseDecl->getDeclName() << FA->getRange();
Craig Topperc3ec1492014-05-26 06:22:03 +00001477 return nullptr;
Anders Carlssonfc1eef42011-01-22 17:51:53 +00001478 }
1479
John McCall3696dcb2010-08-17 07:23:57 +00001480 if (BaseDecl->isInvalidDecl())
1481 Class->setInvalidDecl();
David Majnemer45897602013-11-02 11:24:41 +00001482
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001483 // Create the base specifier.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001484 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +00001485 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +00001486 Access, TInfo, EllipsisLoc);
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001487}
1488
Douglas Gregor556877c2008-04-13 21:30:24 +00001489/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1490/// one entry in the base class list of a class specifier, for
Mike Stump11289f42009-09-09 15:08:12 +00001491/// example:
1492/// class foo : public bar, virtual private baz {
Douglas Gregor556877c2008-04-13 21:30:24 +00001493/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallfaf5fb42010-08-26 23:41:50 +00001494BaseResult
John McCall48871652010-08-21 09:40:31 +00001495Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Richard Smith4c96e992013-02-19 23:47:15 +00001496 ParsedAttributes &Attributes,
Douglas Gregor29a92472008-10-22 17:49:05 +00001497 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +00001498 ParsedType basetype, SourceLocation BaseLoc,
1499 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001500 if (!classdecl)
1501 return true;
1502
Douglas Gregorc40290e2009-03-09 23:48:35 +00001503 AdjustDeclIfTemplate(classdecl);
John McCall48871652010-08-21 09:40:31 +00001504 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregorbeab56e2010-02-27 00:25:28 +00001505 if (!Class)
1506 return true;
1507
David Majnemer5ef4fe72014-06-13 06:43:46 +00001508 // We haven't yet attached the base specifiers.
1509 Class->setIsParsingBaseSpecifiers();
1510
Richard Smith4c96e992013-02-19 23:47:15 +00001511 // We do not support any C++11 attributes on base-specifiers yet.
1512 // Diagnose any attributes we see.
1513 if (!Attributes.empty()) {
1514 for (AttributeList *Attr = Attributes.getList(); Attr;
1515 Attr = Attr->getNext()) {
1516 if (Attr->isInvalid() ||
1517 Attr->getKind() == AttributeList::IgnoredAttribute)
1518 continue;
1519 Diag(Attr->getLoc(),
1520 Attr->getKind() == AttributeList::UnknownAttribute
1521 ? diag::warn_unknown_attribute_ignored
1522 : diag::err_base_specifier_attribute)
1523 << Attr->getName();
1524 }
1525 }
1526
Craig Topperc3ec1492014-05-26 06:22:03 +00001527 TypeSourceInfo *TInfo = nullptr;
Nick Lewycky19b9f952010-07-26 16:56:01 +00001528 GetTypeFromParser(basetype, &TInfo);
Douglas Gregor506bd562010-12-13 22:49:22 +00001529
Douglas Gregor752a5952011-01-03 22:36:02 +00001530 if (EllipsisLoc.isInvalid() &&
1531 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregor506bd562010-12-13 22:49:22 +00001532 UPPC_BaseType))
1533 return true;
Douglas Gregor752a5952011-01-03 22:36:02 +00001534
Douglas Gregor463421d2009-03-03 04:44:36 +00001535 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregor752a5952011-01-03 22:36:02 +00001536 Virtual, Access, TInfo,
1537 EllipsisLoc))
Douglas Gregor463421d2009-03-03 04:44:36 +00001538 return BaseSpec;
Douglas Gregorb9b8b812012-07-02 21:00:41 +00001539 else
1540 Class->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001541
Douglas Gregor463421d2009-03-03 04:44:36 +00001542 return true;
Douglas Gregor29a92472008-10-22 17:49:05 +00001543}
Douglas Gregor556877c2008-04-13 21:30:24 +00001544
Nathan Sidwell44b21742015-01-19 01:44:02 +00001545/// Use small set to collect indirect bases. As this is only used
1546/// locally, there's no need to abstract the small size parameter.
1547typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
1548
1549/// \brief Recursively add the bases of Type. Don't add Type itself.
1550static void
1551NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
1552 const QualType &Type)
1553{
1554 // Even though the incoming type is a base, it might not be
1555 // a class -- it could be a template parm, for instance.
1556 if (auto Rec = Type->getAs<RecordType>()) {
1557 auto Decl = Rec->getAsCXXRecordDecl();
1558
1559 // Iterate over its bases.
1560 for (const auto &BaseSpec : Decl->bases()) {
1561 QualType Base = Context.getCanonicalType(BaseSpec.getType())
1562 .getUnqualifiedType();
1563 if (Set.insert(Base).second)
1564 // If we've not already seen it, recurse.
1565 NoteIndirectBases(Context, Set, Base);
1566 }
1567 }
1568}
1569
Douglas Gregor463421d2009-03-03 04:44:36 +00001570/// \brief Performs the actual work of attaching the given base class
1571/// specifiers to a C++ class.
1572bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1573 unsigned NumBases) {
1574 if (NumBases == 0)
1575 return false;
Douglas Gregor29a92472008-10-22 17:49:05 +00001576
1577 // Used to keep track of which base types we have already seen, so
1578 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001579 // that the key is always the unqualified canonical type of the base
1580 // class.
Douglas Gregor29a92472008-10-22 17:49:05 +00001581 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1582
Nathan Sidwell44b21742015-01-19 01:44:02 +00001583 // Used to track indirect bases so we can see if a direct base is
1584 // ambiguous.
1585 IndirectBaseSet IndirectBaseTypes;
1586
Douglas Gregor29a92472008-10-22 17:49:05 +00001587 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001588 unsigned NumGoodBases = 0;
Douglas Gregor463421d2009-03-03 04:44:36 +00001589 bool Invalid = false;
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001590 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump11289f42009-09-09 15:08:12 +00001591 QualType NewBaseType
Douglas Gregor463421d2009-03-03 04:44:36 +00001592 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001593 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Benjamin Kramer73ecd702012-03-05 17:20:04 +00001594
1595 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1596 if (KnownBase) {
Douglas Gregor29a92472008-10-22 17:49:05 +00001597 // C++ [class.mi]p3:
1598 // A class shall not be specified as a direct base class of a
1599 // derived class more than once.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001600 Diag(Bases[idx]->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001601 diag::err_duplicate_base_class)
Benjamin Kramer73ecd702012-03-05 17:20:04 +00001602 << KnownBase->getType()
Douglas Gregor463421d2009-03-03 04:44:36 +00001603 << Bases[idx]->getSourceRange();
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001604
1605 // Delete the duplicate base class specifier; we're going to
1606 // overwrite its pointer later.
Douglas Gregorb77af8f2009-07-22 20:55:49 +00001607 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +00001608
1609 Invalid = true;
Douglas Gregor29a92472008-10-22 17:49:05 +00001610 } else {
1611 // Okay, add this new base class.
Benjamin Kramer73ecd702012-03-05 17:20:04 +00001612 KnownBase = Bases[idx];
Douglas Gregor463421d2009-03-03 04:44:36 +00001613 Bases[NumGoodBases++] = Bases[idx];
Nathan Sidwell44b21742015-01-19 01:44:02 +00001614
1615 // Note this base's direct & indirect bases, if there could be ambiguity.
1616 if (NumBases > 1)
1617 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
1618
John McCalldb632ac2012-09-25 07:32:39 +00001619 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1620 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1621 if (Class->isInterface() &&
1622 (!RD->isInterface() ||
1623 KnownBase->getAccessSpecifier() != AS_public)) {
1624 // The Microsoft extension __interface does not permit bases that
1625 // are not themselves public interfaces.
1626 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1627 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1628 << RD->getSourceRange();
1629 Invalid = true;
1630 }
1631 if (RD->hasAttr<WeakAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +00001632 Class->addAttr(WeakAttr::CreateImplicit(Context));
John McCalldb632ac2012-09-25 07:32:39 +00001633 }
Douglas Gregor29a92472008-10-22 17:49:05 +00001634 }
1635 }
1636
1637 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor4a62bdf2010-02-11 01:30:34 +00001638 Class->setBases(Bases, NumGoodBases);
Nathan Sidwell44b21742015-01-19 01:44:02 +00001639
1640 for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
1641 // Check whether this direct base is inaccessible due to ambiguity.
1642 QualType BaseType = Bases[idx]->getType();
1643 CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
1644 .getUnqualifiedType();
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001645
Nathan Sidwell44b21742015-01-19 01:44:02 +00001646 if (IndirectBaseTypes.count(CanonicalBase)) {
1647 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1648 /*DetectVirtual=*/true);
1649 bool found
1650 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
1651 assert(found);
NAKAMURA Takumi6a1565c2015-01-19 09:49:59 +00001652 (void)found;
Nathan Sidwell44b21742015-01-19 01:44:02 +00001653
1654 if (Paths.isAmbiguous(CanonicalBase))
1655 Diag(Bases[idx]->getLocStart (), diag::warn_inaccessible_base_class)
1656 << BaseType << getAmbiguousPathsDisplayString(Paths)
1657 << Bases[idx]->getSourceRange();
1658 else
1659 assert(Bases[idx]->isVirtual());
1660 }
1661
1662 // Delete the base class specifier, since its data has been copied
1663 // into the CXXRecordDecl.
Douglas Gregorb77af8f2009-07-22 20:55:49 +00001664 Context.Deallocate(Bases[idx]);
Nathan Sidwell44b21742015-01-19 01:44:02 +00001665 }
Douglas Gregor463421d2009-03-03 04:44:36 +00001666
1667 return Invalid;
1668}
1669
1670/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1671/// class, after checking whether there are any duplicate base
1672/// classes.
Richard Trieu9becef62011-09-09 03:18:59 +00001673void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor463421d2009-03-03 04:44:36 +00001674 unsigned NumBases) {
1675 if (!ClassDecl || !Bases || !NumBases)
1676 return;
1677
1678 AdjustDeclIfTemplate(ClassDecl);
Robert Wilhelme3cea802013-07-22 05:04:01 +00001679 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases, NumBases);
Douglas Gregor556877c2008-04-13 21:30:24 +00001680}
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00001681
Douglas Gregor36d1b142009-10-06 17:59:45 +00001682/// \brief Determine whether the type \p Derived is a C++ class that is
1683/// derived from the type \p Base.
1684bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001685 if (!getLangOpts().CPlusPlus)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001686 return false;
John McCalle78aac42010-03-10 03:28:59 +00001687
Douglas Gregor45bb4832013-03-26 23:36:30 +00001688 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001689 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001690 return false;
1691
Douglas Gregor45bb4832013-03-26 23:36:30 +00001692 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001693 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001694 return false;
Douglas Gregor45bb4832013-03-26 23:36:30 +00001695
1696 // If either the base or the derived type is invalid, don't try to
1697 // check whether one is derived from the other.
1698 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
1699 return false;
1700
John McCall67da35c2010-02-04 22:26:26 +00001701 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1702 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregor36d1b142009-10-06 17:59:45 +00001703}
1704
1705/// \brief Determine whether the type \p Derived is a C++ class that is
1706/// derived from the type \p Base.
1707bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001708 if (!getLangOpts().CPlusPlus)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001709 return false;
1710
Douglas Gregor45bb4832013-03-26 23:36:30 +00001711 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001712 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001713 return false;
1714
Douglas Gregor45bb4832013-03-26 23:36:30 +00001715 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001716 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001717 return false;
1718
Douglas Gregor36d1b142009-10-06 17:59:45 +00001719 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1720}
1721
Anders Carlssona70cff62010-04-24 19:06:50 +00001722void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallcf142162010-08-07 06:22:56 +00001723 CXXCastPath &BasePathArray) {
Anders Carlssona70cff62010-04-24 19:06:50 +00001724 assert(BasePathArray.empty() && "Base path array must be empty!");
1725 assert(Paths.isRecordingPaths() && "Must record paths!");
1726
1727 const CXXBasePath &Path = Paths.front();
1728
1729 // We first go backward and check if we have a virtual base.
1730 // FIXME: It would be better if CXXBasePath had the base specifier for
1731 // the nearest virtual base.
1732 unsigned Start = 0;
1733 for (unsigned I = Path.size(); I != 0; --I) {
1734 if (Path[I - 1].Base->isVirtual()) {
1735 Start = I - 1;
1736 break;
1737 }
1738 }
1739
1740 // Now add all bases.
1741 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallcf142162010-08-07 06:22:56 +00001742 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlssona70cff62010-04-24 19:06:50 +00001743}
1744
Douglas Gregor36d1b142009-10-06 17:59:45 +00001745/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1746/// conversion (where Derived and Base are class types) is
1747/// well-formed, meaning that the conversion is unambiguous (and
1748/// that all of the base classes are accessible). Returns true
1749/// and emits a diagnostic if the code is ill-formed, returns false
1750/// otherwise. Loc is the location where this routine should point to
1751/// if there is an error, and Range is the source range to highlight
1752/// if there is an error.
1753bool
1754Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall1064d7e2010-03-16 05:22:47 +00001755 unsigned InaccessibleBaseID,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001756 unsigned AmbigiousBaseConvID,
1757 SourceLocation Loc, SourceRange Range,
Anders Carlsson7afe4242010-04-24 17:11:09 +00001758 DeclarationName Name,
John McCallcf142162010-08-07 06:22:56 +00001759 CXXCastPath *BasePath) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001760 // First, determine whether the path from Derived to Base is
1761 // ambiguous. This is slightly more expensive than checking whether
1762 // the Derived to Base conversion exists, because here we need to
1763 // explore multiple paths to determine if there is an ambiguity.
1764 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1765 /*DetectVirtual=*/false);
1766 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1767 assert(DerivationOkay &&
1768 "Can only be used with a derived-to-base conversion");
1769 (void)DerivationOkay;
1770
1771 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlssona70cff62010-04-24 19:06:50 +00001772 if (InaccessibleBaseID) {
1773 // Check that the base class can be accessed.
1774 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1775 InaccessibleBaseID)) {
1776 case AR_inaccessible:
1777 return true;
1778 case AR_accessible:
1779 case AR_dependent:
1780 case AR_delayed:
1781 break;
Anders Carlsson7afe4242010-04-24 17:11:09 +00001782 }
John McCall5b0829a2010-02-10 09:31:12 +00001783 }
Anders Carlssona70cff62010-04-24 19:06:50 +00001784
1785 // Build a base path if necessary.
1786 if (BasePath)
1787 BuildBasePathArray(Paths, *BasePath);
1788 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +00001789 }
1790
David Majnemer626032f2013-06-22 06:43:58 +00001791 if (AmbigiousBaseConvID) {
1792 // We know that the derived-to-base conversion is ambiguous, and
1793 // we're going to produce a diagnostic. Perform the derived-to-base
1794 // search just one more time to compute all of the possible paths so
1795 // that we can print them out. This is more expensive than any of
1796 // the previous derived-to-base checks we've done, but at this point
1797 // performance isn't as much of an issue.
1798 Paths.clear();
1799 Paths.setRecordingPaths(true);
1800 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1801 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1802 (void)StillOkay;
1803
1804 // Build up a textual representation of the ambiguous paths, e.g.,
1805 // D -> B -> A, that will be used to illustrate the ambiguous
1806 // conversions in the diagnostic. We only print one of the paths
1807 // to each base class subobject.
1808 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1809
1810 Diag(Loc, AmbigiousBaseConvID)
1811 << Derived << Base << PathDisplayStr << Range << Name;
1812 }
Douglas Gregor36d1b142009-10-06 17:59:45 +00001813 return true;
1814}
1815
1816bool
1817Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redl7c353682009-11-14 21:15:49 +00001818 SourceLocation Loc, SourceRange Range,
John McCallcf142162010-08-07 06:22:56 +00001819 CXXCastPath *BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001820 bool IgnoreAccess) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001821 return CheckDerivedToBaseConversion(Derived, Base,
John McCall1064d7e2010-03-16 05:22:47 +00001822 IgnoreAccess ? 0
1823 : diag::err_upcast_to_inaccessible_base,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001824 diag::err_ambiguous_derived_to_base_conv,
Anders Carlsson7afe4242010-04-24 17:11:09 +00001825 Loc, Range, DeclarationName(),
1826 BasePath);
Douglas Gregor36d1b142009-10-06 17:59:45 +00001827}
1828
1829
1830/// @brief Builds a string representing ambiguous paths from a
1831/// specific derived class to different subobjects of the same base
1832/// class.
1833///
1834/// This function builds a string that can be used in error messages
1835/// to show the different paths that one can take through the
1836/// inheritance hierarchy to go from the derived class to different
1837/// subobjects of a base class. The result looks something like this:
1838/// @code
1839/// struct D -> struct B -> struct A
1840/// struct D -> struct C -> struct A
1841/// @endcode
1842std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1843 std::string PathDisplayStr;
1844 std::set<unsigned> DisplayedPaths;
1845 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1846 Path != Paths.end(); ++Path) {
1847 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1848 // We haven't displayed a path to this particular base
1849 // class subobject yet.
1850 PathDisplayStr += "\n ";
1851 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1852 for (CXXBasePath::const_iterator Element = Path->begin();
1853 Element != Path->end(); ++Element)
1854 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1855 }
1856 }
1857
1858 return PathDisplayStr;
1859}
1860
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001861//===----------------------------------------------------------------------===//
1862// C++ class member Handling
1863//===----------------------------------------------------------------------===//
1864
Abramo Bagnarad7340582010-06-05 05:09:32 +00001865/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00001866bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1867 SourceLocation ASLoc,
1868 SourceLocation ColonLoc,
1869 AttributeList *Attrs) {
Abramo Bagnarad7340582010-06-05 05:09:32 +00001870 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCall48871652010-08-21 09:40:31 +00001871 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnarad7340582010-06-05 05:09:32 +00001872 ASLoc, ColonLoc);
1873 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00001874 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnarad7340582010-06-05 05:09:32 +00001875}
1876
Richard Smith18f07db2012-08-06 03:25:17 +00001877/// CheckOverrideControl - Check C++11 override control semantics.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001878void Sema::CheckOverrideControl(NamedDecl *D) {
Richard Smith09b031f2012-09-06 18:32:18 +00001879 if (D->isInvalidDecl())
1880 return;
1881
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001882 // We only care about "override" and "final" declarations.
1883 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
1884 return;
Anders Carlssonfd835532011-01-20 05:57:14 +00001885
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001886 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlssonfa8e5d32011-01-20 06:33:26 +00001887
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001888 // We can't check dependent instance methods.
1889 if (MD && MD->isInstance() &&
1890 (MD->getParent()->hasAnyDependentBases() ||
1891 MD->getType()->isDependentType()))
1892 return;
1893
1894 if (MD && !MD->isVirtual()) {
1895 // If we have a non-virtual method, check if if hides a virtual method.
1896 // (In that case, it's most likely the method has the wrong type.)
1897 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
1898 FindHiddenVirtualMethods(MD, OverloadedMethods);
1899
1900 if (!OverloadedMethods.empty()) {
Richard Smith18f07db2012-08-06 03:25:17 +00001901 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1902 Diag(OA->getLocation(),
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001903 diag::override_keyword_hides_virtual_member_function)
1904 << "override" << (OverloadedMethods.size() > 1);
1905 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
Richard Smith18f07db2012-08-06 03:25:17 +00001906 Diag(FA->getLocation(),
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001907 diag::override_keyword_hides_virtual_member_function)
David Majnemera5433082013-10-18 00:33:31 +00001908 << (FA->isSpelledAsSealed() ? "sealed" : "final")
1909 << (OverloadedMethods.size() > 1);
Richard Smith18f07db2012-08-06 03:25:17 +00001910 }
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001911 NoteHiddenVirtualMethods(MD, OverloadedMethods);
1912 MD->setInvalidDecl();
1913 return;
1914 }
1915 // Fall through into the general case diagnostic.
1916 // FIXME: We might want to attempt typo correction here.
1917 }
1918
1919 if (!MD || !MD->isVirtual()) {
1920 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1921 Diag(OA->getLocation(),
1922 diag::override_keyword_only_allowed_on_virtual_member_functions)
1923 << "override" << FixItHint::CreateRemoval(OA->getLocation());
1924 D->dropAttr<OverrideAttr>();
1925 }
1926 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1927 Diag(FA->getLocation(),
1928 diag::override_keyword_only_allowed_on_virtual_member_functions)
David Majnemera5433082013-10-18 00:33:31 +00001929 << (FA->isSpelledAsSealed() ? "sealed" : "final")
1930 << FixItHint::CreateRemoval(FA->getLocation());
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001931 D->dropAttr<FinalAttr>();
Richard Smith18f07db2012-08-06 03:25:17 +00001932 }
Anders Carlssonfd835532011-01-20 05:57:14 +00001933 return;
1934 }
Richard Smith18f07db2012-08-06 03:25:17 +00001935
Richard Smith18f07db2012-08-06 03:25:17 +00001936 // C++11 [class.virtual]p5:
David Blaikie1cbb9712014-11-14 19:09:44 +00001937 // If a function is marked with the virt-specifier override and
Richard Smith18f07db2012-08-06 03:25:17 +00001938 // does not override a member function of a base class, the program is
1939 // ill-formed.
1940 bool HasOverriddenMethods =
1941 MD->begin_overridden_methods() != MD->end_overridden_methods();
1942 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1943 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1944 << MD->getDeclName();
Anders Carlssonfd835532011-01-20 05:57:14 +00001945}
1946
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00001947void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) {
1948 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
1949 return;
1950 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
1951 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>() ||
1952 isa<CXXDestructorDecl>(MD))
1953 return;
1954
Fariborz Jahaniane3db7782014-11-03 19:46:18 +00001955 SourceLocation Loc = MD->getLocation();
1956 SourceLocation SpellingLoc = Loc;
1957 if (getSourceManager().isMacroArgExpansion(Loc))
1958 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).first;
1959 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
1960 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
Fariborz Jahanian6e213382014-10-31 19:56:27 +00001961 return;
Fariborz Jahaniane3db7782014-11-03 19:46:18 +00001962
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00001963 if (MD->size_overridden_methods() > 0) {
1964 Diag(MD->getLocation(), diag::warn_function_marked_not_override_overriding)
1965 << MD->getDeclName();
1966 const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
1967 Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
1968 }
1969}
1970
Richard Smith18f07db2012-08-06 03:25:17 +00001971/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
Anders Carlsson3f610c72011-01-20 16:25:36 +00001972/// function overrides a virtual member function marked 'final', according to
Richard Smith18f07db2012-08-06 03:25:17 +00001973/// C++11 [class.virtual]p4.
Anders Carlsson3f610c72011-01-20 16:25:36 +00001974bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1975 const CXXMethodDecl *Old) {
David Majnemera5433082013-10-18 00:33:31 +00001976 FinalAttr *FA = Old->getAttr<FinalAttr>();
1977 if (!FA)
Anders Carlsson19588aa2011-01-23 21:07:30 +00001978 return false;
1979
1980 Diag(New->getLocation(), diag::err_final_function_overridden)
David Majnemera5433082013-10-18 00:33:31 +00001981 << New->getDeclName()
1982 << FA->isSpelledAsSealed();
Anders Carlsson19588aa2011-01-23 21:07:30 +00001983 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1984 return true;
Anders Carlsson3f610c72011-01-20 16:25:36 +00001985}
1986
Daniel Jasper0baec5492012-06-06 08:32:04 +00001987static bool InitializationHasSideEffects(const FieldDecl &FD) {
Richard Smith0a8cfc72012-08-07 21:30:42 +00001988 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1989 // FIXME: Destruction of ObjC lifetime types has side-effects.
1990 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1991 return !RD->isCompleteDefinition() ||
1992 !RD->hasTrivialDefaultConstructor() ||
1993 !RD->hasTrivialDestructor();
Daniel Jasper0baec5492012-06-06 08:32:04 +00001994 return false;
1995}
1996
John McCall5e77d762013-04-16 07:28:30 +00001997static AttributeList *getMSPropertyAttr(AttributeList *list) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001998 for (AttributeList *it = list; it != nullptr; it = it->getNext())
John McCall5e77d762013-04-16 07:28:30 +00001999 if (it->isDeclspecPropertyAttribute())
2000 return it;
Craig Topperc3ec1492014-05-26 06:22:03 +00002001 return nullptr;
John McCall5e77d762013-04-16 07:28:30 +00002002}
2003
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002004/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
2005/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith938f40b2011-06-11 17:19:42 +00002006/// bitfield width if there is one, 'InitExpr' specifies the initializer if
Richard Smith2b013182012-06-10 03:12:00 +00002007/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
2008/// present (but parsing it has been deferred).
Rafael Espindola0a67e2f2013-01-08 20:44:06 +00002009NamedDecl *
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002010Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +00002011 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieu2bd04012011-09-09 02:00:50 +00002012 Expr *BW, const VirtSpecifiers &VS,
Richard Smith2b013182012-06-10 03:12:00 +00002013 InClassInitStyle InitStyle) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002014 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002015 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
2016 DeclarationName Name = NameInfo.getName();
2017 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor23ab7452010-11-09 03:31:16 +00002018
2019 // For anonymous bitfields, the location should point to the type.
2020 if (Loc.isInvalid())
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002021 Loc = D.getLocStart();
Douglas Gregor23ab7452010-11-09 03:31:16 +00002022
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002023 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002024
John McCallb1cd7da2010-06-04 08:34:12 +00002025 assert(isa<CXXRecordDecl>(CurContext));
John McCall07e91c02009-08-06 02:15:43 +00002026 assert(!DS.isFriendSpecified());
2027
Richard Smithcfcdf3a2011-06-25 02:28:38 +00002028 bool isFunc = D.isDeclarationOfFunction();
John McCallb1cd7da2010-06-04 08:34:12 +00002029
John McCalldb632ac2012-09-25 07:32:39 +00002030 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
2031 // The Microsoft extension __interface only permits public member functions
2032 // and prohibits constructors, destructors, operators, non-public member
2033 // functions, static methods and data members.
2034 unsigned InvalidDecl;
2035 bool ShowDeclName = true;
2036 if (!isFunc)
2037 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
2038 else if (AS != AS_public)
2039 InvalidDecl = 2;
2040 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
2041 InvalidDecl = 3;
2042 else switch (Name.getNameKind()) {
2043 case DeclarationName::CXXConstructorName:
2044 InvalidDecl = 4;
2045 ShowDeclName = false;
2046 break;
2047
2048 case DeclarationName::CXXDestructorName:
2049 InvalidDecl = 5;
2050 ShowDeclName = false;
2051 break;
2052
2053 case DeclarationName::CXXOperatorName:
2054 case DeclarationName::CXXConversionFunctionName:
2055 InvalidDecl = 6;
2056 break;
2057
2058 default:
2059 InvalidDecl = 0;
2060 break;
2061 }
2062
2063 if (InvalidDecl) {
2064 if (ShowDeclName)
2065 Diag(Loc, diag::err_invalid_member_in_interface)
2066 << (InvalidDecl-1) << Name;
2067 else
2068 Diag(Loc, diag::err_invalid_member_in_interface)
2069 << (InvalidDecl-1) << "";
Craig Topperc3ec1492014-05-26 06:22:03 +00002070 return nullptr;
John McCalldb632ac2012-09-25 07:32:39 +00002071 }
2072 }
2073
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002074 // C++ 9.2p6: A member shall not be declared to have automatic storage
2075 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redlccdfaba2008-11-14 23:42:31 +00002076 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
2077 // data members and cannot be applied to names declared const or static,
2078 // and cannot be applied to reference members.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002079 switch (DS.getStorageClassSpec()) {
Richard Smithb4a9e862013-04-12 22:46:28 +00002080 case DeclSpec::SCS_unspecified:
2081 case DeclSpec::SCS_typedef:
2082 case DeclSpec::SCS_static:
2083 break;
2084 case DeclSpec::SCS_mutable:
2085 if (isFunc) {
2086 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +00002087
Richard Smithb4a9e862013-04-12 22:46:28 +00002088 // FIXME: It would be nicer if the keyword was ignored only for this
2089 // declarator. Otherwise we could get follow-up errors.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002090 D.getMutableDeclSpec().ClearStorageClassSpecs();
Richard Smithb4a9e862013-04-12 22:46:28 +00002091 }
2092 break;
2093 default:
2094 Diag(DS.getStorageClassSpecLoc(),
2095 diag::err_storageclass_invalid_for_member);
2096 D.getMutableDeclSpec().ClearStorageClassSpecs();
2097 break;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002098 }
2099
Sebastian Redlccdfaba2008-11-14 23:42:31 +00002100 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
2101 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +00002102 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002103
David Blaikie35506f82013-01-30 01:22:18 +00002104 if (DS.isConstexprSpecified() && isInstField) {
2105 SemaDiagnosticBuilder B =
2106 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
2107 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
2108 if (InitStyle == ICIS_NoInit) {
Richard Smith82dce552014-04-14 21:00:40 +00002109 B << 0 << 0;
2110 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
2111 B << FixItHint::CreateRemoval(ConstexprLoc);
2112 else {
2113 B << FixItHint::CreateReplacement(ConstexprLoc, "const");
2114 D.getMutableDeclSpec().ClearConstexprSpec();
2115 const char *PrevSpec;
2116 unsigned DiagID;
2117 bool Failed = D.getMutableDeclSpec().SetTypeQual(
2118 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
2119 (void)Failed;
2120 assert(!Failed && "Making a constexpr member const shouldn't fail");
2121 }
David Blaikie35506f82013-01-30 01:22:18 +00002122 } else {
2123 B << 1;
2124 const char *PrevSpec;
2125 unsigned DiagID;
David Blaikie35506f82013-01-30 01:22:18 +00002126 if (D.getMutableDeclSpec().SetStorageClassSpec(
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002127 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
2128 Context.getPrintingPolicy())) {
Matt Beaumont-Gayefc270d2013-01-31 00:08:03 +00002129 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
David Blaikie35506f82013-01-30 01:22:18 +00002130 "This is the only DeclSpec that should fail to be applied");
2131 B << 1;
2132 } else {
2133 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
2134 isInstField = false;
2135 }
2136 }
2137 }
2138
Rafael Espindola0a67e2f2013-01-08 20:44:06 +00002139 NamedDecl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +00002140 if (isInstField) {
Douglas Gregora007d362010-10-13 22:19:53 +00002141 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorbb64afc2011-10-09 18:55:59 +00002142
2143 // Data members must have identifiers for names.
Benjamin Kramer365082d2012-05-19 16:34:46 +00002144 if (!Name.isIdentifier()) {
Douglas Gregorbb64afc2011-10-09 18:55:59 +00002145 Diag(Loc, diag::err_bad_variable_name)
2146 << Name;
Craig Topperc3ec1492014-05-26 06:22:03 +00002147 return nullptr;
Douglas Gregorbb64afc2011-10-09 18:55:59 +00002148 }
Douglas Gregor7c26c042011-09-21 14:40:46 +00002149
Benjamin Kramer365082d2012-05-19 16:34:46 +00002150 IdentifierInfo *II = Name.getAsIdentifierInfo();
2151
Douglas Gregor7c26c042011-09-21 14:40:46 +00002152 // Member field could not be with "template" keyword.
2153 // So TemplateParameterLists should be empty in this case.
2154 if (TemplateParameterLists.size()) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002155 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
Douglas Gregor7c26c042011-09-21 14:40:46 +00002156 if (TemplateParams->size()) {
2157 // There is no such thing as a member field template.
2158 Diag(D.getIdentifierLoc(), diag::err_template_member)
2159 << II
2160 << SourceRange(TemplateParams->getTemplateLoc(),
2161 TemplateParams->getRAngleLoc());
2162 } else {
2163 // There is an extraneous 'template<>' for this member.
2164 Diag(TemplateParams->getTemplateLoc(),
2165 diag::err_template_member_noparams)
2166 << II
2167 << SourceRange(TemplateParams->getTemplateLoc(),
2168 TemplateParams->getRAngleLoc());
2169 }
Craig Topperc3ec1492014-05-26 06:22:03 +00002170 return nullptr;
Douglas Gregor7c26c042011-09-21 14:40:46 +00002171 }
2172
Douglas Gregora007d362010-10-13 22:19:53 +00002173 if (SS.isSet() && !SS.isInvalid()) {
2174 // The user provided a superfluous scope specifier inside a class
2175 // definition:
2176 //
2177 // class X {
2178 // int X::member;
2179 // };
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00002180 if (DeclContext *DC = computeDeclContext(SS, false))
2181 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
Douglas Gregora007d362010-10-13 22:19:53 +00002182 else
2183 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
2184 << Name << SS.getRange();
Douglas Gregorc3ae7c32011-11-01 22:13:30 +00002185
Douglas Gregora007d362010-10-13 22:19:53 +00002186 SS.clear();
2187 }
Douglas Gregor7c26c042011-09-21 14:40:46 +00002188
John McCall5e77d762013-04-16 07:28:30 +00002189 AttributeList *MSPropertyAttr =
2190 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002191 if (MSPropertyAttr) {
2192 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2193 BitWidth, InitStyle, AS, MSPropertyAttr);
2194 if (!Member)
Craig Topperc3ec1492014-05-26 06:22:03 +00002195 return nullptr;
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002196 isInstField = false;
2197 } else {
2198 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2199 BitWidth, InitStyle, AS);
2200 assert(Member && "HandleField never returns null");
2201 }
2202 } else {
Nico Webera089c7c2015-01-16 21:09:43 +00002203 assert(InitStyle == ICIS_NoInit ||
2204 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static);
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002205
2206 Member = HandleDeclarator(S, D, TemplateParameterLists);
2207 if (!Member)
Craig Topperc3ec1492014-05-26 06:22:03 +00002208 return nullptr;
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002209
2210 // Non-instance-fields can't have a bitfield.
2211 if (BitWidth) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00002212 if (Member->isInvalidDecl()) {
2213 // don't emit another diagnostic.
David Majnemer380443a2014-12-28 22:51:45 +00002214 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00002215 // C++ 9.6p3: A bit-field shall not be a static member.
2216 // "static member 'A' cannot be a bit-field"
2217 Diag(Loc, diag::err_static_not_bitfield)
2218 << Name << BitWidth->getSourceRange();
2219 } else if (isa<TypedefDecl>(Member)) {
2220 // "typedef member 'x' cannot be a bit-field"
2221 Diag(Loc, diag::err_typedef_not_bitfield)
2222 << Name << BitWidth->getSourceRange();
2223 } else {
2224 // A function typedef ("typedef int f(); f a;").
2225 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
2226 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +00002227 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +00002228 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +00002229 }
Mike Stump11289f42009-09-09 15:08:12 +00002230
Craig Topperc3ec1492014-05-26 06:22:03 +00002231 BitWidth = nullptr;
Chris Lattnerd26760a2009-03-05 23:01:03 +00002232 Member->setInvalidDecl();
2233 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +00002234
2235 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +00002236
Larisse Voufo39a1e502013-08-06 01:03:05 +00002237 // If we have declared a member function template or static data member
2238 // template, set the access of the templated declaration as well.
Douglas Gregor3447e762009-08-20 22:52:58 +00002239 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
2240 FunTmpl->getTemplatedDecl()->setAccess(AS);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002241 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
2242 VarTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +00002243 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002244
Richard Smith18f07db2012-08-06 03:25:17 +00002245 if (VS.isOverrideSpecified())
Aaron Ballman36a53502014-01-16 13:03:14 +00002246 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
Richard Smith18f07db2012-08-06 03:25:17 +00002247 if (VS.isFinalSpecified())
David Majnemera5433082013-10-18 00:33:31 +00002248 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
2249 VS.isFinalSpelledSealed()));
Anders Carlssonfd835532011-01-20 05:57:14 +00002250
Douglas Gregorf2f08062011-03-08 17:10:18 +00002251 if (VS.getLastLocation().isValid()) {
2252 // Update the end location of a method that has a virt-specifiers.
2253 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
2254 MD->setRangeEnd(VS.getLastLocation());
2255 }
Richard Smith18f07db2012-08-06 03:25:17 +00002256
Anders Carlssonc87f8612011-01-20 06:29:02 +00002257 CheckOverrideControl(Member);
Anders Carlssonfd835532011-01-20 05:57:14 +00002258
Douglas Gregor92751d42008-11-17 22:58:34 +00002259 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002260
Daniel Jasper0baec5492012-06-06 08:32:04 +00002261 if (isInstField) {
2262 FieldDecl *FD = cast<FieldDecl>(Member);
2263 FieldCollector->Add(FD);
2264
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002265 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
Daniel Jasper0baec5492012-06-06 08:32:04 +00002266 // Remember all explicit private FieldDecls that have a name, no side
2267 // effects and are not part of a dependent type declaration.
2268 if (!FD->isImplicit() && FD->getDeclName() &&
2269 FD->getAccess() == AS_private &&
Daniel Jasper429c1342012-06-13 18:31:09 +00002270 !FD->hasAttr<UnusedAttr>() &&
Richard Smith0a8cfc72012-08-07 21:30:42 +00002271 !FD->getParent()->isDependentContext() &&
Daniel Jasper0baec5492012-06-06 08:32:04 +00002272 !InitializationHasSideEffects(*FD))
2273 UnusedPrivateFields.insert(FD);
2274 }
2275 }
2276
John McCall48871652010-08-21 09:40:31 +00002277 return Member;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002278}
2279
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002280namespace {
2281 class UninitializedFieldVisitor
2282 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2283 Sema &S;
Richard Trieuef64e942013-10-25 00:56:00 +00002284 // List of Decls to generate a warning on. Also remove Decls that become
2285 // initialized.
Craig Topper4dd9b432014-08-17 23:49:53 +00002286 llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
Richard Trieu3630c392014-11-21 03:10:30 +00002287 // List of base classes of the record. Classes are removed after their
2288 // initializers.
2289 llvm::SmallPtrSetImpl<QualType> &BaseClasses;
Richard Trieu8d08a272014-08-28 03:23:47 +00002290 // Vector of decls to be removed from the Decl set prior to visiting the
2291 // nodes. These Decls may have been initialized in the prior initializer.
2292 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
Richard Trieu406e65c2013-09-20 03:03:06 +00002293 // If non-null, add a note to the warning pointing back to the constructor.
NAKAMURA Takumi1af7cd72014-10-17 23:46:34 +00002294 const CXXConstructorDecl *Constructor;
Nick Lewycky314a4492014-10-17 22:45:44 +00002295 // Variables to hold state when processing an initializer list. When
Richard Trieufa1d0a72014-10-17 20:56:10 +00002296 // InitList is true, special case initialization of FieldDecls matching
2297 // InitListFieldDecl.
NAKAMURA Takumi1af7cd72014-10-17 23:46:34 +00002298 bool InitList;
2299 FieldDecl *InitListFieldDecl;
Richard Trieufa1d0a72014-10-17 20:56:10 +00002300 llvm::SmallVector<unsigned, 4> InitFieldIndex;
2301
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002302 public:
2303 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
Richard Trieuef64e942013-10-25 00:56:00 +00002304 UninitializedFieldVisitor(Sema &S,
Richard Trieu3630c392014-11-21 03:10:30 +00002305 llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
2306 llvm::SmallPtrSetImpl<QualType> &BaseClasses)
2307 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
2308 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002309
Richard Trieufa1d0a72014-10-17 20:56:10 +00002310 // Returns true if the use of ME is not an uninitialized use.
2311 bool IsInitListMemberExprInitialized(MemberExpr *ME,
2312 bool CheckReferenceOnly) {
2313 llvm::SmallVector<FieldDecl*, 4> Fields;
2314 bool ReferenceField = false;
2315 while (ME) {
2316 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
2317 if (!FD)
2318 return false;
2319 Fields.push_back(FD);
2320 if (FD->getType()->isReferenceType())
2321 ReferenceField = true;
2322 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
2323 }
2324
2325 // Binding a reference to an unintialized field is not an
2326 // uninitialized use.
2327 if (CheckReferenceOnly && !ReferenceField)
2328 return true;
2329
2330 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
2331 // Discard the first field since it is the field decl that is being
2332 // initialized.
2333 for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
2334 UsedFieldIndex.push_back((*I)->getFieldIndex());
2335 }
2336
2337 for (auto UsedIter = UsedFieldIndex.begin(),
2338 UsedEnd = UsedFieldIndex.end(),
2339 OrigIter = InitFieldIndex.begin(),
2340 OrigEnd = InitFieldIndex.end();
2341 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
2342 if (*UsedIter < *OrigIter)
2343 return true;
2344 if (*UsedIter > *OrigIter)
2345 break;
2346 }
2347
2348 return false;
2349 }
2350
Richard Trieu2d779b92014-10-01 03:44:58 +00002351 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
2352 bool AddressOf) {
Richard Trieu1bc22c12013-09-13 03:20:53 +00002353 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
2354 return;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002355
Richard Trieu1bc22c12013-09-13 03:20:53 +00002356 // FieldME is the inner-most MemberExpr that is not an anonymous struct
2357 // or union.
2358 MemberExpr *FieldME = ME;
2359
Richard Trieu2d779b92014-10-01 03:44:58 +00002360 bool AllPODFields = FieldME->getType().isPODType(S.Context);
2361
Richard Trieu1bc22c12013-09-13 03:20:53 +00002362 Expr *Base = ME;
Richard Trieu3630c392014-11-21 03:10:30 +00002363 while (MemberExpr *SubME =
2364 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
Richard Trieu1bc22c12013-09-13 03:20:53 +00002365
Richard Trieufa1d0a72014-10-17 20:56:10 +00002366 if (isa<VarDecl>(SubME->getMemberDecl()))
Richard Trieu1bc22c12013-09-13 03:20:53 +00002367 return;
2368
Richard Trieufa1d0a72014-10-17 20:56:10 +00002369 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
Richard Trieu1bc22c12013-09-13 03:20:53 +00002370 if (!FD->isAnonymousStructOrUnion())
Richard Trieufa1d0a72014-10-17 20:56:10 +00002371 FieldME = SubME;
Richard Trieu1bc22c12013-09-13 03:20:53 +00002372
Richard Trieu2d779b92014-10-01 03:44:58 +00002373 if (!FieldME->getType().isPODType(S.Context))
2374 AllPODFields = false;
2375
Richard Trieu3630c392014-11-21 03:10:30 +00002376 Base = SubME->getBase();
Richard Trieu1bc22c12013-09-13 03:20:53 +00002377 }
2378
Richard Trieu3630c392014-11-21 03:10:30 +00002379 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts()))
Richard Trieufd687772013-09-16 20:46:50 +00002380 return;
2381
Richard Trieu2d779b92014-10-01 03:44:58 +00002382 if (AddressOf && AllPODFields)
2383 return;
2384
Richard Trieu406e65c2013-09-20 03:03:06 +00002385 ValueDecl* FoundVD = FieldME->getMemberDecl();
2386
Richard Trieu3630c392014-11-21 03:10:30 +00002387 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
2388 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
2389 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
2390 }
2391
2392 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
2393 QualType T = BaseCast->getType();
2394 if (T->isPointerType() &&
2395 BaseClasses.count(T->getPointeeType())) {
2396 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
2397 << T->getPointeeType() << FoundVD;
2398 }
2399 }
2400 }
2401
Richard Trieuef64e942013-10-25 00:56:00 +00002402 if (!Decls.count(FoundVD))
Richard Trieu406e65c2013-09-20 03:03:06 +00002403 return;
2404
Richard Trieuef64e942013-10-25 00:56:00 +00002405 const bool IsReference = FoundVD->getType()->isReferenceType();
Richard Trieu406e65c2013-09-20 03:03:06 +00002406
Richard Trieufa1d0a72014-10-17 20:56:10 +00002407 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
2408 // Special checking for initializer lists.
2409 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
2410 return;
2411 }
2412 } else {
2413 // Prevent double warnings on use of unbounded references.
2414 if (CheckReferenceOnly && !IsReference)
2415 return;
2416 }
Richard Trieuef64e942013-10-25 00:56:00 +00002417
2418 unsigned diag = IsReference
2419 ? diag::warn_reference_field_is_uninit
2420 : diag::warn_field_is_uninit;
2421 S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
2422 if (Constructor)
2423 S.Diag(Constructor->getLocation(),
2424 diag::note_uninit_in_this_constructor)
2425 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
2426
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002427 }
2428
Richard Trieu2d779b92014-10-01 03:44:58 +00002429 void HandleValue(Expr *E, bool AddressOf) {
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002430 E = E->IgnoreParens();
2431
2432 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002433 HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
2434 AddressOf /*AddressOf*/);
Nick Lewyckyc363afb2012-11-15 08:19:20 +00002435 return;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002436 }
2437
2438 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002439 Visit(CO->getCond());
2440 HandleValue(CO->getTrueExpr(), AddressOf);
2441 HandleValue(CO->getFalseExpr(), AddressOf);
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002442 return;
2443 }
2444
2445 if (BinaryConditionalOperator *BCO =
2446 dyn_cast<BinaryConditionalOperator>(E)) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002447 Visit(BCO->getCond());
2448 HandleValue(BCO->getFalseExpr(), AddressOf);
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002449 return;
2450 }
2451
Richard Trieuabf6ec42014-08-27 22:15:10 +00002452 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002453 HandleValue(OVE->getSourceExpr(), AddressOf);
Richard Trieuabf6ec42014-08-27 22:15:10 +00002454 return;
2455 }
2456
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002457 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2458 switch (BO->getOpcode()) {
2459 default:
Richard Trieu2d779b92014-10-01 03:44:58 +00002460 break;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002461 case(BO_PtrMemD):
2462 case(BO_PtrMemI):
Richard Trieu2d779b92014-10-01 03:44:58 +00002463 HandleValue(BO->getLHS(), AddressOf);
2464 Visit(BO->getRHS());
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002465 return;
2466 case(BO_Comma):
Richard Trieu2d779b92014-10-01 03:44:58 +00002467 Visit(BO->getLHS());
2468 HandleValue(BO->getRHS(), AddressOf);
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002469 return;
2470 }
2471 }
Richard Trieu2d779b92014-10-01 03:44:58 +00002472
2473 Visit(E);
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002474 }
2475
Richard Trieufa1d0a72014-10-17 20:56:10 +00002476 void CheckInitListExpr(InitListExpr *ILE) {
2477 InitFieldIndex.push_back(0);
2478 for (auto Child : ILE->children()) {
2479 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
2480 CheckInitListExpr(SubList);
2481 } else {
2482 Visit(Child);
2483 }
2484 ++InitFieldIndex.back();
2485 }
2486 InitFieldIndex.pop_back();
2487 }
2488
Richard Trieu8d08a272014-08-28 03:23:47 +00002489 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
Richard Trieu3630c392014-11-21 03:10:30 +00002490 FieldDecl *Field, const Type *BaseClass) {
Richard Trieu8d08a272014-08-28 03:23:47 +00002491 // Remove Decls that may have been initialized in the previous
2492 // initializer.
2493 for (ValueDecl* VD : DeclsToRemove)
2494 Decls.erase(VD);
Richard Trieu8d08a272014-08-28 03:23:47 +00002495 DeclsToRemove.clear();
Richard Trieufa1d0a72014-10-17 20:56:10 +00002496
Richard Trieu8d08a272014-08-28 03:23:47 +00002497 Constructor = FieldConstructor;
Richard Trieufa1d0a72014-10-17 20:56:10 +00002498 InitListExpr *ILE = dyn_cast<InitListExpr>(E);
2499
2500 if (ILE && Field) {
2501 InitList = true;
2502 InitListFieldDecl = Field;
2503 InitFieldIndex.clear();
2504 CheckInitListExpr(ILE);
2505 } else {
2506 InitList = false;
2507 Visit(E);
2508 }
2509
Richard Trieu8d08a272014-08-28 03:23:47 +00002510 if (Field)
2511 Decls.erase(Field);
Richard Trieu3630c392014-11-21 03:10:30 +00002512 if (BaseClass)
2513 BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
Richard Trieu8d08a272014-08-28 03:23:47 +00002514 }
2515
Richard Trieu1bc22c12013-09-13 03:20:53 +00002516 void VisitMemberExpr(MemberExpr *ME) {
Richard Trieuef64e942013-10-25 00:56:00 +00002517 // All uses of unbounded reference fields will warn.
Richard Trieu2d779b92014-10-01 03:44:58 +00002518 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
Richard Trieu1bc22c12013-09-13 03:20:53 +00002519 }
2520
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002521 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002522 if (E->getCastKind() == CK_LValueToRValue) {
2523 HandleValue(E->getSubExpr(), false /*AddressOf*/);
2524 return;
2525 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002526
2527 Inherited::VisitImplicitCastExpr(E);
2528 }
2529
Richard Trieu1bc22c12013-09-13 03:20:53 +00002530 void VisitCXXConstructExpr(CXXConstructExpr *E) {
Richard Trieu4834ad22014-08-12 21:05:04 +00002531 if (E->getConstructor()->isCopyConstructor()) {
2532 Expr *ArgExpr = E->getArg(0);
Richard Trieu2d779b92014-10-01 03:44:58 +00002533 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
2534 if (ILE->getNumInits() == 1)
2535 ArgExpr = ILE->getInit(0);
2536 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
2537 if (ICE->getCastKind() == CK_NoOp)
Richard Trieu4834ad22014-08-12 21:05:04 +00002538 ArgExpr = ICE->getSubExpr();
Richard Trieu2d779b92014-10-01 03:44:58 +00002539 HandleValue(ArgExpr, false /*AddressOf*/);
2540 return;
Richard Trieu4834ad22014-08-12 21:05:04 +00002541 }
Richard Trieu1bc22c12013-09-13 03:20:53 +00002542 Inherited::VisitCXXConstructExpr(E);
2543 }
2544
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002545 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2546 Expr *Callee = E->getCallee();
Richard Trieu2d779b92014-10-01 03:44:58 +00002547 if (isa<MemberExpr>(Callee)) {
2548 HandleValue(Callee, false /*AddressOf*/);
Richard Trieu46847422014-11-01 00:46:54 +00002549 for (auto Arg : E->arguments())
2550 Visit(Arg);
Richard Trieu2d779b92014-10-01 03:44:58 +00002551 return;
2552 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002553
2554 Inherited::VisitCXXMemberCallExpr(E);
2555 }
Richard Trieu406e65c2013-09-20 03:03:06 +00002556
Richard Trieu11fd0792014-08-26 04:30:55 +00002557 void VisitCallExpr(CallExpr *E) {
2558 // Treat std::move as a use.
2559 if (E->getNumArgs() == 1) {
2560 if (FunctionDecl *FD = E->getDirectCallee()) {
Richard Trieuc321b932014-11-27 01:29:32 +00002561 if (FD->isInStdNamespace() && FD->getIdentifier() &&
2562 FD->getIdentifier()->isStr("move")) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002563 HandleValue(E->getArg(0), false /*AddressOf*/);
2564 return;
Richard Trieu11fd0792014-08-26 04:30:55 +00002565 }
2566 }
2567 }
2568
2569 Inherited::VisitCallExpr(E);
2570 }
2571
Richard Trieud4a01362014-10-31 21:10:22 +00002572 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
2573 Expr *Callee = E->getCallee();
2574
2575 if (isa<UnresolvedLookupExpr>(Callee))
2576 return Inherited::VisitCXXOperatorCallExpr(E);
2577
2578 Visit(Callee);
2579 for (auto Arg : E->arguments())
2580 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
2581 }
2582
Richard Trieu406e65c2013-09-20 03:03:06 +00002583 void VisitBinaryOperator(BinaryOperator *E) {
2584 // If a field assignment is detected, remove the field from the
2585 // uninitiailized field set.
2586 if (E->getOpcode() == BO_Assign)
2587 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
2588 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
Richard Trieuef64e942013-10-25 00:56:00 +00002589 if (!FD->getType()->isReferenceType())
Richard Trieu8d08a272014-08-28 03:23:47 +00002590 DeclsToRemove.push_back(FD);
Richard Trieu406e65c2013-09-20 03:03:06 +00002591
Richard Trieu52b8b602014-09-25 01:15:40 +00002592 if (E->isCompoundAssignmentOp()) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002593 HandleValue(E->getLHS(), false /*AddressOf*/);
2594 Visit(E->getRHS());
2595 return;
Richard Trieu52b8b602014-09-25 01:15:40 +00002596 }
2597
Richard Trieu406e65c2013-09-20 03:03:06 +00002598 Inherited::VisitBinaryOperator(E);
2599 }
Richard Trieu52b8b602014-09-25 01:15:40 +00002600
2601 void VisitUnaryOperator(UnaryOperator *E) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002602 if (E->isIncrementDecrementOp()) {
2603 HandleValue(E->getSubExpr(), false /*AddressOf*/);
2604 return;
2605 }
2606 if (E->getOpcode() == UO_AddrOf) {
2607 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
2608 HandleValue(ME->getBase(), true /*AddressOf*/);
2609 return;
2610 }
2611 }
Richard Trieu52b8b602014-09-25 01:15:40 +00002612
2613 Inherited::VisitUnaryOperator(E);
2614 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002615 };
Richard Trieuef64e942013-10-25 00:56:00 +00002616
2617 // Diagnose value-uses of fields to initialize themselves, e.g.
2618 // foo(foo)
2619 // where foo is not also a parameter to the constructor.
2620 // Also diagnose across field uninitialized use such as
2621 // x(y), y(x)
2622 // TODO: implement -Wuninitialized and fold this into that framework.
2623 static void DiagnoseUninitializedFields(
2624 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
2625
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002626 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
2627 Constructor->getLocation())) {
Richard Trieuef64e942013-10-25 00:56:00 +00002628 return;
2629 }
2630
2631 if (Constructor->isInvalidDecl())
2632 return;
2633
2634 const CXXRecordDecl *RD = Constructor->getParent();
2635
Richard Trieu353a4b42014-10-22 05:21:59 +00002636 if (RD->getDescribedClassTemplate())
Richard Trieu277ace02014-10-22 02:52:00 +00002637 return;
2638
Richard Trieuef64e942013-10-25 00:56:00 +00002639 // Holds fields that are uninitialized.
2640 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
2641
2642 // At the beginning, all fields are uninitialized.
Aaron Ballman629afae2014-03-07 19:56:05 +00002643 for (auto *I : RD->decls()) {
2644 if (auto *FD = dyn_cast<FieldDecl>(I)) {
Richard Trieuef64e942013-10-25 00:56:00 +00002645 UninitializedFields.insert(FD);
Aaron Ballman629afae2014-03-07 19:56:05 +00002646 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
Richard Trieuef64e942013-10-25 00:56:00 +00002647 UninitializedFields.insert(IFD->getAnonField());
2648 }
2649 }
2650
Richard Trieu3630c392014-11-21 03:10:30 +00002651 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
2652 for (auto I : RD->bases())
2653 UninitializedBaseClasses.insert(I.getType().getCanonicalType());
2654
2655 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
Richard Trieu8d08a272014-08-28 03:23:47 +00002656 return;
2657
2658 UninitializedFieldVisitor UninitializedChecker(SemaRef,
Richard Trieu3630c392014-11-21 03:10:30 +00002659 UninitializedFields,
2660 UninitializedBaseClasses);
Richard Trieu8d08a272014-08-28 03:23:47 +00002661
Aaron Ballman0ad78302014-03-13 17:34:31 +00002662 for (const auto *FieldInit : Constructor->inits()) {
Richard Trieu3630c392014-11-21 03:10:30 +00002663 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
Richard Trieu8d08a272014-08-28 03:23:47 +00002664 break;
2665
Aaron Ballman0ad78302014-03-13 17:34:31 +00002666 Expr *InitExpr = FieldInit->getInit();
Richard Trieu8d08a272014-08-28 03:23:47 +00002667 if (!InitExpr)
2668 continue;
Richard Trieuef64e942013-10-25 00:56:00 +00002669
Richard Trieu8d08a272014-08-28 03:23:47 +00002670 if (CXXDefaultInitExpr *Default =
2671 dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
2672 InitExpr = Default->getExpr();
2673 if (!InitExpr)
2674 continue;
2675 // In class initializers will point to the constructor.
2676 UninitializedChecker.CheckInitializer(InitExpr, Constructor,
Richard Trieu3630c392014-11-21 03:10:30 +00002677 FieldInit->getAnyMember(),
2678 FieldInit->getBaseClass());
Richard Trieu8d08a272014-08-28 03:23:47 +00002679 } else {
2680 UninitializedChecker.CheckInitializer(InitExpr, nullptr,
Richard Trieu3630c392014-11-21 03:10:30 +00002681 FieldInit->getAnyMember(),
2682 FieldInit->getBaseClass());
Richard Trieu8d08a272014-08-28 03:23:47 +00002683 }
Richard Trieuef64e942013-10-25 00:56:00 +00002684 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002685 }
2686} // namespace
2687
Richard Smith74108172014-01-17 03:11:34 +00002688/// \brief Enter a new C++ default initializer scope. After calling this, the
2689/// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
2690/// parsing or instantiating the initializer failed.
2691void Sema::ActOnStartCXXInClassMemberInitializer() {
2692 // Create a synthetic function scope to represent the call to the constructor
2693 // that notionally surrounds a use of this initializer.
2694 PushFunctionScope();
2695}
2696
2697/// \brief This is invoked after parsing an in-class initializer for a
2698/// non-static C++ class member, and after instantiating an in-class initializer
2699/// in a class template. Such actions are deferred until the class is complete.
2700void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
2701 SourceLocation InitLoc,
2702 Expr *InitExpr) {
2703 // Pop the notional constructor scope we created earlier.
Craig Topperc3ec1492014-05-26 06:22:03 +00002704 PopFunctionScopeInfo(nullptr, D);
Richard Smith74108172014-01-17 03:11:34 +00002705
David Majnemer87ff66c2014-12-13 11:34:16 +00002706 FieldDecl *FD = dyn_cast<FieldDecl>(D);
2707 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
Richard Smith2b013182012-06-10 03:12:00 +00002708 "must set init style when field is created");
Richard Smith938f40b2011-06-11 17:19:42 +00002709
2710 if (!InitExpr) {
David Majnemer87ff66c2014-12-13 11:34:16 +00002711 D->setInvalidDecl();
2712 if (FD)
2713 FD->removeInClassInitializer();
Richard Smith938f40b2011-06-11 17:19:42 +00002714 return;
2715 }
2716
Peter Collingbourne9f58d7b2011-10-23 18:59:44 +00002717 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
2718 FD->setInvalidDecl();
2719 FD->removeInClassInitializer();
2720 return;
2721 }
2722
Richard Smith938f40b2011-06-11 17:19:42 +00002723 ExprResult Init = InitExpr;
Richard Smithd59b8322012-12-19 01:39:02 +00002724 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
Sebastian Redleef474c2012-02-22 10:50:08 +00002725 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
Richard Smith2b013182012-06-10 03:12:00 +00002726 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
Sebastian Redleef474c2012-02-22 10:50:08 +00002727 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
Richard Smith2b013182012-06-10 03:12:00 +00002728 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002729 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2730 Init = Seq.Perform(*this, Entity, Kind, InitExpr);
Richard Smith938f40b2011-06-11 17:19:42 +00002731 if (Init.isInvalid()) {
2732 FD->setInvalidDecl();
2733 return;
2734 }
Richard Smith938f40b2011-06-11 17:19:42 +00002735 }
2736
Richard Smith945f8d32013-01-14 22:39:08 +00002737 // C++11 [class.base.init]p7:
Richard Smith938f40b2011-06-11 17:19:42 +00002738 // The initialization of each base and member constitutes a
2739 // full-expression.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002740 Init = ActOnFinishFullExpr(Init.get(), InitLoc);
Richard Smith938f40b2011-06-11 17:19:42 +00002741 if (Init.isInvalid()) {
2742 FD->setInvalidDecl();
2743 return;
2744 }
2745
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002746 InitExpr = Init.get();
Richard Smith938f40b2011-06-11 17:19:42 +00002747
2748 FD->setInClassInitializer(InitExpr);
2749}
2750
Douglas Gregor15e77a22009-12-31 09:10:24 +00002751/// \brief Find the direct and/or virtual base specifiers that
2752/// correspond to the given base type, for use in base initialization
2753/// within a constructor.
2754static bool FindBaseInitializer(Sema &SemaRef,
2755 CXXRecordDecl *ClassDecl,
2756 QualType BaseType,
2757 const CXXBaseSpecifier *&DirectBaseSpec,
2758 const CXXBaseSpecifier *&VirtualBaseSpec) {
2759 // First, check for a direct base class.
Craig Topperc3ec1492014-05-26 06:22:03 +00002760 DirectBaseSpec = nullptr;
Aaron Ballman574705e2014-03-13 15:41:46 +00002761 for (const auto &Base : ClassDecl->bases()) {
2762 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00002763 // We found a direct base of this type. That's what we're
2764 // initializing.
Aaron Ballman574705e2014-03-13 15:41:46 +00002765 DirectBaseSpec = &Base;
Douglas Gregor15e77a22009-12-31 09:10:24 +00002766 break;
2767 }
2768 }
2769
2770 // Check for a virtual base class.
2771 // FIXME: We might be able to short-circuit this if we know in advance that
2772 // there are no virtual bases.
Craig Topperc3ec1492014-05-26 06:22:03 +00002773 VirtualBaseSpec = nullptr;
Douglas Gregor15e77a22009-12-31 09:10:24 +00002774 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2775 // We haven't found a base yet; search the class hierarchy for a
2776 // virtual base class.
2777 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2778 /*DetectVirtual=*/false);
2779 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2780 BaseType, Paths)) {
2781 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2782 Path != Paths.end(); ++Path) {
2783 if (Path->back().Base->isVirtual()) {
2784 VirtualBaseSpec = Path->back().Base;
2785 break;
2786 }
2787 }
2788 }
2789 }
2790
2791 return DirectBaseSpec || VirtualBaseSpec;
2792}
2793
Sebastian Redla74948d2011-09-24 17:48:25 +00002794/// \brief Handle a C++ member initializer using braced-init-list syntax.
2795MemInitResult
2796Sema::ActOnMemInitializer(Decl *ConstructorD,
2797 Scope *S,
2798 CXXScopeSpec &SS,
2799 IdentifierInfo *MemberOrBase,
2800 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00002801 const DeclSpec &DS,
Sebastian Redla74948d2011-09-24 17:48:25 +00002802 SourceLocation IdLoc,
2803 Expr *InitList,
2804 SourceLocation EllipsisLoc) {
2805 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redla9351792012-02-11 23:51:47 +00002806 DS, IdLoc, InitList,
David Blaikie186a8892012-01-24 06:03:59 +00002807 EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002808}
2809
2810/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallfaf5fb42010-08-26 23:41:50 +00002811MemInitResult
John McCall48871652010-08-21 09:40:31 +00002812Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +00002813 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00002814 CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +00002815 IdentifierInfo *MemberOrBase,
John McCallba7bf592010-08-24 05:47:05 +00002816 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00002817 const DeclSpec &DS,
Douglas Gregore8381c02008-11-05 04:29:56 +00002818 SourceLocation IdLoc,
2819 SourceLocation LParenLoc,
Dmitri Gribenko139474d2013-05-09 23:51:52 +00002820 ArrayRef<Expr *> Args,
Douglas Gregor44e7df62011-01-04 00:32:56 +00002821 SourceLocation RParenLoc,
2822 SourceLocation EllipsisLoc) {
Benjamin Kramerc215e762012-08-24 11:54:20 +00002823 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
Dmitri Gribenko139474d2013-05-09 23:51:52 +00002824 Args, RParenLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002825 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redla9351792012-02-11 23:51:47 +00002826 DS, IdLoc, List, EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002827}
2828
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002829namespace {
2830
Kaelyn Uhrain8811b392012-01-11 21:17:51 +00002831// Callback to only accept typo corrections that can be a valid C++ member
2832// intializer: either a non-static field member or a base class.
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002833class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002834public:
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002835 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2836 : ClassDecl(ClassDecl) {}
2837
Craig Toppera798a9d2014-03-02 09:32:10 +00002838 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002839 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2840 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2841 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002842 return isa<TypeDecl>(ND);
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002843 }
2844 return false;
2845 }
2846
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002847private:
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002848 CXXRecordDecl *ClassDecl;
2849};
2850
2851}
2852
Sebastian Redla74948d2011-09-24 17:48:25 +00002853/// \brief Handle a C++ member initializer.
2854MemInitResult
2855Sema::BuildMemInitializer(Decl *ConstructorD,
2856 Scope *S,
2857 CXXScopeSpec &SS,
2858 IdentifierInfo *MemberOrBase,
2859 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00002860 const DeclSpec &DS,
Sebastian Redla74948d2011-09-24 17:48:25 +00002861 SourceLocation IdLoc,
Sebastian Redla9351792012-02-11 23:51:47 +00002862 Expr *Init,
Sebastian Redla74948d2011-09-24 17:48:25 +00002863 SourceLocation EllipsisLoc) {
Kaelyn Takataa15a6dc2014-12-08 22:41:42 +00002864 ExprResult Res = CorrectDelayedTyposInExpr(Init);
2865 if (!Res.isUsable())
2866 return true;
2867 Init = Res.get();
2868
Douglas Gregor71a57182009-06-22 23:20:33 +00002869 if (!ConstructorD)
2870 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002871
Douglas Gregorc8c277a2009-08-24 11:57:43 +00002872 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +00002873
2874 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002875 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregore8381c02008-11-05 04:29:56 +00002876 if (!Constructor) {
2877 // The user wrote a constructor initializer on a function that is
2878 // not a C++ constructor. Ignore the error for now, because we may
2879 // have more member initializers coming; we'll diagnose it just
2880 // once in ActOnMemInitializers.
2881 return true;
2882 }
2883
2884 CXXRecordDecl *ClassDecl = Constructor->getParent();
2885
2886 // C++ [class.base.init]p2:
2887 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky9331ed82010-11-20 01:29:55 +00002888 // constructor's class and, if not found in that scope, are looked
2889 // up in the scope containing the constructor's definition.
2890 // [Note: if the constructor's class contains a member with the
2891 // same name as a direct or virtual base class of the class, a
2892 // mem-initializer-id naming the member or base class and composed
2893 // of a single identifier refers to the class member. A
Douglas Gregore8381c02008-11-05 04:29:56 +00002894 // mem-initializer-id for the hidden base class may be specified
2895 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00002896 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00002897 // Look for a member, first.
Nico Weberaa0117c2014-11-12 03:44:43 +00002898 DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
David Blaikieff7d47a2012-12-19 00:45:41 +00002899 if (!Result.empty()) {
Peter Collingbourne05156e32011-10-23 18:59:37 +00002900 ValueDecl *Member;
David Blaikieff7d47a2012-12-19 00:45:41 +00002901 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2902 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
Douglas Gregor44e7df62011-01-04 00:32:56 +00002903 if (EllipsisLoc.isValid())
2904 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redla9351792012-02-11 23:51:47 +00002905 << MemberOrBase
2906 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redla74948d2011-09-24 17:48:25 +00002907
Sebastian Redla9351792012-02-11 23:51:47 +00002908 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00002909 }
Francois Pichetd583da02010-12-04 09:14:42 +00002910 }
Douglas Gregore8381c02008-11-05 04:29:56 +00002911 }
Douglas Gregore8381c02008-11-05 04:29:56 +00002912 // It didn't name a member, so see if it names a class.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00002913 QualType BaseType;
Craig Topperc3ec1492014-05-26 06:22:03 +00002914 TypeSourceInfo *TInfo = nullptr;
John McCallb5a0d312009-12-21 10:41:20 +00002915
2916 if (TemplateTypeTy) {
John McCallbcd03502009-12-07 02:54:59 +00002917 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikie186a8892012-01-24 06:03:59 +00002918 } else if (DS.getTypeSpecType() == TST_decltype) {
2919 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCallb5a0d312009-12-21 10:41:20 +00002920 } else {
2921 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2922 LookupParsedName(R, S, &SS);
2923
2924 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2925 if (!TyD) {
2926 if (R.isAmbiguous()) return true;
2927
John McCallda6841b2010-04-09 19:01:14 +00002928 // We don't want access-control diagnostics here.
2929 R.suppressDiagnostics();
2930
Douglas Gregora3b624a2010-01-19 06:46:48 +00002931 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2932 bool NotUnknownSpecialization = false;
2933 DeclContext *DC = computeDeclContext(SS, false);
2934 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2935 NotUnknownSpecialization = !Record->hasAnyDependentBases();
2936
2937 if (!NotUnknownSpecialization) {
2938 // When the scope specifier can refer to a member of an unknown
2939 // specialization, we take it as a type name.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00002940 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2941 SS.getWithLocInContext(Context),
2942 *MemberOrBase, IdLoc);
Douglas Gregor281c4862010-03-07 23:26:22 +00002943 if (BaseType.isNull())
2944 return true;
2945
Douglas Gregora3b624a2010-01-19 06:46:48 +00002946 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00002947 R.setLookupName(MemberOrBase);
Douglas Gregora3b624a2010-01-19 06:46:48 +00002948 }
2949 }
2950
Douglas Gregor15e77a22009-12-31 09:10:24 +00002951 // If no results were found, try to correct typos.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002952 TypoCorrection Corr;
Douglas Gregora3b624a2010-01-19 06:46:48 +00002953 if (R.empty() && BaseType.isNull() &&
Kaelyn Takata89c881b2014-10-27 18:07:29 +00002954 (Corr = CorrectTypo(
2955 R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
2956 llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl),
2957 CTK_ErrorRecovery, ClassDecl))) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002958 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002959 // We have found a non-static data member with a similar
2960 // name to what was typed; complain and initialize that
2961 // member.
Richard Smithf9b15102013-08-17 00:46:16 +00002962 diagnoseTypo(Corr,
2963 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2964 << MemberOrBase << true);
Sebastian Redla9351792012-02-11 23:51:47 +00002965 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002966 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00002967 const CXXBaseSpecifier *DirectBaseSpec;
2968 const CXXBaseSpecifier *VirtualBaseSpec;
2969 if (FindBaseInitializer(*this, ClassDecl,
2970 Context.getTypeDeclType(Type),
2971 DirectBaseSpec, VirtualBaseSpec)) {
2972 // We have found a direct or virtual base class with a
2973 // similar name to what was typed; complain and initialize
2974 // that base class.
Richard Smithf9b15102013-08-17 00:46:16 +00002975 diagnoseTypo(Corr,
2976 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2977 << MemberOrBase << false,
2978 PDiag() /*Suppress note, we provide our own.*/);
Douglas Gregor43a08572010-01-07 00:26:25 +00002979
Richard Smithf9b15102013-08-17 00:46:16 +00002980 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
2981 : VirtualBaseSpec;
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002982 Diag(BaseSpec->getLocStart(),
Douglas Gregor43a08572010-01-07 00:26:25 +00002983 diag::note_base_class_specified_here)
2984 << BaseSpec->getType()
2985 << BaseSpec->getSourceRange();
2986
Douglas Gregor15e77a22009-12-31 09:10:24 +00002987 TyD = Type;
2988 }
2989 }
2990 }
2991
Douglas Gregora3b624a2010-01-19 06:46:48 +00002992 if (!TyD && BaseType.isNull()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00002993 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redla9351792012-02-11 23:51:47 +00002994 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregor15e77a22009-12-31 09:10:24 +00002995 return true;
2996 }
John McCallb5a0d312009-12-21 10:41:20 +00002997 }
2998
Douglas Gregora3b624a2010-01-19 06:46:48 +00002999 if (BaseType.isNull()) {
3000 BaseType = Context.getTypeDeclType(TyD);
Nico Weber28309182014-11-12 03:52:25 +00003001 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
Aaron Ballman4a979672014-01-03 13:56:08 +00003002 if (SS.isSet())
Douglas Gregora3b624a2010-01-19 06:46:48 +00003003 // FIXME: preserve source range information
Aaron Ballman4a979672014-01-03 13:56:08 +00003004 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
3005 BaseType);
John McCallb5a0d312009-12-21 10:41:20 +00003006 }
3007 }
Mike Stump11289f42009-09-09 15:08:12 +00003008
John McCallbcd03502009-12-07 02:54:59 +00003009 if (!TInfo)
3010 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00003011
Sebastian Redla9351792012-02-11 23:51:47 +00003012 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00003013}
3014
Chandler Carruth599deef2011-09-03 01:14:15 +00003015/// Checks a member initializer expression for cases where reference (or
3016/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth599deef2011-09-03 01:14:15 +00003017static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
3018 Expr *Init,
3019 SourceLocation IdLoc) {
3020 QualType MemberTy = Member->getType();
3021
3022 // We only handle pointers and references currently.
3023 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
3024 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
3025 return;
3026
3027 const bool IsPointer = MemberTy->isPointerType();
3028 if (IsPointer) {
3029 if (const UnaryOperator *Op
3030 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
3031 // The only case we're worried about with pointers requires taking the
3032 // address.
3033 if (Op->getOpcode() != UO_AddrOf)
3034 return;
3035
3036 Init = Op->getSubExpr();
3037 } else {
3038 // We only handle address-of expression initializers for pointers.
3039 return;
3040 }
3041 }
3042
Richard Smithe3b28bc2013-06-12 21:51:50 +00003043 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
Chandler Carruthd551d4e2011-09-03 02:21:57 +00003044 // We only warn when referring to a non-reference parameter declaration.
3045 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
3046 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth599deef2011-09-03 01:14:15 +00003047 return;
3048
3049 S.Diag(Init->getExprLoc(),
3050 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
3051 : diag::warn_bind_ref_member_to_parameter)
3052 << Member << Parameter << Init->getSourceRange();
Chandler Carruthd551d4e2011-09-03 02:21:57 +00003053 } else {
3054 // Other initializers are fine.
3055 return;
Chandler Carruth599deef2011-09-03 01:14:15 +00003056 }
Chandler Carruthd551d4e2011-09-03 02:21:57 +00003057
3058 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
3059 << (unsigned)IsPointer;
Chandler Carruth599deef2011-09-03 01:14:15 +00003060}
3061
John McCallfaf5fb42010-08-26 23:41:50 +00003062MemInitResult
Sebastian Redla9351792012-02-11 23:51:47 +00003063Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redla74948d2011-09-24 17:48:25 +00003064 SourceLocation IdLoc) {
Chandler Carruthd44c3102010-12-06 09:23:57 +00003065 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
3066 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
3067 assert((DirectMember || IndirectMember) &&
Francois Pichetd583da02010-12-04 09:14:42 +00003068 "Member must be a FieldDecl or IndirectFieldDecl");
3069
Sebastian Redla9351792012-02-11 23:51:47 +00003070 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbourne9f58d7b2011-10-23 18:59:44 +00003071 return true;
3072
Douglas Gregor266bb5f2010-11-05 22:21:31 +00003073 if (Member->isInvalidDecl())
3074 return true;
Chandler Carruthd44c3102010-12-06 09:23:57 +00003075
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003076 MultiExprArg Args;
Sebastian Redla9351792012-02-11 23:51:47 +00003077 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003078 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Richard Smithd59b8322012-12-19 01:39:02 +00003079 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003080 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Richard Smithd59b8322012-12-19 01:39:02 +00003081 } else {
3082 // Template instantiation doesn't reconstruct ParenListExprs for us.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003083 Args = Init;
Sebastian Redla9351792012-02-11 23:51:47 +00003084 }
Daniel Jasper0baec5492012-06-06 08:32:04 +00003085
Sebastian Redla9351792012-02-11 23:51:47 +00003086 SourceRange InitRange = Init->getSourceRange();
Eli Friedman8e1433b2009-07-29 19:44:27 +00003087
Sebastian Redla9351792012-02-11 23:51:47 +00003088 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003089 // Can't check initialization for a member of dependent type or when
3090 // any of the arguments are type-dependent expressions.
John McCall31168b02011-06-15 23:02:42 +00003091 DiscardCleanupsInEvaluationContext();
Chandler Carruthd44c3102010-12-06 09:23:57 +00003092 } else {
Sebastian Redl0501c632012-02-12 16:37:36 +00003093 bool InitList = false;
3094 if (isa<InitListExpr>(Init)) {
3095 InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003096 Args = Init;
Sebastian Redl0501c632012-02-12 16:37:36 +00003097 }
3098
Chandler Carruthd44c3102010-12-06 09:23:57 +00003099 // Initialize the member.
3100 InitializedEntity MemberEntity =
Craig Topperc3ec1492014-05-26 06:22:03 +00003101 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
3102 : InitializedEntity::InitializeMember(IndirectMember,
3103 nullptr);
Chandler Carruthd44c3102010-12-06 09:23:57 +00003104 InitializationKind Kind =
Sebastian Redl0501c632012-02-12 16:37:36 +00003105 InitList ? InitializationKind::CreateDirectList(IdLoc)
3106 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
3107 InitRange.getEnd());
John McCallacf0ee52010-10-08 02:01:28 +00003108
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003109 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
Craig Topperc3ec1492014-05-26 06:22:03 +00003110 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
3111 nullptr);
Chandler Carruthd44c3102010-12-06 09:23:57 +00003112 if (MemberInit.isInvalid())
3113 return true;
3114
Richard Smith736a9472013-06-12 20:42:33 +00003115 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
3116
Richard Smith945f8d32013-01-14 22:39:08 +00003117 // C++11 [class.base.init]p7:
Chandler Carruthd44c3102010-12-06 09:23:57 +00003118 // The initialization of each base and member constitutes a
3119 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00003120 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
Chandler Carruthd44c3102010-12-06 09:23:57 +00003121 if (MemberInit.isInvalid())
3122 return true;
3123
Richard Smithd59b8322012-12-19 01:39:02 +00003124 Init = MemberInit.get();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003125 }
3126
Chandler Carruthd44c3102010-12-06 09:23:57 +00003127 if (DirectMember) {
Sebastian Redla9351792012-02-11 23:51:47 +00003128 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
3129 InitRange.getBegin(), Init,
3130 InitRange.getEnd());
Chandler Carruthd44c3102010-12-06 09:23:57 +00003131 } else {
Sebastian Redla9351792012-02-11 23:51:47 +00003132 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
3133 InitRange.getBegin(), Init,
3134 InitRange.getEnd());
Chandler Carruthd44c3102010-12-06 09:23:57 +00003135 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00003136}
3137
John McCallfaf5fb42010-08-26 23:41:50 +00003138MemInitResult
Sebastian Redla9351792012-02-11 23:51:47 +00003139Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Alexis Huntc5575cc2011-02-26 19:13:13 +00003140 CXXRecordDecl *ClassDecl) {
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003141 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003142 if (!LangOpts.CPlusPlus11)
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003143 return Diag(NameLoc, diag::err_delegating_ctor)
Alexis Hunt4049b8d2011-01-08 19:20:43 +00003144 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003145 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redl9cb4be22011-03-12 13:53:51 +00003146
Sebastian Redl0501c632012-02-12 16:37:36 +00003147 bool InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003148 MultiExprArg Args = Init;
Sebastian Redl0501c632012-02-12 16:37:36 +00003149 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3150 InitList = false;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003151 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redl0501c632012-02-12 16:37:36 +00003152 }
3153
Sebastian Redla9351792012-02-11 23:51:47 +00003154 SourceRange InitRange = Init->getSourceRange();
Alexis Huntc5575cc2011-02-26 19:13:13 +00003155 // Initialize the object.
3156 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
3157 QualType(ClassDecl->getTypeForDecl(), 0));
3158 InitializationKind Kind =
Sebastian Redl0501c632012-02-12 16:37:36 +00003159 InitList ? InitializationKind::CreateDirectList(NameLoc)
3160 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
3161 InitRange.getEnd());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003162 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
Sebastian Redla9351792012-02-11 23:51:47 +00003163 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
Craig Topperc3ec1492014-05-26 06:22:03 +00003164 Args, nullptr);
Alexis Huntc5575cc2011-02-26 19:13:13 +00003165 if (DelegationInit.isInvalid())
3166 return true;
3167
Matt Beaumont-Gay3e59fac2011-11-01 18:10:22 +00003168 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
3169 "Delegating constructor with no target?");
Alexis Huntc5575cc2011-02-26 19:13:13 +00003170
Richard Smith945f8d32013-01-14 22:39:08 +00003171 // C++11 [class.base.init]p7:
Alexis Huntc5575cc2011-02-26 19:13:13 +00003172 // The initialization of each base and member constitutes a
3173 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00003174 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
3175 InitRange.getBegin());
Alexis Huntc5575cc2011-02-26 19:13:13 +00003176 if (DelegationInit.isInvalid())
3177 return true;
3178
Eli Friedmana9e9ebc2012-05-19 23:35:23 +00003179 // If we are in a dependent context, template instantiation will
3180 // perform this type-checking again. Just save the arguments that we
3181 // received in a ParenListExpr.
3182 // FIXME: This isn't quite ideal, since our ASTs don't capture all
3183 // of the information that we have about the base
3184 // initializer. However, deconstructing the ASTs is a dicey process,
3185 // and this approach is far more likely to get the corner cases right.
3186 if (CurContext->isDependentContext())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003187 DelegationInit = Init;
Eli Friedmana9e9ebc2012-05-19 23:35:23 +00003188
Sebastian Redla9351792012-02-11 23:51:47 +00003189 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003190 DelegationInit.getAs<Expr>(),
Sebastian Redla9351792012-02-11 23:51:47 +00003191 InitRange.getEnd());
Alexis Hunt4049b8d2011-01-08 19:20:43 +00003192}
3193
3194MemInitResult
John McCallbcd03502009-12-07 02:54:59 +00003195Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redla9351792012-02-11 23:51:47 +00003196 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor44e7df62011-01-04 00:32:56 +00003197 SourceLocation EllipsisLoc) {
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003198 SourceLocation BaseLoc
3199 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redla74948d2011-09-24 17:48:25 +00003200
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003201 if (!BaseType->isDependentType() && !BaseType->isRecordType())
3202 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
3203 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
3204
3205 // C++ [class.base.init]p2:
3206 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky9331ed82010-11-20 01:29:55 +00003207 // member of the constructor's class or a direct or virtual base
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003208 // of that class, the mem-initializer is ill-formed. A
3209 // mem-initializer-list can initialize a base class using any
3210 // name that denotes that base class type.
Sebastian Redla9351792012-02-11 23:51:47 +00003211 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003212
Sebastian Redla9351792012-02-11 23:51:47 +00003213 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor44e7df62011-01-04 00:32:56 +00003214 if (EllipsisLoc.isValid()) {
3215 // This is a pack expansion.
3216 if (!BaseType->containsUnexpandedParameterPack()) {
3217 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redla9351792012-02-11 23:51:47 +00003218 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redla74948d2011-09-24 17:48:25 +00003219
Douglas Gregor44e7df62011-01-04 00:32:56 +00003220 EllipsisLoc = SourceLocation();
3221 }
3222 } else {
3223 // Check for any unexpanded parameter packs.
3224 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
3225 return true;
Sebastian Redla74948d2011-09-24 17:48:25 +00003226
Sebastian Redla9351792012-02-11 23:51:47 +00003227 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redla74948d2011-09-24 17:48:25 +00003228 return true;
Douglas Gregor44e7df62011-01-04 00:32:56 +00003229 }
Sebastian Redla74948d2011-09-24 17:48:25 +00003230
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003231 // Check for direct and virtual base classes.
Craig Topperc3ec1492014-05-26 06:22:03 +00003232 const CXXBaseSpecifier *DirectBaseSpec = nullptr;
3233 const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003234 if (!Dependent) {
Alexis Hunt4049b8d2011-01-08 19:20:43 +00003235 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
3236 BaseType))
Sebastian Redla9351792012-02-11 23:51:47 +00003237 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Alexis Hunt4049b8d2011-01-08 19:20:43 +00003238
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003239 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
3240 VirtualBaseSpec);
3241
3242 // C++ [base.class.init]p2:
3243 // Unless the mem-initializer-id names a nonstatic data member of the
3244 // constructor's class or a direct or virtual base of that class, the
3245 // mem-initializer is ill-formed.
3246 if (!DirectBaseSpec && !VirtualBaseSpec) {
3247 // If the class has any dependent bases, then it's possible that
3248 // one of those types will resolve to the same type as
3249 // BaseType. Therefore, just treat this as a dependent base
3250 // class initialization. FIXME: Should we try to check the
3251 // initialization anyway? It seems odd.
3252 if (ClassDecl->hasAnyDependentBases())
3253 Dependent = true;
3254 else
3255 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
3256 << BaseType << Context.getTypeDeclType(ClassDecl)
3257 << BaseTInfo->getTypeLoc().getLocalSourceRange();
3258 }
3259 }
3260
3261 if (Dependent) {
John McCall31168b02011-06-15 23:02:42 +00003262 DiscardCleanupsInEvaluationContext();
Mike Stump11289f42009-09-09 15:08:12 +00003263
Sebastian Redla74948d2011-09-24 17:48:25 +00003264 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
3265 /*IsVirtual=*/false,
Sebastian Redla9351792012-02-11 23:51:47 +00003266 InitRange.getBegin(), Init,
3267 InitRange.getEnd(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00003268 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003269
3270 // C++ [base.class.init]p2:
3271 // If a mem-initializer-id is ambiguous because it designates both
3272 // a direct non-virtual base class and an inherited virtual base
3273 // class, the mem-initializer is ill-formed.
3274 if (DirectBaseSpec && VirtualBaseSpec)
3275 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00003276 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003277
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003278 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003279 if (!BaseSpec)
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003280 BaseSpec = VirtualBaseSpec;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003281
3282 // Initialize the base.
Sebastian Redl0501c632012-02-12 16:37:36 +00003283 bool InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003284 MultiExprArg Args = Init;
Sebastian Redla9351792012-02-11 23:51:47 +00003285 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl0501c632012-02-12 16:37:36 +00003286 InitList = false;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003287 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redla9351792012-02-11 23:51:47 +00003288 }
Sebastian Redl0501c632012-02-12 16:37:36 +00003289
3290 InitializedEntity BaseEntity =
3291 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
3292 InitializationKind Kind =
3293 InitList ? InitializationKind::CreateDirectList(BaseLoc)
3294 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
3295 InitRange.getEnd());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003296 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
Craig Topperc3ec1492014-05-26 06:22:03 +00003297 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003298 if (BaseInit.isInvalid())
3299 return true;
John McCallacf0ee52010-10-08 02:01:28 +00003300
Richard Smith945f8d32013-01-14 22:39:08 +00003301 // C++11 [class.base.init]p7:
3302 // The initialization of each base and member constitutes a
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003303 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00003304 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003305 if (BaseInit.isInvalid())
3306 return true;
3307
3308 // If we are in a dependent context, template instantiation will
3309 // perform this type-checking again. Just save the arguments that we
3310 // received in a ParenListExpr.
3311 // FIXME: This isn't quite ideal, since our ASTs don't capture all
3312 // of the information that we have about the base
3313 // initializer. However, deconstructing the ASTs is a dicey process,
3314 // and this approach is far more likely to get the corner cases right.
Sebastian Redla74948d2011-09-24 17:48:25 +00003315 if (CurContext->isDependentContext())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003316 BaseInit = Init;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003317
Alexis Hunt1d792652011-01-08 20:30:50 +00003318 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redla74948d2011-09-24 17:48:25 +00003319 BaseSpec->isVirtual(),
Sebastian Redla9351792012-02-11 23:51:47 +00003320 InitRange.getBegin(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003321 BaseInit.getAs<Expr>(),
Sebastian Redla9351792012-02-11 23:51:47 +00003322 InitRange.getEnd(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00003323}
3324
Sebastian Redl22653ba2011-08-30 19:58:05 +00003325// Create a static_cast\<T&&>(expr).
Richard Smithc2bc61b2013-03-18 21:12:30 +00003326static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
3327 if (T.isNull()) T = E->getType();
3328 QualType TargetType = SemaRef.BuildReferenceType(
3329 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
Sebastian Redl22653ba2011-08-30 19:58:05 +00003330 SourceLocation ExprLoc = E->getLocStart();
3331 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
3332 TargetType, ExprLoc);
3333
3334 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
3335 SourceRange(ExprLoc, ExprLoc),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003336 E->getSourceRange()).get();
Sebastian Redl22653ba2011-08-30 19:58:05 +00003337}
3338
Anders Carlsson1b00e242010-04-23 03:10:23 +00003339/// ImplicitInitializerKind - How an implicit base or member initializer should
3340/// initialize its base or member.
3341enum ImplicitInitializerKind {
3342 IIK_Default,
3343 IIK_Copy,
Richard Smithc2bc61b2013-03-18 21:12:30 +00003344 IIK_Move,
3345 IIK_Inherit
Anders Carlsson1b00e242010-04-23 03:10:23 +00003346};
3347
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003348static bool
Anders Carlsson3c1db572010-04-23 02:15:47 +00003349BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00003350 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson43c64af2010-04-21 19:52:01 +00003351 CXXBaseSpecifier *BaseSpec,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003352 bool IsInheritedVirtualBase,
Alexis Hunt1d792652011-01-08 20:30:50 +00003353 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003354 InitializedEntity InitEntity
Anders Carlsson43c64af2010-04-21 19:52:01 +00003355 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
3356 IsInheritedVirtualBase);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003357
John McCalldadc5752010-08-24 06:29:42 +00003358 ExprResult BaseInit;
Anders Carlsson1b00e242010-04-23 03:10:23 +00003359
3360 switch (ImplicitInitKind) {
Richard Smithc2bc61b2013-03-18 21:12:30 +00003361 case IIK_Inherit: {
3362 const CXXRecordDecl *Inherited =
3363 Constructor->getInheritedConstructor()->getParent();
3364 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
3365 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
3366 // C++11 [class.inhctor]p8:
3367 // Each expression in the expression-list is of the form
3368 // static_cast<T&&>(p), where p is the name of the corresponding
3369 // constructor parameter and T is the declared type of p.
3370 SmallVector<Expr*, 16> Args;
3371 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
3372 ParmVarDecl *PD = Constructor->getParamDecl(I);
3373 ExprResult ArgExpr =
3374 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
3375 VK_LValue, SourceLocation());
3376 if (ArgExpr.isInvalid())
3377 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003378 Args.push_back(CastForMoving(SemaRef, ArgExpr.get(), PD->getType()));
Richard Smithc2bc61b2013-03-18 21:12:30 +00003379 }
3380
3381 InitializationKind InitKind = InitializationKind::CreateDirect(
3382 Constructor->getLocation(), SourceLocation(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003383 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args);
Richard Smithc2bc61b2013-03-18 21:12:30 +00003384 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
3385 break;
3386 }
3387 }
3388 // Fall through.
Anders Carlsson1b00e242010-04-23 03:10:23 +00003389 case IIK_Default: {
3390 InitializationKind InitKind
3391 = InitializationKind::CreateDefault(Constructor->getLocation());
Dmitri Gribenko78852e92013-05-05 20:40:26 +00003392 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3393 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
Anders Carlsson1b00e242010-04-23 03:10:23 +00003394 break;
3395 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003396
Sebastian Redl22653ba2011-08-30 19:58:05 +00003397 case IIK_Move:
Anders Carlsson1b00e242010-04-23 03:10:23 +00003398 case IIK_Copy: {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003399 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson1b00e242010-04-23 03:10:23 +00003400 ParmVarDecl *Param = Constructor->getParamDecl(0);
3401 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedman2dfa7932012-01-16 21:00:51 +00003402
Anders Carlsson1b00e242010-04-23 03:10:23 +00003403 Expr *CopyCtorArg =
Abramo Bagnara7945c982012-01-27 09:46:47 +00003404 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCall113bee02012-03-10 09:33:50 +00003405 SourceLocation(), Param, false,
John McCall7decc9e2010-11-18 06:31:45 +00003406 Constructor->getLocation(), ParamType,
Craig Topperc3ec1492014-05-26 06:22:03 +00003407 VK_LValue, nullptr);
Sebastian Redl22653ba2011-08-30 19:58:05 +00003408
Eli Friedmanfa0df832012-02-02 03:46:19 +00003409 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
3410
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00003411 // Cast to the base class to avoid ambiguities.
Anders Carlsson79111502010-05-01 16:39:01 +00003412 QualType ArgTy =
3413 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
3414 ParamType.getQualifiers());
John McCallcf142162010-08-07 06:22:56 +00003415
Sebastian Redl22653ba2011-08-30 19:58:05 +00003416 if (Moving) {
3417 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
3418 }
3419
John McCallcf142162010-08-07 06:22:56 +00003420 CXXCastPath BasePath;
3421 BasePath.push_back(BaseSpec);
John Wiegley01296292011-04-08 18:41:53 +00003422 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
3423 CK_UncheckedDerivedToBase,
Sebastian Redle9c4e842011-09-04 18:14:28 +00003424 Moving ? VK_XValue : VK_LValue,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003425 &BasePath).get();
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00003426
Anders Carlsson1b00e242010-04-23 03:10:23 +00003427 InitializationKind InitKind
3428 = InitializationKind::CreateDirect(Constructor->getLocation(),
3429 SourceLocation(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003430 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
3431 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
Anders Carlsson1b00e242010-04-23 03:10:23 +00003432 break;
3433 }
Anders Carlsson1b00e242010-04-23 03:10:23 +00003434 }
John McCallb268a282010-08-23 23:25:46 +00003435
Douglas Gregora40433a2010-12-07 00:41:46 +00003436 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003437 if (BaseInit.isInvalid())
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003438 return true;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003439
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003440 CXXBaseInit =
Alexis Hunt1d792652011-01-08 20:30:50 +00003441 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003442 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
3443 SourceLocation()),
3444 BaseSpec->isVirtual(),
3445 SourceLocation(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003446 BaseInit.getAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00003447 SourceLocation(),
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003448 SourceLocation());
3449
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003450 return false;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003451}
3452
Sebastian Redl22653ba2011-08-30 19:58:05 +00003453static bool RefersToRValueRef(Expr *MemRef) {
3454 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
3455 return Referenced->getType()->isRValueReferenceType();
3456}
3457
Anders Carlsson3c1db572010-04-23 02:15:47 +00003458static bool
3459BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00003460 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor493627b2011-08-10 15:22:55 +00003461 FieldDecl *Field, IndirectFieldDecl *Indirect,
Alexis Hunt1d792652011-01-08 20:30:50 +00003462 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00003463 if (Field->isInvalidDecl())
3464 return true;
3465
Chandler Carruth9c9286b2010-06-29 23:50:44 +00003466 SourceLocation Loc = Constructor->getLocation();
3467
Sebastian Redl22653ba2011-08-30 19:58:05 +00003468 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
3469 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson423f5d82010-04-23 16:04:08 +00003470 ParmVarDecl *Param = Constructor->getParamDecl(0);
3471 QualType ParamType = Param->getType().getNonReferenceType();
John McCall1b1a1db2011-06-17 00:18:42 +00003472
3473 // Suppress copying zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +00003474 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
3475 return false;
Douglas Gregor10f939c2011-11-02 23:04:16 +00003476
Anders Carlsson423f5d82010-04-23 16:04:08 +00003477 Expr *MemberExprBase =
Abramo Bagnara7945c982012-01-27 09:46:47 +00003478 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCall113bee02012-03-10 09:33:50 +00003479 SourceLocation(), Param, false,
Craig Topperc3ec1492014-05-26 06:22:03 +00003480 Loc, ParamType, VK_LValue, nullptr);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003481
Eli Friedmanfa0df832012-02-02 03:46:19 +00003482 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
3483
Sebastian Redl22653ba2011-08-30 19:58:05 +00003484 if (Moving) {
3485 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
3486 }
3487
Douglas Gregor94f9a482010-05-05 05:51:00 +00003488 // Build a reference to this field within the parameter.
3489 CXXScopeSpec SS;
3490 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
3491 Sema::LookupMemberName);
Sebastian Redl22653ba2011-08-30 19:58:05 +00003492 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
3493 : cast<ValueDecl>(Field), AS_public);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003494 MemberLookup.resolveKind();
Sebastian Redle9c4e842011-09-04 18:14:28 +00003495 ExprResult CtorArg
John McCallb268a282010-08-23 23:25:46 +00003496 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregor94f9a482010-05-05 05:51:00 +00003497 ParamType, Loc,
3498 /*IsArrow=*/false,
3499 SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00003500 /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00003501 /*FirstQualifierInScope=*/nullptr,
Douglas Gregor94f9a482010-05-05 05:51:00 +00003502 MemberLookup,
Craig Topperc3ec1492014-05-26 06:22:03 +00003503 /*TemplateArgs=*/nullptr);
Sebastian Redle9c4e842011-09-04 18:14:28 +00003504 if (CtorArg.isInvalid())
Anders Carlsson423f5d82010-04-23 16:04:08 +00003505 return true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00003506
3507 // C++11 [class.copy]p15:
3508 // - if a member m has rvalue reference type T&&, it is direct-initialized
3509 // with static_cast<T&&>(x.m);
Sebastian Redle9c4e842011-09-04 18:14:28 +00003510 if (RefersToRValueRef(CtorArg.get())) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003511 CtorArg = CastForMoving(SemaRef, CtorArg.get());
Sebastian Redl22653ba2011-08-30 19:58:05 +00003512 }
3513
Douglas Gregor94f9a482010-05-05 05:51:00 +00003514 // When the field we are copying is an array, create index variables for
3515 // each dimension of the array. We use these index variables to subscript
3516 // the source array, and other clients (e.g., CodeGen) will perform the
3517 // necessary iteration with these index variables.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003518 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003519 QualType BaseType = Field->getType();
3520 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl22653ba2011-08-30 19:58:05 +00003521 bool InitializingArray = false;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003522 while (const ConstantArrayType *Array
3523 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003524 InitializingArray = true;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003525 // Create the iteration variable for this array index.
Craig Topperc3ec1492014-05-26 06:22:03 +00003526 IdentifierInfo *IterationVarName = nullptr;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003527 {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003528 SmallString<8> Str;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003529 llvm::raw_svector_ostream OS(Str);
3530 OS << "__i" << IndexVariables.size();
3531 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
3532 }
3533 VarDecl *IterationVar
Abramo Bagnaradff19302011-03-08 08:55:46 +00003534 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregor94f9a482010-05-05 05:51:00 +00003535 IterationVarName, SizeType,
3536 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003537 SC_None);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003538 IndexVariables.push_back(IterationVar);
3539
3540 // Create a reference to the iteration variable.
John McCalldadc5752010-08-24 06:29:42 +00003541 ExprResult IterationVarRef
Eli Friedman844f9452012-01-23 02:35:22 +00003542 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003543 assert(!IterationVarRef.isInvalid() &&
3544 "Reference to invented variable cannot fail!");
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003545 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.get());
Eli Friedman844f9452012-01-23 02:35:22 +00003546 assert(!IterationVarRef.isInvalid() &&
3547 "Conversion of invented variable cannot fail!");
Sebastian Redle9c4e842011-09-04 18:14:28 +00003548
Douglas Gregor94f9a482010-05-05 05:51:00 +00003549 // Subscript the array with this iteration variable.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003550 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.get(), Loc,
3551 IterationVarRef.get(),
Sebastian Redle9c4e842011-09-04 18:14:28 +00003552 Loc);
3553 if (CtorArg.isInvalid())
Douglas Gregor94f9a482010-05-05 05:51:00 +00003554 return true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00003555
Douglas Gregor94f9a482010-05-05 05:51:00 +00003556 BaseType = Array->getElementType();
3557 }
Sebastian Redl22653ba2011-08-30 19:58:05 +00003558
3559 // The array subscript expression is an lvalue, which is wrong for moving.
3560 if (Moving && InitializingArray)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003561 CtorArg = CastForMoving(SemaRef, CtorArg.get());
Sebastian Redl22653ba2011-08-30 19:58:05 +00003562
Douglas Gregor94f9a482010-05-05 05:51:00 +00003563 // Construct the entity that we will be initializing. For an array, this
3564 // will be first element in the array, which may require several levels
3565 // of array-subscript entities.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003566 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003567 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor493627b2011-08-10 15:22:55 +00003568 if (Indirect)
3569 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
3570 else
3571 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregor94f9a482010-05-05 05:51:00 +00003572 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
3573 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
3574 0,
3575 Entities.back()));
3576
3577 // Direct-initialize to use the copy constructor.
3578 InitializationKind InitKind =
3579 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
3580
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003581 Expr *CtorArgE = CtorArg.getAs<Expr>();
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003582 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, CtorArgE);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003583
John McCalldadc5752010-08-24 06:29:42 +00003584 ExprResult MemberInit
Douglas Gregor94f9a482010-05-05 05:51:00 +00003585 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redle9c4e842011-09-04 18:14:28 +00003586 MultiExprArg(&CtorArgE, 1));
Douglas Gregora40433a2010-12-07 00:41:46 +00003587 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003588 if (MemberInit.isInvalid())
3589 return true;
3590
Douglas Gregor493627b2011-08-10 15:22:55 +00003591 if (Indirect) {
3592 assert(IndexVariables.size() == 0 &&
3593 "Indirect field improperly initialized");
3594 CXXMemberInit
3595 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3596 Loc, Loc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003597 MemberInit.getAs<Expr>(),
Douglas Gregor493627b2011-08-10 15:22:55 +00003598 Loc);
3599 } else
3600 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003601 Loc, MemberInit.getAs<Expr>(),
Douglas Gregor493627b2011-08-10 15:22:55 +00003602 Loc,
3603 IndexVariables.data(),
3604 IndexVariables.size());
Anders Carlsson1b00e242010-04-23 03:10:23 +00003605 return false;
3606 }
3607
Richard Smithc2bc61b2013-03-18 21:12:30 +00003608 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
3609 "Unhandled implicit init kind!");
Anders Carlsson423f5d82010-04-23 16:04:08 +00003610
Anders Carlsson3c1db572010-04-23 02:15:47 +00003611 QualType FieldBaseElementType =
3612 SemaRef.Context.getBaseElementType(Field->getType());
3613
Anders Carlsson3c1db572010-04-23 02:15:47 +00003614 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor493627b2011-08-10 15:22:55 +00003615 InitializedEntity InitEntity
3616 = Indirect? InitializedEntity::InitializeMember(Indirect)
3617 : InitializedEntity::InitializeMember(Field);
Anders Carlsson423f5d82010-04-23 16:04:08 +00003618 InitializationKind InitKind =
Chandler Carruth9c9286b2010-06-29 23:50:44 +00003619 InitializationKind::CreateDefault(Loc);
Dmitri Gribenko78852e92013-05-05 20:40:26 +00003620
3621 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3622 ExprResult MemberInit =
3623 InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
John McCallb268a282010-08-23 23:25:46 +00003624
Douglas Gregora40433a2010-12-07 00:41:46 +00003625 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlsson3c1db572010-04-23 02:15:47 +00003626 if (MemberInit.isInvalid())
3627 return true;
3628
Douglas Gregor493627b2011-08-10 15:22:55 +00003629 if (Indirect)
3630 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3631 Indirect, Loc,
3632 Loc,
3633 MemberInit.get(),
3634 Loc);
3635 else
3636 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3637 Field, Loc, Loc,
3638 MemberInit.get(),
3639 Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00003640 return false;
3641 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003642
Alexis Hunt8b455182011-05-17 00:19:05 +00003643 if (!Field->getParent()->isUnion()) {
3644 if (FieldBaseElementType->isReferenceType()) {
3645 SemaRef.Diag(Constructor->getLocation(),
3646 diag::err_uninitialized_member_in_ctor)
3647 << (int)Constructor->isImplicit()
3648 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3649 << 0 << Field->getDeclName();
3650 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3651 return true;
3652 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003653
Alexis Hunt8b455182011-05-17 00:19:05 +00003654 if (FieldBaseElementType.isConstQualified()) {
3655 SemaRef.Diag(Constructor->getLocation(),
3656 diag::err_uninitialized_member_in_ctor)
3657 << (int)Constructor->isImplicit()
3658 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3659 << 1 << Field->getDeclName();
3660 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3661 return true;
3662 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003663 }
Anders Carlsson3c1db572010-04-23 02:15:47 +00003664
David Blaikiebbafb8a2012-03-11 07:00:24 +00003665 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00003666 FieldBaseElementType->isObjCRetainableType() &&
3667 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3668 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
Douglas Gregor6fa69422012-07-23 04:23:39 +00003669 // ARC:
John McCall31168b02011-06-15 23:02:42 +00003670 // Default-initialize Objective-C pointers to NULL.
3671 CXXMemberInit
3672 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3673 Loc, Loc,
3674 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3675 Loc);
3676 return false;
3677 }
3678
Anders Carlsson3c1db572010-04-23 02:15:47 +00003679 // Nothing to initialize.
Craig Topperc3ec1492014-05-26 06:22:03 +00003680 CXXMemberInit = nullptr;
Anders Carlsson3c1db572010-04-23 02:15:47 +00003681 return false;
3682}
John McCallbc83b3f2010-05-20 23:23:51 +00003683
3684namespace {
3685struct BaseAndFieldInfo {
3686 Sema &S;
3687 CXXConstructorDecl *Ctor;
3688 bool AnyErrorsInInits;
3689 ImplicitInitializerKind IIK;
Alexis Hunt1d792652011-01-08 20:30:50 +00003690 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003691 SmallVector<CXXCtorInitializer*, 8> AllToInit;
Richard Smithab44d5b2013-12-10 08:25:00 +00003692 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
John McCallbc83b3f2010-05-20 23:23:51 +00003693
3694 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3695 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003696 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3697 if (Generated && Ctor->isCopyConstructor())
John McCallbc83b3f2010-05-20 23:23:51 +00003698 IIK = IIK_Copy;
Sebastian Redl22653ba2011-08-30 19:58:05 +00003699 else if (Generated && Ctor->isMoveConstructor())
3700 IIK = IIK_Move;
Richard Smithc2bc61b2013-03-18 21:12:30 +00003701 else if (Ctor->getInheritedConstructor())
3702 IIK = IIK_Inherit;
John McCallbc83b3f2010-05-20 23:23:51 +00003703 else
3704 IIK = IIK_Default;
3705 }
Douglas Gregor7db3e952011-11-28 20:03:15 +00003706
3707 bool isImplicitCopyOrMove() const {
3708 switch (IIK) {
3709 case IIK_Copy:
3710 case IIK_Move:
3711 return true;
3712
3713 case IIK_Default:
Richard Smithc2bc61b2013-03-18 21:12:30 +00003714 case IIK_Inherit:
Douglas Gregor7db3e952011-11-28 20:03:15 +00003715 return false;
3716 }
David Blaikiee4d798f2012-01-20 21:50:17 +00003717
3718 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregor7db3e952011-11-28 20:03:15 +00003719 }
Richard Smith0a8cfc72012-08-07 21:30:42 +00003720
3721 bool addFieldInitializer(CXXCtorInitializer *Init) {
3722 AllToInit.push_back(Init);
3723
3724 // Check whether this initializer makes the field "used".
Richard Smith852c9db2013-04-20 22:23:05 +00003725 if (Init->getInit()->HasSideEffects(S.Context))
Richard Smith0a8cfc72012-08-07 21:30:42 +00003726 S.UnusedPrivateFields.remove(Init->getAnyMember());
3727
3728 return false;
3729 }
John McCallbc83b3f2010-05-20 23:23:51 +00003730
Richard Smithab44d5b2013-12-10 08:25:00 +00003731 bool isInactiveUnionMember(FieldDecl *Field) {
3732 RecordDecl *Record = Field->getParent();
3733 if (!Record->isUnion())
3734 return false;
3735
Richard Smith8d183852013-12-10 20:56:03 +00003736 if (FieldDecl *Active =
3737 ActiveUnionMember.lookup(Record->getCanonicalDecl()))
Richard Smithab44d5b2013-12-10 08:25:00 +00003738 return Active != Field->getCanonicalDecl();
3739
3740 // In an implicit copy or move constructor, ignore any in-class initializer.
3741 if (isImplicitCopyOrMove())
3742 return true;
3743
3744 // If there's no explicit initialization, the field is active only if it
3745 // has an in-class initializer...
3746 if (Field->hasInClassInitializer())
3747 return false;
3748 // ... or it's an anonymous struct or union whose class has an in-class
3749 // initializer.
3750 if (!Field->isAnonymousStructOrUnion())
3751 return true;
3752 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
3753 return !FieldRD->hasInClassInitializer();
3754 }
3755
3756 /// \brief Determine whether the given field is, or is within, a union member
3757 /// that is inactive (because there was an initializer given for a different
3758 /// member of the union, or because the union was not initialized at all).
3759 bool isWithinInactiveUnionMember(FieldDecl *Field,
3760 IndirectFieldDecl *Indirect) {
3761 if (!Indirect)
3762 return isInactiveUnionMember(Field);
3763
Aaron Ballman29c94602014-03-07 18:36:15 +00003764 for (auto *C : Indirect->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00003765 FieldDecl *Field = dyn_cast<FieldDecl>(C);
Richard Smithab44d5b2013-12-10 08:25:00 +00003766 if (Field && isInactiveUnionMember(Field))
Richard Smithc94ec842011-09-19 13:34:43 +00003767 return true;
Richard Smithab44d5b2013-12-10 08:25:00 +00003768 }
3769 return false;
3770 }
3771};
Richard Smithc94ec842011-09-19 13:34:43 +00003772}
3773
Douglas Gregor10f939c2011-11-02 23:04:16 +00003774/// \brief Determine whether the given type is an incomplete or zero-lenfgth
3775/// array type.
3776static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3777 if (T->isIncompleteArrayType())
3778 return true;
3779
3780 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3781 if (!ArrayT->getSize())
3782 return true;
3783
3784 T = ArrayT->getElementType();
3785 }
3786
3787 return false;
3788}
3789
Richard Smith938f40b2011-06-11 17:19:42 +00003790static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor493627b2011-08-10 15:22:55 +00003791 FieldDecl *Field,
Craig Topperc3ec1492014-05-26 06:22:03 +00003792 IndirectFieldDecl *Indirect = nullptr) {
Eli Friedmanb13e64e2013-06-28 21:07:41 +00003793 if (Field->isInvalidDecl())
3794 return false;
John McCallbc83b3f2010-05-20 23:23:51 +00003795
Chandler Carruth139e9622010-06-30 02:59:29 +00003796 // Overwhelmingly common case: we have a direct initializer for this field.
Richard Smithcd45dbc2014-04-19 03:48:30 +00003797 if (CXXCtorInitializer *Init =
3798 Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
Richard Smith0a8cfc72012-08-07 21:30:42 +00003799 return Info.addFieldInitializer(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00003800
Richard Smithab44d5b2013-12-10 08:25:00 +00003801 // C++11 [class.base.init]p8:
3802 // if the entity is a non-static data member that has a
3803 // brace-or-equal-initializer and either
3804 // -- the constructor's class is a union and no other variant member of that
3805 // union is designated by a mem-initializer-id or
3806 // -- the constructor's class is not a union, and, if the entity is a member
3807 // of an anonymous union, no other member of that union is designated by
3808 // a mem-initializer-id,
3809 // the entity is initialized as specified in [dcl.init].
3810 //
3811 // We also apply the same rules to handle anonymous structs within anonymous
3812 // unions.
3813 if (Info.isWithinInactiveUnionMember(Field, Indirect))
3814 return false;
3815
Douglas Gregor7db3e952011-11-28 20:03:15 +00003816 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Reid Klecknerd60b82f2014-11-17 23:36:45 +00003817 ExprResult DIE =
3818 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
3819 if (DIE.isInvalid())
3820 return true;
Douglas Gregor493627b2011-08-10 15:22:55 +00003821 CXXCtorInitializer *Init;
3822 if (Indirect)
Reid Klecknerd60b82f2014-11-17 23:36:45 +00003823 Init = new (SemaRef.Context)
3824 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
3825 SourceLocation(), DIE.get(), SourceLocation());
Douglas Gregor493627b2011-08-10 15:22:55 +00003826 else
Reid Klecknerd60b82f2014-11-17 23:36:45 +00003827 Init = new (SemaRef.Context)
3828 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
3829 SourceLocation(), DIE.get(), SourceLocation());
Richard Smith0a8cfc72012-08-07 21:30:42 +00003830 return Info.addFieldInitializer(Init);
Richard Smith938f40b2011-06-11 17:19:42 +00003831 }
3832
Douglas Gregor10f939c2011-11-02 23:04:16 +00003833 // Don't initialize incomplete or zero-length arrays.
3834 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3835 return false;
3836
John McCallbc83b3f2010-05-20 23:23:51 +00003837 // Don't try to build an implicit initializer if there were semantic
3838 // errors in any of the initializers (and therefore we might be
3839 // missing some that the user actually wrote).
Eli Friedmanb13e64e2013-06-28 21:07:41 +00003840 if (Info.AnyErrorsInInits)
John McCallbc83b3f2010-05-20 23:23:51 +00003841 return false;
3842
Craig Topperc3ec1492014-05-26 06:22:03 +00003843 CXXCtorInitializer *Init = nullptr;
Douglas Gregor493627b2011-08-10 15:22:55 +00003844 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3845 Indirect, Init))
John McCallbc83b3f2010-05-20 23:23:51 +00003846 return true;
John McCallbc83b3f2010-05-20 23:23:51 +00003847
Richard Smith0a8cfc72012-08-07 21:30:42 +00003848 if (!Init)
3849 return false;
Francois Pichetd583da02010-12-04 09:14:42 +00003850
Richard Smith0a8cfc72012-08-07 21:30:42 +00003851 return Info.addFieldInitializer(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00003852}
Alexis Hunt61bc1732011-05-01 07:04:31 +00003853
3854bool
3855Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3856 CXXCtorInitializer *Initializer) {
Alexis Hunt6118d662011-05-04 05:57:24 +00003857 assert(Initializer->isDelegatingInitializer());
Alexis Hunt5583d562011-05-03 20:43:02 +00003858 Constructor->setNumCtorInitializers(1);
3859 CXXCtorInitializer **initializer =
3860 new (Context) CXXCtorInitializer*[1];
3861 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3862 Constructor->setCtorInitializers(initializer);
3863
Alexis Hunt9d47faf2011-05-03 23:05:34 +00003864 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00003865 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Alexis Hunt9d47faf2011-05-03 23:05:34 +00003866 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3867 }
3868
Alexis Hunte2622992011-05-05 00:05:47 +00003869 DelegatingCtorDecls.push_back(Constructor);
Alexis Hunt6118d662011-05-04 05:57:24 +00003870
Richard Trieu8a0c9e62014-09-12 22:47:58 +00003871 DiagnoseUninitializedFields(*this, Constructor);
3872
Alexis Hunt61bc1732011-05-01 07:04:31 +00003873 return false;
3874}
Douglas Gregor493627b2011-08-10 15:22:55 +00003875
David Blaikie3fc2f912013-01-17 05:26:25 +00003876bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3877 ArrayRef<CXXCtorInitializer *> Initializers) {
Douglas Gregor52235292011-09-22 23:04:35 +00003878 if (Constructor->isDependentContext()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003879 // Just store the initializers as written, they will be checked during
3880 // instantiation.
David Blaikie3fc2f912013-01-17 05:26:25 +00003881 if (!Initializers.empty()) {
3882 Constructor->setNumCtorInitializers(Initializers.size());
Alexis Hunt1d792652011-01-08 20:30:50 +00003883 CXXCtorInitializer **baseOrMemberInitializers =
David Blaikie3fc2f912013-01-17 05:26:25 +00003884 new (Context) CXXCtorInitializer*[Initializers.size()];
3885 memcpy(baseOrMemberInitializers, Initializers.data(),
3886 Initializers.size() * sizeof(CXXCtorInitializer*));
Alexis Hunt1d792652011-01-08 20:30:50 +00003887 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssondb0a9652010-04-02 06:26:44 +00003888 }
Richard Smith60f2e1e2012-09-25 00:23:05 +00003889
3890 // Let template instantiation know whether we had errors.
3891 if (AnyErrors)
3892 Constructor->setInvalidDecl();
3893
Anders Carlssondb0a9652010-04-02 06:26:44 +00003894 return false;
3895 }
3896
John McCallbc83b3f2010-05-20 23:23:51 +00003897 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlsson1b00e242010-04-23 03:10:23 +00003898
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003899 // We need to build the initializer AST according to order of construction
3900 // and not what user specified in the Initializers list.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003901 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregorc14922f2010-03-26 22:43:07 +00003902 if (!ClassDecl)
3903 return true;
3904
Eli Friedman9cf6b592009-11-09 19:20:36 +00003905 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00003906
David Blaikie3fc2f912013-01-17 05:26:25 +00003907 for (unsigned i = 0; i < Initializers.size(); i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003908 CXXCtorInitializer *Member = Initializers[i];
Richard Smithbc46e432013-07-22 02:56:56 +00003909
Anders Carlssondb0a9652010-04-02 06:26:44 +00003910 if (Member->isBaseInitializer())
John McCallbc83b3f2010-05-20 23:23:51 +00003911 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Richard Smithab44d5b2013-12-10 08:25:00 +00003912 else {
Richard Smithcd45dbc2014-04-19 03:48:30 +00003913 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
Richard Smithab44d5b2013-12-10 08:25:00 +00003914
3915 if (IndirectFieldDecl *F = Member->getIndirectMember()) {
Aaron Ballman29c94602014-03-07 18:36:15 +00003916 for (auto *C : F->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00003917 FieldDecl *FD = dyn_cast<FieldDecl>(C);
Richard Smithab44d5b2013-12-10 08:25:00 +00003918 if (FD && FD->getParent()->isUnion())
3919 Info.ActiveUnionMember.insert(std::make_pair(
3920 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3921 }
3922 } else if (FieldDecl *FD = Member->getMember()) {
3923 if (FD->getParent()->isUnion())
3924 Info.ActiveUnionMember.insert(std::make_pair(
3925 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3926 }
3927 }
Anders Carlssondb0a9652010-04-02 06:26:44 +00003928 }
3929
Anders Carlsson43c64af2010-04-21 19:52:01 +00003930 // Keep track of the direct virtual bases.
3931 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
Aaron Ballman574705e2014-03-13 15:41:46 +00003932 for (auto &I : ClassDecl->bases()) {
3933 if (I.isVirtual())
3934 DirectVBases.insert(&I);
Anders Carlsson43c64af2010-04-21 19:52:01 +00003935 }
3936
Anders Carlssondb0a9652010-04-02 06:26:44 +00003937 // Push virtual bases before others.
Aaron Ballman445a9392014-03-13 16:15:17 +00003938 for (auto &VBase : ClassDecl->vbases()) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003939 if (CXXCtorInitializer *Value
Aaron Ballman445a9392014-03-13 16:15:17 +00003940 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
Richard Smithbc46e432013-07-22 02:56:56 +00003941 // [class.base.init]p7, per DR257:
3942 // A mem-initializer where the mem-initializer-id names a virtual base
3943 // class is ignored during execution of a constructor of any class that
3944 // is not the most derived class.
3945 if (ClassDecl->isAbstract()) {
3946 // FIXME: Provide a fixit to remove the base specifier. This requires
3947 // tracking the location of the associated comma for a base specifier.
3948 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
Aaron Ballman445a9392014-03-13 16:15:17 +00003949 << VBase.getType() << ClassDecl;
Richard Smithbc46e432013-07-22 02:56:56 +00003950 DiagnoseAbstractType(ClassDecl);
3951 }
3952
John McCallbc83b3f2010-05-20 23:23:51 +00003953 Info.AllToInit.push_back(Value);
Richard Smithbc46e432013-07-22 02:56:56 +00003954 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
3955 // [class.base.init]p8, per DR257:
3956 // If a given [...] base class is not named by a mem-initializer-id
3957 // [...] and the entity is not a virtual base class of an abstract
3958 // class, then [...] the entity is default-initialized.
Aaron Ballman445a9392014-03-13 16:15:17 +00003959 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
Alexis Hunt1d792652011-01-08 20:30:50 +00003960 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00003961 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Aaron Ballman445a9392014-03-13 16:15:17 +00003962 &VBase, IsInheritedVirtualBase,
Anders Carlsson1b00e242010-04-23 03:10:23 +00003963 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003964 HadError = true;
3965 continue;
3966 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003967
John McCallbc83b3f2010-05-20 23:23:51 +00003968 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003969 }
3970 }
Mike Stump11289f42009-09-09 15:08:12 +00003971
John McCallbc83b3f2010-05-20 23:23:51 +00003972 // Non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00003973 for (auto &Base : ClassDecl->bases()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003974 // Virtuals are in the virtual base list and already constructed.
Aaron Ballman574705e2014-03-13 15:41:46 +00003975 if (Base.isVirtual())
Anders Carlssondb0a9652010-04-02 06:26:44 +00003976 continue;
Mike Stump11289f42009-09-09 15:08:12 +00003977
Alexis Hunt1d792652011-01-08 20:30:50 +00003978 if (CXXCtorInitializer *Value
Aaron Ballman574705e2014-03-13 15:41:46 +00003979 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
John McCallbc83b3f2010-05-20 23:23:51 +00003980 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00003981 } else if (!AnyErrors) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003982 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00003983 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Aaron Ballman574705e2014-03-13 15:41:46 +00003984 &Base, /*IsInheritedVirtualBase=*/false,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003985 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003986 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003987 continue;
Anders Carlssondb0a9652010-04-02 06:26:44 +00003988 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00003989
John McCallbc83b3f2010-05-20 23:23:51 +00003990 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003991 }
3992 }
Mike Stump11289f42009-09-09 15:08:12 +00003993
John McCallbc83b3f2010-05-20 23:23:51 +00003994 // Fields.
Aaron Ballman629afae2014-03-07 19:56:05 +00003995 for (auto *Mem : ClassDecl->decls()) {
3996 if (auto *F = dyn_cast<FieldDecl>(Mem)) {
Douglas Gregor556e5862011-10-10 17:22:13 +00003997 // C++ [class.bit]p2:
3998 // A declaration for a bit-field that omits the identifier declares an
3999 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
4000 // initialized.
4001 if (F->isUnnamedBitfield())
4002 continue;
Douglas Gregor10f939c2011-11-02 23:04:16 +00004003
Sebastian Redl22653ba2011-08-30 19:58:05 +00004004 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor493627b2011-08-10 15:22:55 +00004005 // handle anonymous struct/union fields based on their individual
4006 // indirect fields.
Richard Smithc2bc61b2013-03-18 21:12:30 +00004007 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
Douglas Gregor493627b2011-08-10 15:22:55 +00004008 continue;
4009
4010 if (CollectFieldInitializer(*this, Info, F))
4011 HadError = true;
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00004012 continue;
4013 }
Douglas Gregor493627b2011-08-10 15:22:55 +00004014
4015 // Beyond this point, we only consider default initialization.
Richard Smithc2bc61b2013-03-18 21:12:30 +00004016 if (Info.isImplicitCopyOrMove())
Douglas Gregor493627b2011-08-10 15:22:55 +00004017 continue;
4018
Aaron Ballman629afae2014-03-07 19:56:05 +00004019 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
Douglas Gregor493627b2011-08-10 15:22:55 +00004020 if (F->getType()->isIncompleteArrayType()) {
4021 assert(ClassDecl->hasFlexibleArrayMember() &&
4022 "Incomplete array type is not valid");
4023 continue;
4024 }
4025
Douglas Gregor493627b2011-08-10 15:22:55 +00004026 // Initialize each field of an anonymous struct individually.
4027 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
4028 HadError = true;
4029
4030 continue;
4031 }
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00004032 }
Mike Stump11289f42009-09-09 15:08:12 +00004033
David Blaikie3fc2f912013-01-17 05:26:25 +00004034 unsigned NumInitializers = Info.AllToInit.size();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00004035 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004036 Constructor->setNumCtorInitializers(NumInitializers);
4037 CXXCtorInitializer **baseOrMemberInitializers =
4038 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallbc83b3f2010-05-20 23:23:51 +00004039 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Alexis Hunt1d792652011-01-08 20:30:50 +00004040 NumInitializers * sizeof(CXXCtorInitializer*));
4041 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola13327bb2010-03-13 18:12:56 +00004042
John McCalla6309952010-03-16 21:39:52 +00004043 // Constructors implicitly reference the base and member
4044 // destructors.
4045 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
4046 Constructor->getParent());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00004047 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00004048
4049 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00004050}
4051
David Blaikieb61b8152013-01-17 08:49:22 +00004052static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004053 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
David Blaikieb61b8152013-01-17 08:49:22 +00004054 const RecordDecl *RD = RT->getDecl();
4055 if (RD->isAnonymousStructOrUnion()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004056 for (auto *Field : RD->fields())
4057 PopulateKeysForFields(Field, IdealInits);
David Blaikieb61b8152013-01-17 08:49:22 +00004058 return;
4059 }
Eli Friedman952c15d2009-07-21 19:28:10 +00004060 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00004061 IdealInits.push_back(Field->getCanonicalDecl());
Eli Friedman952c15d2009-07-21 19:28:10 +00004062}
4063
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004064static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
4065 return Context.getCanonicalType(BaseType).getTypePtr();
Anders Carlssonbcec05c2009-09-01 06:22:14 +00004066}
4067
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004068static const void *GetKeyForMember(ASTContext &Context,
4069 CXXCtorInitializer *Member) {
Francois Pichetd583da02010-12-04 09:14:42 +00004070 if (!Member->isAnyMemberInitializer())
Anders Carlsson7b3f2782010-04-02 05:42:15 +00004071 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlssona942dcd2010-03-30 15:39:27 +00004072
Richard Smithcd45dbc2014-04-19 03:48:30 +00004073 return Member->getAnyMember()->getCanonicalDecl();
Eli Friedman952c15d2009-07-21 19:28:10 +00004074}
4075
David Blaikie3fc2f912013-01-17 05:26:25 +00004076static void DiagnoseBaseOrMemInitializerOrder(
4077 Sema &SemaRef, const CXXConstructorDecl *Constructor,
4078 ArrayRef<CXXCtorInitializer *> Inits) {
John McCallbb7b6582010-04-10 07:37:23 +00004079 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00004080 return;
Mike Stump11289f42009-09-09 15:08:12 +00004081
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00004082 // Don't check initializers order unless the warning is enabled at the
4083 // location of at least one initializer.
4084 bool ShouldCheckOrder = false;
David Blaikie3fc2f912013-01-17 05:26:25 +00004085 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004086 CXXCtorInitializer *Init = Inits[InitIndex];
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00004087 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
4088 Init->getSourceLocation())) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00004089 ShouldCheckOrder = true;
4090 break;
4091 }
4092 }
4093 if (!ShouldCheckOrder)
Anders Carlssone0eebb32009-08-27 05:45:01 +00004094 return;
Anders Carlssone857b292010-04-02 03:37:03 +00004095
John McCallbb7b6582010-04-10 07:37:23 +00004096 // Build the list of bases and members in the order that they'll
4097 // actually be initialized. The explicit initializers should be in
4098 // this same order but may be missing things.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004099 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump11289f42009-09-09 15:08:12 +00004100
Anders Carlsson96b8fc62010-04-02 03:38:04 +00004101 const CXXRecordDecl *ClassDecl = Constructor->getParent();
4102
John McCallbb7b6582010-04-10 07:37:23 +00004103 // 1. Virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +00004104 for (const auto &VBase : ClassDecl->vbases())
4105 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
Mike Stump11289f42009-09-09 15:08:12 +00004106
John McCallbb7b6582010-04-10 07:37:23 +00004107 // 2. Non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00004108 for (const auto &Base : ClassDecl->bases()) {
4109 if (Base.isVirtual())
Anders Carlssone0eebb32009-08-27 05:45:01 +00004110 continue;
Aaron Ballman574705e2014-03-13 15:41:46 +00004111 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00004112 }
Mike Stump11289f42009-09-09 15:08:12 +00004113
John McCallbb7b6582010-04-10 07:37:23 +00004114 // 3. Direct fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004115 for (auto *Field : ClassDecl->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +00004116 if (Field->isUnnamedBitfield())
4117 continue;
4118
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004119 PopulateKeysForFields(Field, IdealInitKeys);
Douglas Gregor556e5862011-10-10 17:22:13 +00004120 }
4121
John McCallbb7b6582010-04-10 07:37:23 +00004122 unsigned NumIdealInits = IdealInitKeys.size();
4123 unsigned IdealIndex = 0;
Eli Friedman952c15d2009-07-21 19:28:10 +00004124
Craig Topperc3ec1492014-05-26 06:22:03 +00004125 CXXCtorInitializer *PrevInit = nullptr;
David Blaikie3fc2f912013-01-17 05:26:25 +00004126 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004127 CXXCtorInitializer *Init = Inits[InitIndex];
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004128 const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCallbb7b6582010-04-10 07:37:23 +00004129
4130 // Scan forward to try to find this initializer in the idealized
4131 // initializers list.
4132 for (; IdealIndex != NumIdealInits; ++IdealIndex)
4133 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00004134 break;
John McCallbb7b6582010-04-10 07:37:23 +00004135
4136 // If we didn't find this initializer, it must be because we
4137 // scanned past it on a previous iteration. That can only
4138 // happen if we're out of order; emit a warning.
Douglas Gregoraabdfcb2010-05-20 23:49:34 +00004139 if (IdealIndex == NumIdealInits && PrevInit) {
John McCallbb7b6582010-04-10 07:37:23 +00004140 Sema::SemaDiagnosticBuilder D =
4141 SemaRef.Diag(PrevInit->getSourceLocation(),
4142 diag::warn_initializer_out_of_order);
4143
Francois Pichetd583da02010-12-04 09:14:42 +00004144 if (PrevInit->isAnyMemberInitializer())
4145 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00004146 else
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004147 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCallbb7b6582010-04-10 07:37:23 +00004148
Francois Pichetd583da02010-12-04 09:14:42 +00004149 if (Init->isAnyMemberInitializer())
4150 D << 0 << Init->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00004151 else
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004152 D << 1 << Init->getTypeSourceInfo()->getType();
John McCallbb7b6582010-04-10 07:37:23 +00004153
4154 // Move back to the initializer's location in the ideal list.
4155 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
4156 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00004157 break;
John McCallbb7b6582010-04-10 07:37:23 +00004158
4159 assert(IdealIndex != NumIdealInits &&
4160 "initializer not found in initializer list");
Fariborz Jahanian341583c2009-07-09 19:59:47 +00004161 }
John McCallbb7b6582010-04-10 07:37:23 +00004162
4163 PrevInit = Init;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00004164 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00004165}
4166
John McCall23eebd92010-04-10 09:28:51 +00004167namespace {
4168bool CheckRedundantInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00004169 CXXCtorInitializer *Init,
4170 CXXCtorInitializer *&PrevInit) {
John McCall23eebd92010-04-10 09:28:51 +00004171 if (!PrevInit) {
4172 PrevInit = Init;
4173 return false;
4174 }
4175
Douglas Gregorea306a12013-03-25 23:28:23 +00004176 if (FieldDecl *Field = Init->getAnyMember())
John McCall23eebd92010-04-10 09:28:51 +00004177 S.Diag(Init->getSourceLocation(),
4178 diag::err_multiple_mem_initialization)
4179 << Field->getDeclName()
4180 << Init->getSourceRange();
4181 else {
John McCall424cec92011-01-19 06:33:43 +00004182 const Type *BaseClass = Init->getBaseClass();
John McCall23eebd92010-04-10 09:28:51 +00004183 assert(BaseClass && "neither field nor base");
4184 S.Diag(Init->getSourceLocation(),
4185 diag::err_multiple_base_initialization)
4186 << QualType(BaseClass, 0)
4187 << Init->getSourceRange();
4188 }
4189 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
4190 << 0 << PrevInit->getSourceRange();
4191
4192 return true;
4193}
4194
Alexis Hunt1d792652011-01-08 20:30:50 +00004195typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall23eebd92010-04-10 09:28:51 +00004196typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
4197
4198bool CheckRedundantUnionInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00004199 CXXCtorInitializer *Init,
John McCall23eebd92010-04-10 09:28:51 +00004200 RedundantUnionMap &Unions) {
Francois Pichetd583da02010-12-04 09:14:42 +00004201 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00004202 RecordDecl *Parent = Field->getParent();
John McCall23eebd92010-04-10 09:28:51 +00004203 NamedDecl *Child = Field;
David Blaikie0f65d592011-11-17 06:01:57 +00004204
4205 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall23eebd92010-04-10 09:28:51 +00004206 if (Parent->isUnion()) {
4207 UnionEntry &En = Unions[Parent];
4208 if (En.first && En.first != Child) {
4209 S.Diag(Init->getSourceLocation(),
4210 diag::err_multiple_mem_union_initialization)
4211 << Field->getDeclName()
4212 << Init->getSourceRange();
4213 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
4214 << 0 << En.second->getSourceRange();
4215 return true;
David Blaikie256ee192011-11-12 20:54:14 +00004216 }
4217 if (!En.first) {
John McCall23eebd92010-04-10 09:28:51 +00004218 En.first = Child;
4219 En.second = Init;
4220 }
David Blaikie0f65d592011-11-17 06:01:57 +00004221 if (!Parent->isAnonymousStructOrUnion())
4222 return false;
John McCall23eebd92010-04-10 09:28:51 +00004223 }
4224
4225 Child = Parent;
4226 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie0f65d592011-11-17 06:01:57 +00004227 }
John McCall23eebd92010-04-10 09:28:51 +00004228
4229 return false;
4230}
4231}
4232
Anders Carlssone857b292010-04-02 03:37:03 +00004233/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCall48871652010-08-21 09:40:31 +00004234void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlssone857b292010-04-02 03:37:03 +00004235 SourceLocation ColonLoc,
David Blaikie3fc2f912013-01-17 05:26:25 +00004236 ArrayRef<CXXCtorInitializer*> MemInits,
Anders Carlssone857b292010-04-02 03:37:03 +00004237 bool AnyErrors) {
4238 if (!ConstructorDecl)
4239 return;
4240
4241 AdjustDeclIfTemplate(ConstructorDecl);
4242
4243 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00004244 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlssone857b292010-04-02 03:37:03 +00004245
4246 if (!Constructor) {
4247 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
4248 return;
4249 }
4250
John McCall23eebd92010-04-10 09:28:51 +00004251 // Mapping for the duplicate initializers check.
4252 // For member initializers, this is keyed with a FieldDecl*.
4253 // For base initializers, this is keyed with a Type*.
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004254 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
John McCall23eebd92010-04-10 09:28:51 +00004255
4256 // Mapping for the inconsistent anonymous-union initializers check.
4257 RedundantUnionMap MemberUnions;
4258
Anders Carlsson7b3f2782010-04-02 05:42:15 +00004259 bool HadError = false;
David Blaikie3fc2f912013-01-17 05:26:25 +00004260 for (unsigned i = 0; i < MemInits.size(); i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004261 CXXCtorInitializer *Init = MemInits[i];
Anders Carlssone857b292010-04-02 03:37:03 +00004262
Abramo Bagnara341d7832010-05-26 18:09:23 +00004263 // Set the source order index.
4264 Init->setSourceOrder(i);
4265
Francois Pichetd583da02010-12-04 09:14:42 +00004266 if (Init->isAnyMemberInitializer()) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00004267 const void *Key = GetKeyForMember(Context, Init);
4268 if (CheckRedundantInit(*this, Init, Members[Key]) ||
John McCall23eebd92010-04-10 09:28:51 +00004269 CheckRedundantUnionInit(*this, Init, MemberUnions))
4270 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00004271 } else if (Init->isBaseInitializer()) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00004272 const void *Key = GetKeyForMember(Context, Init);
John McCall23eebd92010-04-10 09:28:51 +00004273 if (CheckRedundantInit(*this, Init, Members[Key]))
4274 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00004275 } else {
4276 assert(Init->isDelegatingInitializer());
4277 // This must be the only initializer
David Blaikie3fc2f912013-01-17 05:26:25 +00004278 if (MemInits.size() != 1) {
Richard Smith21f06f02012-09-14 18:21:10 +00004279 Diag(Init->getSourceLocation(),
Alexis Huntc5575cc2011-02-26 19:13:13 +00004280 diag::err_delegating_initializer_alone)
Richard Smith21f06f02012-09-14 18:21:10 +00004281 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
Alexis Hunt61bc1732011-05-01 07:04:31 +00004282 // We will treat this as being the only initializer.
Alexis Huntc5575cc2011-02-26 19:13:13 +00004283 }
Alexis Hunt6118d662011-05-04 05:57:24 +00004284 SetDelegatingInitializer(Constructor, MemInits[i]);
Alexis Hunt61bc1732011-05-01 07:04:31 +00004285 // Return immediately as the initializer is set.
4286 return;
Anders Carlssone857b292010-04-02 03:37:03 +00004287 }
Anders Carlssone857b292010-04-02 03:37:03 +00004288 }
4289
Anders Carlsson7b3f2782010-04-02 05:42:15 +00004290 if (HadError)
4291 return;
4292
David Blaikie3fc2f912013-01-17 05:26:25 +00004293 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
Anders Carlsson4c8cb012010-04-02 03:43:34 +00004294
David Blaikie3fc2f912013-01-17 05:26:25 +00004295 SetCtorInitializers(Constructor, AnyErrors, MemInits);
Richard Trieu3a446ff2013-09-16 21:54:53 +00004296
Richard Trieuef64e942013-10-25 00:56:00 +00004297 DiagnoseUninitializedFields(*this, Constructor);
Anders Carlssone857b292010-04-02 03:37:03 +00004298}
4299
Fariborz Jahanian37d06562009-09-03 23:18:17 +00004300void
John McCalla6309952010-03-16 21:39:52 +00004301Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
4302 CXXRecordDecl *ClassDecl) {
Richard Smith20104042011-09-18 12:11:43 +00004303 // Ignore dependent contexts. Also ignore unions, since their members never
4304 // have destructors implicitly called.
4305 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlssondee9a302009-11-17 04:44:12 +00004306 return;
John McCall1064d7e2010-03-16 05:22:47 +00004307
4308 // FIXME: all the access-control diagnostics are positioned on the
4309 // field/base declaration. That's probably good; that said, the
4310 // user might reasonably want to know why the destructor is being
4311 // emitted, and we currently don't say.
Anders Carlssondee9a302009-11-17 04:44:12 +00004312
Anders Carlssondee9a302009-11-17 04:44:12 +00004313 // Non-static data members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004314 for (auto *Field : ClassDecl->fields()) {
Fariborz Jahanian16f94c62010-05-17 18:15:18 +00004315 if (Field->isInvalidDecl())
4316 continue;
Douglas Gregor10f939c2011-11-02 23:04:16 +00004317
4318 // Don't destroy incomplete or zero-length arrays.
4319 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
4320 continue;
4321
Anders Carlssondee9a302009-11-17 04:44:12 +00004322 QualType FieldType = Context.getBaseElementType(Field->getType());
4323
4324 const RecordType* RT = FieldType->getAs<RecordType>();
4325 if (!RT)
4326 continue;
4327
4328 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004329 if (FieldClassDecl->isInvalidDecl())
4330 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00004331 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlssondee9a302009-11-17 04:44:12 +00004332 continue;
Richard Smith921bd202012-02-26 09:11:52 +00004333 // The destructor for an implicit anonymous union member is never invoked.
4334 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
4335 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00004336
Douglas Gregore71edda2010-07-01 22:47:18 +00004337 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004338 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00004339 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00004340 PDiag(diag::err_access_dtor_field)
John McCall1064d7e2010-03-16 05:22:47 +00004341 << Field->getDeclName()
4342 << FieldType);
4343
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004344 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00004345 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlssondee9a302009-11-17 04:44:12 +00004346 }
4347
John McCall1064d7e2010-03-16 05:22:47 +00004348 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
4349
Anders Carlssondee9a302009-11-17 04:44:12 +00004350 // Bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00004351 for (const auto &Base : ClassDecl->bases()) {
John McCall1064d7e2010-03-16 05:22:47 +00004352 // Bases are always records in a well-formed non-dependent class.
Aaron Ballman574705e2014-03-13 15:41:46 +00004353 const RecordType *RT = Base.getType()->getAs<RecordType>();
John McCall1064d7e2010-03-16 05:22:47 +00004354
4355 // Remember direct virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00004356 if (Base.isVirtual())
John McCall1064d7e2010-03-16 05:22:47 +00004357 DirectVirtualBases.insert(RT);
Anders Carlssondee9a302009-11-17 04:44:12 +00004358
John McCall1064d7e2010-03-16 05:22:47 +00004359 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004360 // If our base class is invalid, we probably can't get its dtor anyway.
4361 if (BaseClassDecl->isInvalidDecl())
4362 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00004363 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlssondee9a302009-11-17 04:44:12 +00004364 continue;
John McCall1064d7e2010-03-16 05:22:47 +00004365
Douglas Gregore71edda2010-07-01 22:47:18 +00004366 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004367 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00004368
4369 // FIXME: caret should be on the start of the class name
Aaron Ballman574705e2014-03-13 15:41:46 +00004370 CheckDestructorAccess(Base.getLocStart(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00004371 PDiag(diag::err_access_dtor_base)
Aaron Ballman574705e2014-03-13 15:41:46 +00004372 << Base.getType()
4373 << Base.getSourceRange(),
John McCall5dadb652012-04-07 03:04:20 +00004374 Context.getTypeDeclType(ClassDecl));
Anders Carlssondee9a302009-11-17 04:44:12 +00004375
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004376 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00004377 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlssondee9a302009-11-17 04:44:12 +00004378 }
4379
4380 // Virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +00004381 for (const auto &VBase : ClassDecl->vbases()) {
John McCall1064d7e2010-03-16 05:22:47 +00004382 // Bases are always records in a well-formed non-dependent class.
Aaron Ballman445a9392014-03-13 16:15:17 +00004383 const RecordType *RT = VBase.getType()->castAs<RecordType>();
John McCall1064d7e2010-03-16 05:22:47 +00004384
4385 // Ignore direct virtual bases.
4386 if (DirectVirtualBases.count(RT))
4387 continue;
4388
John McCall1064d7e2010-03-16 05:22:47 +00004389 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004390 // If our base class is invalid, we probably can't get its dtor anyway.
4391 if (BaseClassDecl->isInvalidDecl())
4392 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00004393 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian37d06562009-09-03 23:18:17 +00004394 continue;
John McCall1064d7e2010-03-16 05:22:47 +00004395
Douglas Gregore71edda2010-07-01 22:47:18 +00004396 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004397 assert(Dtor && "No dtor found for BaseClassDecl!");
David Majnemer626032f2013-06-22 06:43:58 +00004398 if (CheckDestructorAccess(
4399 ClassDecl->getLocation(), Dtor,
4400 PDiag(diag::err_access_dtor_vbase)
Aaron Ballman445a9392014-03-13 16:15:17 +00004401 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
David Majnemer626032f2013-06-22 06:43:58 +00004402 Context.getTypeDeclType(ClassDecl)) ==
4403 AR_accessible) {
4404 CheckDerivedToBaseConversion(
Aaron Ballman445a9392014-03-13 16:15:17 +00004405 Context.getTypeDeclType(ClassDecl), VBase.getType(),
David Majnemer626032f2013-06-22 06:43:58 +00004406 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00004407 SourceRange(), DeclarationName(), nullptr);
David Majnemer626032f2013-06-22 06:43:58 +00004408 }
John McCall1064d7e2010-03-16 05:22:47 +00004409
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004410 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00004411 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian37d06562009-09-03 23:18:17 +00004412 }
4413}
4414
John McCall48871652010-08-21 09:40:31 +00004415void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00004416 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00004417 return;
Mike Stump11289f42009-09-09 15:08:12 +00004418
Mike Stump11289f42009-09-09 15:08:12 +00004419 if (CXXConstructorDecl *Constructor
Richard Trieuef64e942013-10-25 00:56:00 +00004420 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
David Blaikie3fc2f912013-01-17 05:26:25 +00004421 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
Richard Trieuef64e942013-10-25 00:56:00 +00004422 DiagnoseUninitializedFields(*this, Constructor);
4423 }
Fariborz Jahanian49c81792009-07-14 18:24:21 +00004424}
4425
Mike Stump11289f42009-09-09 15:08:12 +00004426bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00004427 unsigned DiagID, AbstractDiagSelID SelID) {
Douglas Gregorae298422012-05-04 17:09:59 +00004428 class NonAbstractTypeDiagnoser : public TypeDiagnoser {
4429 unsigned DiagID;
4430 AbstractDiagSelID SelID;
4431
4432 public:
4433 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
4434 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004435
Craig Toppera798a9d2014-03-02 09:32:10 +00004436 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00004437 if (Suppressed) return;
Douglas Gregorae298422012-05-04 17:09:59 +00004438 if (SelID == -1)
4439 S.Diag(Loc, DiagID) << T;
4440 else
4441 S.Diag(Loc, DiagID) << SelID << T;
4442 }
4443 } Diagnoser(DiagID, SelID);
4444
4445 return RequireNonAbstractType(Loc, T, Diagnoser);
Mike Stump11289f42009-09-09 15:08:12 +00004446}
4447
Anders Carlssoneabf7702009-08-27 00:13:57 +00004448bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Douglas Gregorae298422012-05-04 17:09:59 +00004449 TypeDiagnoser &Diagnoser) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00004450 if (!getLangOpts().CPlusPlus)
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004451 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004452
Anders Carlssoneb0c5322009-03-23 19:10:31 +00004453 if (const ArrayType *AT = Context.getAsArrayType(T))
Douglas Gregorae298422012-05-04 17:09:59 +00004454 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Mike Stump11289f42009-09-09 15:08:12 +00004455
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004456 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004457 // Find the innermost pointer type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004458 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004459 PT = T;
Mike Stump11289f42009-09-09 15:08:12 +00004460
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004461 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Douglas Gregorae298422012-05-04 17:09:59 +00004462 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004463 }
Mike Stump11289f42009-09-09 15:08:12 +00004464
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004465 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004466 if (!RT)
4467 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004468
John McCall67da35c2010-02-04 22:26:26 +00004469 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004470
John McCall02db245d2010-08-18 09:41:07 +00004471 // We can't answer whether something is abstract until it has a
4472 // definition. If it's currently being defined, we'll walk back
4473 // over all the declarations when we have a full definition.
4474 const CXXRecordDecl *Def = RD->getDefinition();
4475 if (!Def || Def->isBeingDefined())
John McCall67da35c2010-02-04 22:26:26 +00004476 return false;
4477
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004478 if (!RD->isAbstract())
4479 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004480
Douglas Gregorae298422012-05-04 17:09:59 +00004481 Diagnoser.diagnose(*this, Loc, T);
John McCall02db245d2010-08-18 09:41:07 +00004482 DiagnoseAbstractType(RD);
Mike Stump11289f42009-09-09 15:08:12 +00004483
John McCall02db245d2010-08-18 09:41:07 +00004484 return true;
4485}
4486
4487void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
4488 // Check if we've already emitted the list of pure virtual functions
4489 // for this class.
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004490 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall02db245d2010-08-18 09:41:07 +00004491 return;
Mike Stump11289f42009-09-09 15:08:12 +00004492
Richard Smithbc46e432013-07-22 02:56:56 +00004493 // If the diagnostic is suppressed, don't emit the notes. We're only
4494 // going to emit them once, so try to attach them to a diagnostic we're
4495 // actually going to show.
4496 if (Diags.isLastDiagnosticIgnored())
4497 return;
4498
Douglas Gregor4165bd62010-03-23 23:47:56 +00004499 CXXFinalOverriderMap FinalOverriders;
4500 RD->getFinalOverriders(FinalOverriders);
Mike Stump11289f42009-09-09 15:08:12 +00004501
Anders Carlssona2f74f32010-06-03 01:00:02 +00004502 // Keep a set of seen pure methods so we won't diagnose the same method
4503 // more than once.
4504 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
4505
Douglas Gregor4165bd62010-03-23 23:47:56 +00004506 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
4507 MEnd = FinalOverriders.end();
4508 M != MEnd;
4509 ++M) {
4510 for (OverridingMethods::iterator SO = M->second.begin(),
4511 SOEnd = M->second.end();
4512 SO != SOEnd; ++SO) {
4513 // C++ [class.abstract]p4:
4514 // A class is abstract if it contains or inherits at least one
4515 // pure virtual function for which the final overrider is pure
4516 // virtual.
Mike Stump11289f42009-09-09 15:08:12 +00004517
Douglas Gregor4165bd62010-03-23 23:47:56 +00004518 //
4519 if (SO->second.size() != 1)
4520 continue;
4521
4522 if (!SO->second.front().Method->isPure())
4523 continue;
4524
David Blaikie82e95a32014-11-19 07:49:47 +00004525 if (!SeenPureMethods.insert(SO->second.front().Method).second)
Anders Carlssona2f74f32010-06-03 01:00:02 +00004526 continue;
4527
Douglas Gregor4165bd62010-03-23 23:47:56 +00004528 Diag(SO->second.front().Method->getLocation(),
4529 diag::note_pure_virtual_function)
Chandler Carruth98e3c562011-02-18 23:59:51 +00004530 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor4165bd62010-03-23 23:47:56 +00004531 }
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004532 }
4533
4534 if (!PureVirtualClassDiagSet)
4535 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
4536 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004537}
4538
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004539namespace {
John McCall02db245d2010-08-18 09:41:07 +00004540struct AbstractUsageInfo {
4541 Sema &S;
4542 CXXRecordDecl *Record;
4543 CanQualType AbstractType;
4544 bool Invalid;
Mike Stump11289f42009-09-09 15:08:12 +00004545
John McCall02db245d2010-08-18 09:41:07 +00004546 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
4547 : S(S), Record(Record),
4548 AbstractType(S.Context.getCanonicalType(
4549 S.Context.getTypeDeclType(Record))),
4550 Invalid(false) {}
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004551
John McCall02db245d2010-08-18 09:41:07 +00004552 void DiagnoseAbstractType() {
4553 if (Invalid) return;
4554 S.DiagnoseAbstractType(Record);
4555 Invalid = true;
4556 }
Anders Carlssonb57738b2009-03-24 17:23:42 +00004557
John McCall02db245d2010-08-18 09:41:07 +00004558 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
4559};
4560
4561struct CheckAbstractUsage {
4562 AbstractUsageInfo &Info;
4563 const NamedDecl *Ctx;
4564
4565 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
4566 : Info(Info), Ctx(Ctx) {}
4567
4568 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4569 switch (TL.getTypeLocClass()) {
4570#define ABSTRACT_TYPELOC(CLASS, PARENT)
4571#define TYPELOC(CLASS, PARENT) \
David Blaikie6adc78e2013-02-18 22:06:02 +00004572 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
John McCall02db245d2010-08-18 09:41:07 +00004573#include "clang/AST/TypeLocNodes.def"
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004574 }
John McCall02db245d2010-08-18 09:41:07 +00004575 }
Mike Stump11289f42009-09-09 15:08:12 +00004576
John McCall02db245d2010-08-18 09:41:07 +00004577 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
Alp Toker42a16a62014-01-25 23:51:36 +00004578 Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004579 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
4580 if (!TL.getParam(I))
Douglas Gregor385d3fd2011-02-22 23:21:06 +00004581 continue;
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004582
4583 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
John McCall02db245d2010-08-18 09:41:07 +00004584 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssonb57738b2009-03-24 17:23:42 +00004585 }
John McCall02db245d2010-08-18 09:41:07 +00004586 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004587
John McCall02db245d2010-08-18 09:41:07 +00004588 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4589 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
4590 }
Mike Stump11289f42009-09-09 15:08:12 +00004591
John McCall02db245d2010-08-18 09:41:07 +00004592 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4593 // Visit the type parameters from a permissive context.
4594 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
4595 TemplateArgumentLoc TAL = TL.getArgLoc(I);
4596 if (TAL.getArgument().getKind() == TemplateArgument::Type)
4597 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
4598 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
4599 // TODO: other template argument types?
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004600 }
John McCall02db245d2010-08-18 09:41:07 +00004601 }
Mike Stump11289f42009-09-09 15:08:12 +00004602
John McCall02db245d2010-08-18 09:41:07 +00004603 // Visit pointee types from a permissive context.
4604#define CheckPolymorphic(Type) \
4605 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
4606 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
4607 }
4608 CheckPolymorphic(PointerTypeLoc)
4609 CheckPolymorphic(ReferenceTypeLoc)
4610 CheckPolymorphic(MemberPointerTypeLoc)
4611 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedman0dfb8892011-10-06 23:00:33 +00004612 CheckPolymorphic(AtomicTypeLoc)
Mike Stump11289f42009-09-09 15:08:12 +00004613
John McCall02db245d2010-08-18 09:41:07 +00004614 /// Handle all the types we haven't given a more specific
4615 /// implementation for above.
4616 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4617 // Every other kind of type that we haven't called out already
4618 // that has an inner type is either (1) sugar or (2) contains that
4619 // inner type in some way as a subobject.
4620 if (TypeLoc Next = TL.getNextTypeLoc())
4621 return Visit(Next, Sel);
4622
4623 // If there's no inner type and we're in a permissive context,
4624 // don't diagnose.
4625 if (Sel == Sema::AbstractNone) return;
4626
4627 // Check whether the type matches the abstract type.
4628 QualType T = TL.getType();
4629 if (T->isArrayType()) {
4630 Sel = Sema::AbstractArrayType;
4631 T = Info.S.Context.getBaseElementType(T);
Anders Carlssonb57738b2009-03-24 17:23:42 +00004632 }
John McCall02db245d2010-08-18 09:41:07 +00004633 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
4634 if (CT != Info.AbstractType) return;
4635
4636 // It matched; do some magic.
4637 if (Sel == Sema::AbstractArrayType) {
4638 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
4639 << T << TL.getSourceRange();
4640 } else {
4641 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
4642 << Sel << T << TL.getSourceRange();
4643 }
4644 Info.DiagnoseAbstractType();
4645 }
4646};
4647
4648void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
4649 Sema::AbstractDiagSelID Sel) {
4650 CheckAbstractUsage(*this, D).Visit(TL, Sel);
4651}
4652
4653}
4654
4655/// Check for invalid uses of an abstract type in a method declaration.
4656static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4657 CXXMethodDecl *MD) {
4658 // No need to do the check on definitions, which require that
4659 // the return/param types be complete.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00004660 if (MD->doesThisDeclarationHaveABody())
John McCall02db245d2010-08-18 09:41:07 +00004661 return;
4662
4663 // For safety's sake, just ignore it if we don't have type source
4664 // information. This should never happen for non-implicit methods,
4665 // but...
4666 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
4667 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
4668}
4669
4670/// Check for invalid uses of an abstract type within a class definition.
4671static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4672 CXXRecordDecl *RD) {
Aaron Ballman629afae2014-03-07 19:56:05 +00004673 for (auto *D : RD->decls()) {
John McCall02db245d2010-08-18 09:41:07 +00004674 if (D->isImplicit()) continue;
4675
4676 // Methods and method templates.
4677 if (isa<CXXMethodDecl>(D)) {
4678 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
4679 } else if (isa<FunctionTemplateDecl>(D)) {
4680 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
4681 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
4682
4683 // Fields and static variables.
4684 } else if (isa<FieldDecl>(D)) {
4685 FieldDecl *FD = cast<FieldDecl>(D);
4686 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
4687 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
4688 } else if (isa<VarDecl>(D)) {
4689 VarDecl *VD = cast<VarDecl>(D);
4690 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
4691 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
4692
4693 // Nested classes and class templates.
4694 } else if (isa<CXXRecordDecl>(D)) {
4695 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
4696 } else if (isa<ClassTemplateDecl>(D)) {
4697 CheckAbstractClassUsage(Info,
4698 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
4699 }
4700 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004701}
4702
Hans Wennborg853ae942014-05-30 16:59:42 +00004703/// \brief Check class-level dllimport/dllexport attribute.
4704static void checkDLLAttribute(Sema &S, CXXRecordDecl *Class) {
4705 Attr *ClassAttr = getDLLAttr(Class);
Hans Wennborg205c39b2014-08-23 22:34:43 +00004706
4707 // MSVC inherits DLL attributes to partial class template specializations.
4708 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
4709 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
4710 if (Attr *TemplateAttr =
4711 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
4712 auto *A = cast<InheritableAttr>(TemplateAttr->clone(S.getASTContext()));
4713 A->setInherited(true);
4714 ClassAttr = A;
4715 }
4716 }
4717 }
4718
Hans Wennborg853ae942014-05-30 16:59:42 +00004719 if (!ClassAttr)
4720 return;
4721
Hans Wennborg8313c762014-11-03 16:09:16 +00004722 if (!Class->isExternallyVisible()) {
4723 S.Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
4724 << Class << ClassAttr;
4725 return;
4726 }
4727
Hans Wennborgc2b7f7a2014-08-24 00:12:36 +00004728 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() &&
4729 !ClassAttr->isInherited()) {
4730 // Diagnose dll attributes on members of class with dll attribute.
4731 for (Decl *Member : Class->decls()) {
4732 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
4733 continue;
4734 InheritableAttr *MemberAttr = getDLLAttr(Member);
4735 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
4736 continue;
4737
4738 S.Diag(MemberAttr->getLocation(),
4739 diag::err_attribute_dll_member_of_dll_class)
4740 << MemberAttr << ClassAttr;
4741 S.Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
4742 Member->setInvalidDecl();
4743 }
4744 }
4745
4746 if (Class->getDescribedClassTemplate())
4747 // Don't inherit dll attribute until the template is instantiated.
4748 return;
4749
Hans Wennborg606bd6d2014-11-03 14:24:45 +00004750 // The class is either imported or exported.
4751 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
4752 const bool ClassImported = !ClassExported;
Hans Wennborg853ae942014-05-30 16:59:42 +00004753
Hans Wennborgfd76d912015-01-15 21:18:30 +00004754 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
4755
4756 // Don't dllexport explicit class template instantiation declarations.
4757 if (ClassExported && TSK == TSK_ExplicitInstantiationDeclaration) {
4758 Class->dropAttr<DLLExportAttr>();
4759 return;
4760 }
4761
Hans Wennborg853ae942014-05-30 16:59:42 +00004762 // Force declaration of implicit members so they can inherit the attribute.
4763 S.ForceDeclarationOfImplicitMembers(Class);
4764
4765 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
4766 // seem to be true in practice?
4767
Hans Wennborg853ae942014-05-30 16:59:42 +00004768 for (Decl *Member : Class->decls()) {
Hans Wennborge8ad3832014-06-11 22:44:39 +00004769 VarDecl *VD = dyn_cast<VarDecl>(Member);
4770 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
4771
4772 // Only methods and static fields inherit the attributes.
4773 if (!VD && !MD)
Hans Wennborg853ae942014-05-30 16:59:42 +00004774 continue;
Hans Wennborge8ad3832014-06-11 22:44:39 +00004775
Hans Wennborg606bd6d2014-11-03 14:24:45 +00004776 if (MD) {
4777 // Don't process deleted methods.
4778 if (MD->isDeleted())
4779 continue;
Hans Wennborg853ae942014-05-30 16:59:42 +00004780
Hans Wennborg606bd6d2014-11-03 14:24:45 +00004781 if (MD->isMoveAssignmentOperator() && ClassImported && MD->isInlined()) {
4782 // Current MSVC versions don't export the move assignment operators, so
4783 // don't attempt to import them if we have a definition.
4784 continue;
4785 }
4786
4787 if (MD->isInlined() && ClassImported &&
4788 !S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
4789 // MinGW does not import inline functions.
4790 continue;
4791 }
Hans Wennborge8ad3832014-06-11 22:44:39 +00004792 }
4793
Hans Wennborgc2b7f7a2014-08-24 00:12:36 +00004794 if (!getDLLAttr(Member)) {
Hans Wennborg496524b2014-05-31 02:08:49 +00004795 auto *NewAttr =
4796 cast<InheritableAttr>(ClassAttr->clone(S.getASTContext()));
4797 NewAttr->setInherited(true);
4798 Member->addAttr(NewAttr);
4799 }
Hans Wennborg853ae942014-05-30 16:59:42 +00004800
Hans Wennborg2f9e2932014-08-23 21:10:39 +00004801 if (MD && ClassExported) {
4802 if (MD->isUserProvided()) {
Hans Wennborg45810b42014-12-16 01:15:01 +00004803 // Instantiate non-default class member functions ...
Hans Wennborg334e4ff2014-08-21 01:14:01 +00004804
Hans Wennborg2f9e2932014-08-23 21:10:39 +00004805 // .. except for certain kinds of template specializations.
4806 if (TSK == TSK_ExplicitInstantiationDeclaration)
4807 continue;
4808 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
4809 continue;
Hans Wennborg334e4ff2014-08-21 01:14:01 +00004810
Hans Wennborg2f9e2932014-08-23 21:10:39 +00004811 S.MarkFunctionReferenced(Class->getLocation(), MD);
Hans Wennborg45810b42014-12-16 01:15:01 +00004812
4813 // The function will be passed to the consumer when its definition is
4814 // encountered.
Hans Wennborg2f9e2932014-08-23 21:10:39 +00004815 } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
4816 MD->isCopyAssignmentOperator() ||
4817 MD->isMoveAssignmentOperator()) {
Hans Wennborg45810b42014-12-16 01:15:01 +00004818 // Synthesize and instantiate non-trivial implicit methods, explicitly
4819 // defaulted methods, and the copy and move assignment operators. The
4820 // latter are exported even if they are trivial, because the address of
4821 // an operator can be taken and should compare equal accross libraries.
Hans Wennborg2f9e2932014-08-23 21:10:39 +00004822 S.MarkFunctionReferenced(Class->getLocation(), MD);
Hans Wennborg45810b42014-12-16 01:15:01 +00004823
4824 // There is no later point when we will see the definition of this
4825 // function, so pass it to the consumer now.
4826 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
Hans Wennborg853ae942014-05-30 16:59:42 +00004827 }
4828 }
4829 }
4830}
4831
Douglas Gregorc99f1552009-12-03 18:33:45 +00004832/// \brief Perform semantic checks on a class definition that has been
4833/// completing, introducing implicitly-declared members, checking for
4834/// abstract types, etc.
Douglas Gregor0be31a22010-07-02 17:43:08 +00004835void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +00004836 if (!Record)
Douglas Gregorc99f1552009-12-03 18:33:45 +00004837 return;
4838
John McCall02db245d2010-08-18 09:41:07 +00004839 if (Record->isAbstract() && !Record->isInvalidDecl()) {
4840 AbstractUsageInfo Info(*this, Record);
4841 CheckAbstractClassUsage(Info, Record);
4842 }
Douglas Gregor454a5b62010-04-15 00:00:53 +00004843
4844 // If this is not an aggregate type and has no user-declared constructor,
4845 // complain about any non-static data members of reference or const scalar
4846 // type, since they will never get initializers.
4847 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregorfbf19a02012-02-09 02:20:38 +00004848 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
4849 !Record->isLambda()) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00004850 bool Complained = false;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004851 for (const auto *F : Record->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +00004852 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith938f40b2011-06-11 17:19:42 +00004853 continue;
4854
Douglas Gregor454a5b62010-04-15 00:00:53 +00004855 if (F->getType()->isReferenceType() ||
Benjamin Kramer659d7fc2010-04-16 17:43:15 +00004856 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00004857 if (!Complained) {
4858 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
4859 << Record->getTagKind() << Record;
4860 Complained = true;
4861 }
4862
4863 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4864 << F->getType()->isReferenceType()
4865 << F->getDeclName();
4866 }
4867 }
4868 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00004869
Anders Carlssone771e762011-01-25 18:08:22 +00004870 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor88d292c2010-05-13 16:44:06 +00004871 DynamicClasses.push_back(Record);
Douglas Gregor36c22a22010-10-15 13:21:21 +00004872
4873 if (Record->getIdentifier()) {
4874 // C++ [class.mem]p13:
4875 // If T is the name of a class, then each of the following shall have a
4876 // name different from T:
4877 // - every member of every anonymous union that is a member of class T.
4878 //
4879 // C++ [class.mem]p14:
4880 // In addition, if class T has a user-declared constructor (12.1), every
4881 // non-static data member of class T shall have a name different from T.
David Blaikieff7d47a2012-12-19 00:45:41 +00004882 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4883 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4884 ++I) {
4885 NamedDecl *D = *I;
Francois Pichet783dd6e2010-11-21 06:08:52 +00004886 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4887 isa<IndirectFieldDecl>(D)) {
4888 Diag(D->getLocation(), diag::err_member_name_of_class)
4889 << D->getDeclName();
Douglas Gregor36c22a22010-10-15 13:21:21 +00004890 break;
4891 }
Francois Pichet783dd6e2010-11-21 06:08:52 +00004892 }
Douglas Gregor36c22a22010-10-15 13:21:21 +00004893 }
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004894
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00004895 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregor0cf82f62011-02-19 19:14:36 +00004896 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004897 CXXDestructorDecl *dtor = Record->getDestructor();
David Blaikie04e2e662014-05-09 22:02:28 +00004898 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
4899 !Record->hasAttr<FinalAttr>())
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004900 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4901 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4902 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004903
David Majnemera5433082013-10-18 00:33:31 +00004904 if (Record->isAbstract()) {
4905 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
4906 Diag(Record->getLocation(), diag::warn_abstract_final_class)
4907 << FA->isSpelledAsSealed();
4908 DiagnoseAbstractType(Record);
4909 }
David Blaikie348df502012-09-21 03:21:07 +00004910 }
4911
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00004912 bool HasMethodWithOverrideControl = false,
4913 HasOverridingMethodWithoutOverrideControl = false;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004914 if (!Record->isDependentType()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00004915 for (auto *M : Record->methods()) {
Richard Smithbd305122012-12-11 01:14:52 +00004916 // See if a method overloads virtual methods in a base
4917 // class without overriding any.
David Blaikie2d7c57e2012-04-30 02:36:29 +00004918 if (!M->isStatic())
Aaron Ballman2b124d12014-03-13 16:36:16 +00004919 DiagnoseHiddenVirtualMethods(M);
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00004920 if (M->hasAttr<OverrideAttr>())
4921 HasMethodWithOverrideControl = true;
4922 else if (M->size_overridden_methods() > 0)
4923 HasOverridingMethodWithoutOverrideControl = true;
Richard Smithbd305122012-12-11 01:14:52 +00004924 // Check whether the explicitly-defaulted special members are valid.
4925 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
Aaron Ballman2b124d12014-03-13 16:36:16 +00004926 CheckExplicitlyDefaultedSpecialMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00004927
4928 // For an explicitly defaulted or deleted special member, we defer
4929 // determining triviality until the class is complete. That time is now!
4930 if (!M->isImplicit() && !M->isUserProvided()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00004931 CXXSpecialMember CSM = getSpecialMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00004932 if (CSM != CXXInvalid) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00004933 M->setTrivial(SpecialMemberIsTrivial(M, CSM));
Richard Smithbd305122012-12-11 01:14:52 +00004934
4935 // Inform the class that we've finished declaring this member.
Aaron Ballman2b124d12014-03-13 16:36:16 +00004936 Record->finishedDefaultedOrDeletedMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00004937 }
4938 }
4939 }
4940 }
4941
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00004942 if (HasMethodWithOverrideControl &&
4943 HasOverridingMethodWithoutOverrideControl) {
4944 // At least one method has the 'override' control declared.
4945 // Diagnose all other overridden methods which do not have 'override' specified on them.
4946 for (auto *M : Record->methods())
4947 DiagnoseAbsenceOfOverrideControl(M);
4948 }
Sebastian Redl08905022011-02-05 19:23:19 +00004949
John McCall95833f32014-02-27 20:30:49 +00004950 // ms_struct is a request to use the same ABI rules as MSVC. Check
4951 // whether this class uses any C++ features that are implemented
4952 // completely differently in MSVC, and if so, emit a diagnostic.
4953 // That diagnostic defaults to an error, but we allow projects to
4954 // map it down to a warning (or ignore it). It's a fairly common
4955 // practice among users of the ms_struct pragma to mass-annotate
4956 // headers, sweeping up a bunch of types that the project doesn't
4957 // really rely on MSVC-compatible layout for. We must therefore
4958 // support "ms_struct except for C++ stuff" as a secondary ABI.
4959 if (Record->isMsStruct(Context) &&
4960 (Record->isPolymorphic() || Record->getNumBases())) {
4961 Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
Warren Hunt8f8bad72013-10-11 20:19:00 +00004962 }
4963
Richard Smithc2bc61b2013-03-18 21:12:30 +00004964 // Declare inheriting constructors. We do this eagerly here because:
4965 // - The standard requires an eager diagnostic for conflicting inheriting
Sebastian Redl08905022011-02-05 19:23:19 +00004966 // constructors from different classes.
4967 // - The lazy declaration of the other implicit constructors is so as to not
4968 // waste space and performance on classes that are not meant to be
4969 // instantiated (e.g. meta-functions). This doesn't apply to classes that
Richard Smithc2bc61b2013-03-18 21:12:30 +00004970 // have inheriting constructors.
4971 DeclareInheritingConstructors(Record);
Hans Wennborg853ae942014-05-30 16:59:42 +00004972
4973 checkDLLAttribute(*this, Record);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00004974}
4975
Richard Smith41c35d62013-11-27 03:39:20 +00004976/// Look up the special member function that would be called by a special
4977/// member function for a subobject of class type.
4978///
4979/// \param Class The class type of the subobject.
4980/// \param CSM The kind of special member function.
4981/// \param FieldQuals If the subobject is a field, its cv-qualifiers.
4982/// \param ConstRHS True if this is a copy operation with a const object
4983/// on its RHS, that is, if the argument to the outer special member
4984/// function is 'const' and this is not a field marked 'mutable'.
4985static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember(
4986 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
4987 unsigned FieldQuals, bool ConstRHS) {
4988 unsigned LHSQuals = 0;
4989 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
4990 LHSQuals = FieldQuals;
4991
4992 unsigned RHSQuals = FieldQuals;
4993 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4994 RHSQuals = 0;
4995 else if (ConstRHS)
4996 RHSQuals |= Qualifiers::Const;
4997
4998 return S.LookupSpecialMember(Class, CSM,
4999 RHSQuals & Qualifiers::Const,
5000 RHSQuals & Qualifiers::Volatile,
5001 false,
5002 LHSQuals & Qualifiers::Const,
5003 LHSQuals & Qualifiers::Volatile);
5004}
5005
Richard Smithb5800092012-06-10 05:43:50 +00005006/// Is the special member function which would be selected to perform the
5007/// specified operation on the specified class type a constexpr constructor?
5008static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
5009 Sema::CXXSpecialMember CSM,
Richard Smith41c35d62013-11-27 03:39:20 +00005010 unsigned Quals, bool ConstRHS) {
Richard Smithb5800092012-06-10 05:43:50 +00005011 Sema::SpecialMemberOverloadResult *SMOR =
Richard Smith41c35d62013-11-27 03:39:20 +00005012 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
Richard Smithb5800092012-06-10 05:43:50 +00005013 if (!SMOR || !SMOR->getMethod())
5014 // A constructor we wouldn't select can't be "involved in initializing"
5015 // anything.
5016 return true;
5017 return SMOR->getMethod()->isConstexpr();
5018}
5019
5020/// Determine whether the specified special member function would be constexpr
5021/// if it were implicitly defined.
5022static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
5023 Sema::CXXSpecialMember CSM,
5024 bool ConstArg) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005025 if (!S.getLangOpts().CPlusPlus11)
Richard Smithb5800092012-06-10 05:43:50 +00005026 return false;
5027
5028 // C++11 [dcl.constexpr]p4:
5029 // In the definition of a constexpr constructor [...]
Richard Smith99005e62013-05-07 03:19:20 +00005030 bool Ctor = true;
Richard Smithb5800092012-06-10 05:43:50 +00005031 switch (CSM) {
5032 case Sema::CXXDefaultConstructor:
Richard Smith4086a132012-06-10 07:07:24 +00005033 // Since default constructor lookup is essentially trivial (and cannot
5034 // involve, for instance, template instantiation), we compute whether a
5035 // defaulted default constructor is constexpr directly within CXXRecordDecl.
5036 //
5037 // This is important for performance; we need to know whether the default
5038 // constructor is constexpr to determine whether the type is a literal type.
5039 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
5040
Richard Smithb5800092012-06-10 05:43:50 +00005041 case Sema::CXXCopyConstructor:
5042 case Sema::CXXMoveConstructor:
Richard Smith4086a132012-06-10 07:07:24 +00005043 // For copy or move constructors, we need to perform overload resolution.
Richard Smithb5800092012-06-10 05:43:50 +00005044 break;
5045
5046 case Sema::CXXCopyAssignment:
5047 case Sema::CXXMoveAssignment:
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005048 if (!S.getLangOpts().CPlusPlus14)
Richard Smith99005e62013-05-07 03:19:20 +00005049 return false;
5050 // In C++1y, we need to perform overload resolution.
5051 Ctor = false;
5052 break;
5053
Richard Smithb5800092012-06-10 05:43:50 +00005054 case Sema::CXXDestructor:
5055 case Sema::CXXInvalid:
5056 return false;
5057 }
5058
5059 // -- if the class is a non-empty union, or for each non-empty anonymous
5060 // union member of a non-union class, exactly one non-static data member
5061 // shall be initialized; [DR1359]
Richard Smith4086a132012-06-10 07:07:24 +00005062 //
5063 // If we squint, this is guaranteed, since exactly one non-static data member
5064 // will be initialized (if the constructor isn't deleted), we just don't know
5065 // which one.
Richard Smith99005e62013-05-07 03:19:20 +00005066 if (Ctor && ClassDecl->isUnion())
Richard Smith4086a132012-06-10 07:07:24 +00005067 return true;
Richard Smithb5800092012-06-10 05:43:50 +00005068
5069 // -- the class shall not have any virtual base classes;
Richard Smith99005e62013-05-07 03:19:20 +00005070 if (Ctor && ClassDecl->getNumVBases())
5071 return false;
5072
5073 // C++1y [class.copy]p26:
5074 // -- [the class] is a literal type, and
5075 if (!Ctor && !ClassDecl->isLiteral())
Richard Smithb5800092012-06-10 05:43:50 +00005076 return false;
5077
5078 // -- every constructor involved in initializing [...] base class
5079 // sub-objects shall be a constexpr constructor;
Richard Smith99005e62013-05-07 03:19:20 +00005080 // -- the assignment operator selected to copy/move each direct base
5081 // class is a constexpr function, and
Aaron Ballman574705e2014-03-13 15:41:46 +00005082 for (const auto &B : ClassDecl->bases()) {
5083 const RecordType *BaseType = B.getType()->getAs<RecordType>();
Richard Smithb5800092012-06-10 05:43:50 +00005084 if (!BaseType) continue;
5085
5086 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith41c35d62013-11-27 03:39:20 +00005087 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg))
Richard Smithb5800092012-06-10 05:43:50 +00005088 return false;
5089 }
5090
5091 // -- every constructor involved in initializing non-static data members
5092 // [...] shall be a constexpr constructor;
5093 // -- every non-static data member and base class sub-object shall be
5094 // initialized
Richard Smith41c35d62013-11-27 03:39:20 +00005095 // -- for each non-static data member of X that is of class type (or array
Richard Smith99005e62013-05-07 03:19:20 +00005096 // thereof), the assignment operator selected to copy/move that member is
5097 // a constexpr function
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005098 for (const auto *F : ClassDecl->fields()) {
Richard Smithb5800092012-06-10 05:43:50 +00005099 if (F->isInvalidDecl())
5100 continue;
Richard Smith41c35d62013-11-27 03:39:20 +00005101 QualType BaseType = S.Context.getBaseElementType(F->getType());
5102 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
Richard Smithb5800092012-06-10 05:43:50 +00005103 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith41c35d62013-11-27 03:39:20 +00005104 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
5105 BaseType.getCVRQualifiers(),
5106 ConstArg && !F->isMutable()))
Richard Smithb5800092012-06-10 05:43:50 +00005107 return false;
Richard Smithb5800092012-06-10 05:43:50 +00005108 }
5109 }
5110
5111 // All OK, it's constexpr!
5112 return true;
5113}
5114
Richard Smithd3b5c9082012-07-27 04:22:15 +00005115static Sema::ImplicitExceptionSpecification
5116computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
5117 switch (S.getSpecialMember(MD)) {
5118 case Sema::CXXDefaultConstructor:
5119 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
5120 case Sema::CXXCopyConstructor:
5121 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
5122 case Sema::CXXCopyAssignment:
5123 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
5124 case Sema::CXXMoveConstructor:
5125 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
5126 case Sema::CXXMoveAssignment:
5127 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
5128 case Sema::CXXDestructor:
5129 return S.ComputeDefaultedDtorExceptionSpec(MD);
5130 case Sema::CXXInvalid:
5131 break;
5132 }
Richard Smithc2bc61b2013-03-18 21:12:30 +00005133 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
5134 "only special members have implicit exception specs");
5135 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
Richard Smithd3b5c9082012-07-27 04:22:15 +00005136}
5137
Reid Kleckner78af0702013-08-27 23:08:25 +00005138static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
5139 CXXMethodDecl *MD) {
5140 FunctionProtoType::ExtProtoInfo EPI;
5141
5142 // Build an exception specification pointing back at this member.
Richard Smith8acb4282014-07-31 21:57:55 +00005143 EPI.ExceptionSpec.Type = EST_Unevaluated;
5144 EPI.ExceptionSpec.SourceDecl = MD;
Reid Kleckner78af0702013-08-27 23:08:25 +00005145
5146 // Set the calling convention to the default for C++ instance methods.
5147 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
5148 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
5149 /*IsCXXMethod=*/true));
5150 return EPI;
5151}
5152
Richard Smithd3b5c9082012-07-27 04:22:15 +00005153void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
5154 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
5155 if (FPT->getExceptionSpecType() != EST_Unevaluated)
5156 return;
5157
Richard Smith7f782272012-07-30 23:48:14 +00005158 // Evaluate the exception specification.
Richard Smith8acb4282014-07-31 21:57:55 +00005159 auto ESI = computeImplicitExceptionSpec(*this, Loc, MD).getExceptionSpec();
Richard Smith564417a2014-03-20 21:47:22 +00005160
Richard Smith7f782272012-07-30 23:48:14 +00005161 // Update the type of the special member to use it.
Richard Smith8acb4282014-07-31 21:57:55 +00005162 UpdateExceptionSpec(MD, ESI);
Richard Smith7f782272012-07-30 23:48:14 +00005163
5164 // A user-provided destructor can be defined outside the class. When that
5165 // happens, be sure to update the exception specification on both
5166 // declarations.
5167 const FunctionProtoType *CanonicalFPT =
5168 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
5169 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
Richard Smith8acb4282014-07-31 21:57:55 +00005170 UpdateExceptionSpec(MD->getCanonicalDecl(), ESI);
Richard Smithd3b5c9082012-07-27 04:22:15 +00005171}
5172
Richard Smithb9e90b12012-05-15 04:39:51 +00005173void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
5174 CXXRecordDecl *RD = MD->getParent();
5175 CXXSpecialMember CSM = getSpecialMember(MD);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00005176
Richard Smithb9e90b12012-05-15 04:39:51 +00005177 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
5178 "not an explicitly-defaulted special member");
Alexis Hunt913820d2011-05-13 06:10:58 +00005179
5180 // Whether this was the first-declared instance of the constructor.
Richard Smithb9e90b12012-05-15 04:39:51 +00005181 // This affects whether we implicitly add an exception spec and constexpr.
Alexis Huntc9a55732011-05-14 05:23:28 +00005182 bool First = MD == MD->getCanonicalDecl();
5183
5184 bool HadError = false;
Richard Smithb9e90b12012-05-15 04:39:51 +00005185
5186 // C++11 [dcl.fct.def.default]p1:
5187 // A function that is explicitly defaulted shall
5188 // -- be a special member function (checked elsewhere),
5189 // -- have the same type (except for ref-qualifiers, and except that a
5190 // copy operation can take a non-const reference) as an implicit
5191 // declaration, and
5192 // -- not have default arguments.
5193 unsigned ExpectedParams = 1;
5194 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
5195 ExpectedParams = 0;
5196 if (MD->getNumParams() != ExpectedParams) {
5197 // This also checks for default arguments: a copy or move constructor with a
5198 // default argument is classified as a default constructor, and assignment
5199 // operations and destructors can't have default arguments.
5200 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
5201 << CSM << MD->getSourceRange();
Alexis Huntc9a55732011-05-14 05:23:28 +00005202 HadError = true;
Richard Smith50d705b2012-12-07 02:10:28 +00005203 } else if (MD->isVariadic()) {
5204 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
5205 << CSM << MD->getSourceRange();
5206 HadError = true;
Alexis Huntc9a55732011-05-14 05:23:28 +00005207 }
5208
Richard Smithb9e90b12012-05-15 04:39:51 +00005209 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
Alexis Huntc9a55732011-05-14 05:23:28 +00005210
Richard Smithb5800092012-06-10 05:43:50 +00005211 bool CanHaveConstParam = false;
Richard Smith92f241f2012-12-08 02:53:02 +00005212 if (CSM == CXXCopyConstructor)
Richard Smith1c33fe82012-11-28 06:23:12 +00005213 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
Richard Smith92f241f2012-12-08 02:53:02 +00005214 else if (CSM == CXXCopyAssignment)
Richard Smith1c33fe82012-11-28 06:23:12 +00005215 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
Alexis Huntc9a55732011-05-14 05:23:28 +00005216
Richard Smithb9e90b12012-05-15 04:39:51 +00005217 QualType ReturnType = Context.VoidTy;
5218 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
5219 // Check for return type matching.
Alp Toker314cc812014-01-25 16:55:45 +00005220 ReturnType = Type->getReturnType();
Richard Smithb9e90b12012-05-15 04:39:51 +00005221 QualType ExpectedReturnType =
5222 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
5223 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
5224 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
5225 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
5226 HadError = true;
5227 }
5228
5229 // A defaulted special member cannot have cv-qualifiers.
5230 if (Type->getTypeQuals()) {
5231 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005232 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
Richard Smithb9e90b12012-05-15 04:39:51 +00005233 HadError = true;
5234 }
5235 }
5236
5237 // Check for parameter type matching.
Alp Toker9cacbab2014-01-20 20:26:09 +00005238 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
Richard Smithb5800092012-06-10 05:43:50 +00005239 bool HasConstParam = false;
Richard Smithb9e90b12012-05-15 04:39:51 +00005240 if (ExpectedParams && ArgType->isReferenceType()) {
5241 // Argument must be reference to possibly-const T.
5242 QualType ReferentType = ArgType->getPointeeType();
Richard Smithb5800092012-06-10 05:43:50 +00005243 HasConstParam = ReferentType.isConstQualified();
Richard Smithb9e90b12012-05-15 04:39:51 +00005244
5245 if (ReferentType.isVolatileQualified()) {
5246 Diag(MD->getLocation(),
5247 diag::err_defaulted_special_member_volatile_param) << CSM;
5248 HadError = true;
5249 }
5250
Richard Smithb5800092012-06-10 05:43:50 +00005251 if (HasConstParam && !CanHaveConstParam) {
Richard Smithb9e90b12012-05-15 04:39:51 +00005252 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
5253 Diag(MD->getLocation(),
5254 diag::err_defaulted_special_member_copy_const_param)
5255 << (CSM == CXXCopyAssignment);
5256 // FIXME: Explain why this special member can't be const.
5257 } else {
5258 Diag(MD->getLocation(),
5259 diag::err_defaulted_special_member_move_const_param)
5260 << (CSM == CXXMoveAssignment);
5261 }
5262 HadError = true;
5263 }
Richard Smithb9e90b12012-05-15 04:39:51 +00005264 } else if (ExpectedParams) {
5265 // A copy assignment operator can take its argument by value, but a
5266 // defaulted one cannot.
5267 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Alexis Hunt604aeb32011-05-17 20:44:43 +00005268 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Alexis Huntc9a55732011-05-14 05:23:28 +00005269 HadError = true;
5270 }
Alexis Hunt604aeb32011-05-17 20:44:43 +00005271
Richard Smithcc36f692011-12-22 02:22:31 +00005272 // C++11 [dcl.fct.def.default]p2:
5273 // An explicitly-defaulted function may be declared constexpr only if it
5274 // would have been implicitly declared as constexpr,
Richard Smithb9e90b12012-05-15 04:39:51 +00005275 // Do not apply this rule to members of class templates, since core issue 1358
5276 // makes such functions always instantiate to constexpr functions. For
Richard Smith99005e62013-05-07 03:19:20 +00005277 // functions which cannot be constexpr (for non-constructors in C++11 and for
5278 // destructors in C++1y), this is checked elsewhere.
Richard Smithb5800092012-06-10 05:43:50 +00005279 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
5280 HasConstParam);
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005281 if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
Richard Smith99005e62013-05-07 03:19:20 +00005282 : isa<CXXConstructorDecl>(MD)) &&
5283 MD->isConstexpr() && !Constexpr &&
Richard Smithb9e90b12012-05-15 04:39:51 +00005284 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
5285 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
Richard Smith99005e62013-05-07 03:19:20 +00005286 // FIXME: Explain why the special member can't be constexpr.
Richard Smithb9e90b12012-05-15 04:39:51 +00005287 HadError = true;
Richard Smithcc36f692011-12-22 02:22:31 +00005288 }
Richard Smithbd305122012-12-11 01:14:52 +00005289
Richard Smithcc36f692011-12-22 02:22:31 +00005290 // and may have an explicit exception-specification only if it is compatible
5291 // with the exception-specification on the implicit declaration.
Richard Smithbd305122012-12-11 01:14:52 +00005292 if (Type->hasExceptionSpec()) {
5293 // Delay the check if this is the first declaration of the special member,
5294 // since we may not have parsed some necessary in-class initializers yet.
Richard Smith3901dfe2013-03-27 00:22:47 +00005295 if (First) {
5296 // If the exception specification needs to be instantiated, do so now,
5297 // before we clobber it with an EST_Unevaluated specification below.
5298 if (Type->getExceptionSpecType() == EST_Uninstantiated) {
5299 InstantiateExceptionSpec(MD->getLocStart(), MD);
5300 Type = MD->getType()->getAs<FunctionProtoType>();
5301 }
Richard Smithbd305122012-12-11 01:14:52 +00005302 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
Richard Smith3901dfe2013-03-27 00:22:47 +00005303 } else
Richard Smithbd305122012-12-11 01:14:52 +00005304 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
5305 }
Richard Smithcc36f692011-12-22 02:22:31 +00005306
5307 // If a function is explicitly defaulted on its first declaration,
5308 if (First) {
5309 // -- it is implicitly considered to be constexpr if the implicit
5310 // definition would be,
Richard Smithb9e90b12012-05-15 04:39:51 +00005311 MD->setConstexpr(Constexpr);
Richard Smithcc36f692011-12-22 02:22:31 +00005312
Richard Smithb9e90b12012-05-15 04:39:51 +00005313 // -- it is implicitly considered to have the same exception-specification
5314 // as if it had been implicitly declared,
Richard Smithbd305122012-12-11 01:14:52 +00005315 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
Richard Smith8acb4282014-07-31 21:57:55 +00005316 EPI.ExceptionSpec.Type = EST_Unevaluated;
5317 EPI.ExceptionSpec.SourceDecl = MD;
Jordan Rose5c382722013-03-08 21:51:21 +00005318 MD->setType(Context.getFunctionType(ReturnType,
Craig Topper5fc8fc22014-08-27 06:28:36 +00005319 llvm::makeArrayRef(&ArgType,
Jordan Rose5c382722013-03-08 21:51:21 +00005320 ExpectedParams),
5321 EPI));
Sebastian Redl22653ba2011-08-30 19:58:05 +00005322 }
5323
Richard Smithb9e90b12012-05-15 04:39:51 +00005324 if (ShouldDeleteSpecialMember(MD, CSM)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00005325 if (First) {
Richard Smithb4d2a152013-04-02 19:38:47 +00005326 SetDeclDeleted(MD, MD->getLocation());
Sebastian Redl22653ba2011-08-30 19:58:05 +00005327 } else {
Richard Smithb9e90b12012-05-15 04:39:51 +00005328 // C++11 [dcl.fct.def.default]p4:
5329 // [For a] user-provided explicitly-defaulted function [...] if such a
5330 // function is implicitly defined as deleted, the program is ill-formed.
5331 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
Richard Smith566184a2014-01-22 20:09:10 +00005332 ShouldDeleteSpecialMember(MD, CSM, /*Diagnose*/true);
Richard Smithb9e90b12012-05-15 04:39:51 +00005333 HadError = true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00005334 }
5335 }
Sebastian Redl22653ba2011-08-30 19:58:05 +00005336
Richard Smithb9e90b12012-05-15 04:39:51 +00005337 if (HadError)
5338 MD->setInvalidDecl();
Alexis Huntf91729462011-05-12 22:46:25 +00005339}
5340
Richard Smithbd305122012-12-11 01:14:52 +00005341/// Check whether the exception specification provided for an
5342/// explicitly-defaulted special member matches the exception specification
5343/// that would have been generated for an implicit special member, per
5344/// C++11 [dcl.fct.def.default]p2.
5345void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
5346 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
Richard Smith0b3a4622014-11-13 20:01:57 +00005347 // If the exception specification was explicitly specified but hadn't been
5348 // parsed when the method was defaulted, grab it now.
5349 if (SpecifiedType->getExceptionSpecType() == EST_Unparsed)
5350 SpecifiedType =
5351 MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
5352
Richard Smithbd305122012-12-11 01:14:52 +00005353 // Compute the implicit exception specification.
Reid Kleckner78af0702013-08-27 23:08:25 +00005354 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
5355 /*IsCXXMethod=*/true);
5356 FunctionProtoType::ExtProtoInfo EPI(CC);
Richard Smith8acb4282014-07-31 21:57:55 +00005357 EPI.ExceptionSpec = computeImplicitExceptionSpec(*this, MD->getLocation(), MD)
5358 .getExceptionSpec();
Richard Smithbd305122012-12-11 01:14:52 +00005359 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00005360 Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithbd305122012-12-11 01:14:52 +00005361
5362 // Ensure that it matches.
5363 CheckEquivalentExceptionSpec(
5364 PDiag(diag::err_incorrect_defaulted_exception_spec)
5365 << getSpecialMember(MD), PDiag(),
5366 ImplicitType, SourceLocation(),
5367 SpecifiedType, MD->getLocation());
5368}
5369
Alp Tokerae3a9442013-10-18 05:54:19 +00005370void Sema::CheckDelayedMemberExceptionSpecs() {
Richard Smith88f45492014-11-22 03:09:05 +00005371 decltype(DelayedExceptionSpecChecks) Checks;
5372 decltype(DelayedDefaultedMemberExceptionSpecs) Specs;
Richard Smithbd305122012-12-11 01:14:52 +00005373
Richard Smith88f45492014-11-22 03:09:05 +00005374 std::swap(Checks, DelayedExceptionSpecChecks);
Alp Tokerae3a9442013-10-18 05:54:19 +00005375 std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
5376
5377 // Perform any deferred checking of exception specifications for virtual
5378 // destructors.
Richard Smith88f45492014-11-22 03:09:05 +00005379 for (auto &Check : Checks)
5380 CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
Alp Tokerae3a9442013-10-18 05:54:19 +00005381
5382 // Check that any explicitly-defaulted methods have exception specifications
5383 // compatible with their implicit exception specifications.
Richard Smith88f45492014-11-22 03:09:05 +00005384 for (auto &Spec : Specs)
5385 CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second);
Richard Smithbd305122012-12-11 01:14:52 +00005386}
5387
Richard Smithd951a1d2012-02-18 02:02:13 +00005388namespace {
5389struct SpecialMemberDeletionInfo {
5390 Sema &S;
5391 CXXMethodDecl *MD;
5392 Sema::CXXSpecialMember CSM;
Richard Smith852265f2012-03-30 20:53:28 +00005393 bool Diagnose;
Richard Smithd951a1d2012-02-18 02:02:13 +00005394
5395 // Properties of the special member, computed for convenience.
Richard Smith41c35d62013-11-27 03:39:20 +00005396 bool IsConstructor, IsAssignment, IsMove, ConstArg;
Richard Smithd951a1d2012-02-18 02:02:13 +00005397 SourceLocation Loc;
5398
5399 bool AllFieldsAreConst;
5400
5401 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith852265f2012-03-30 20:53:28 +00005402 Sema::CXXSpecialMember CSM, bool Diagnose)
5403 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
Richard Smithd951a1d2012-02-18 02:02:13 +00005404 IsConstructor(false), IsAssignment(false), IsMove(false),
Richard Smith41c35d62013-11-27 03:39:20 +00005405 ConstArg(false), Loc(MD->getLocation()),
Richard Smithd951a1d2012-02-18 02:02:13 +00005406 AllFieldsAreConst(true) {
5407 switch (CSM) {
5408 case Sema::CXXDefaultConstructor:
5409 case Sema::CXXCopyConstructor:
5410 IsConstructor = true;
5411 break;
5412 case Sema::CXXMoveConstructor:
5413 IsConstructor = true;
5414 IsMove = true;
5415 break;
5416 case Sema::CXXCopyAssignment:
5417 IsAssignment = true;
5418 break;
5419 case Sema::CXXMoveAssignment:
5420 IsAssignment = true;
5421 IsMove = true;
5422 break;
5423 case Sema::CXXDestructor:
5424 break;
5425 case Sema::CXXInvalid:
5426 llvm_unreachable("invalid special member kind");
5427 }
5428
5429 if (MD->getNumParams()) {
Richard Smith41c35d62013-11-27 03:39:20 +00005430 if (const ReferenceType *RT =
5431 MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
5432 ConstArg = RT->getPointeeType().isConstQualified();
Richard Smithd951a1d2012-02-18 02:02:13 +00005433 }
5434 }
5435
5436 bool inUnion() const { return MD->getParent()->isUnion(); }
5437
5438 /// Look up the corresponding special member in the given class.
Richard Smithaf136f82012-07-18 03:51:16 +00005439 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
Richard Smith41c35d62013-11-27 03:39:20 +00005440 unsigned Quals, bool IsMutable) {
5441 return lookupCallFromSpecialMember(S, Class, CSM, Quals,
5442 ConstArg && !IsMutable);
Richard Smithd951a1d2012-02-18 02:02:13 +00005443 }
5444
Richard Smith852265f2012-03-30 20:53:28 +00005445 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
Richard Smith921bd202012-02-26 09:11:52 +00005446
Richard Smith852265f2012-03-30 20:53:28 +00005447 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smithd951a1d2012-02-18 02:02:13 +00005448 bool shouldDeleteForField(FieldDecl *FD);
5449 bool shouldDeleteForAllConstMembers();
Richard Smith852265f2012-03-30 20:53:28 +00005450
Richard Smithaf136f82012-07-18 03:51:16 +00005451 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
5452 unsigned Quals);
Richard Smith852265f2012-03-30 20:53:28 +00005453 bool shouldDeleteForSubobjectCall(Subobject Subobj,
5454 Sema::SpecialMemberOverloadResult *SMOR,
5455 bool IsDtorCallInCtor);
John McCalld4274212012-04-09 20:53:23 +00005456
5457 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smithd951a1d2012-02-18 02:02:13 +00005458};
5459}
5460
John McCalld4274212012-04-09 20:53:23 +00005461/// Is the given special member inaccessible when used on the given
5462/// sub-object.
5463bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
5464 CXXMethodDecl *target) {
5465 /// If we're operating on a base class, the object type is the
5466 /// type of this special member.
5467 QualType objectTy;
Dmitri Gribenko76bb5cabfa2012-09-10 21:20:09 +00005468 AccessSpecifier access = target->getAccess();
John McCalld4274212012-04-09 20:53:23 +00005469 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
5470 objectTy = S.Context.getTypeDeclType(MD->getParent());
5471 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
5472
5473 // If we're operating on a field, the object type is the type of the field.
5474 } else {
5475 objectTy = S.Context.getTypeDeclType(target->getParent());
5476 }
5477
5478 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
5479}
5480
Richard Smith852265f2012-03-30 20:53:28 +00005481/// Check whether we should delete a special member due to the implicit
5482/// definition containing a call to a special member of a subobject.
5483bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
5484 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
5485 bool IsDtorCallInCtor) {
5486 CXXMethodDecl *Decl = SMOR->getMethod();
5487 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
5488
5489 int DiagKind = -1;
5490
5491 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
5492 DiagKind = !Decl ? 0 : 1;
5493 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5494 DiagKind = 2;
John McCalld4274212012-04-09 20:53:23 +00005495 else if (!isAccessible(Subobj, Decl))
Richard Smith852265f2012-03-30 20:53:28 +00005496 DiagKind = 3;
5497 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
5498 !Decl->isTrivial()) {
5499 // A member of a union must have a trivial corresponding special member.
5500 // As a weird special case, a destructor call from a union's constructor
5501 // must be accessible and non-deleted, but need not be trivial. Such a
5502 // destructor is never actually called, but is semantically checked as
5503 // if it were.
5504 DiagKind = 4;
5505 }
5506
5507 if (DiagKind == -1)
5508 return false;
5509
5510 if (Diagnose) {
5511 if (Field) {
5512 S.Diag(Field->getLocation(),
5513 diag::note_deleted_special_member_class_subobject)
5514 << CSM << MD->getParent() << /*IsField*/true
5515 << Field << DiagKind << IsDtorCallInCtor;
5516 } else {
5517 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
5518 S.Diag(Base->getLocStart(),
5519 diag::note_deleted_special_member_class_subobject)
5520 << CSM << MD->getParent() << /*IsField*/false
5521 << Base->getType() << DiagKind << IsDtorCallInCtor;
5522 }
5523
5524 if (DiagKind == 1)
5525 S.NoteDeletedFunction(Decl);
5526 // FIXME: Explain inaccessibility if DiagKind == 3.
5527 }
5528
5529 return true;
5530}
5531
Richard Smith921bd202012-02-26 09:11:52 +00005532/// Check whether we should delete a special member function due to having a
Richard Smithaf136f82012-07-18 03:51:16 +00005533/// direct or virtual base class or non-static data member of class type M.
Richard Smith921bd202012-02-26 09:11:52 +00005534bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smithaf136f82012-07-18 03:51:16 +00005535 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
Richard Smith852265f2012-03-30 20:53:28 +00005536 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Richard Smith41c35d62013-11-27 03:39:20 +00005537 bool IsMutable = Field && Field->isMutable();
Richard Smithd951a1d2012-02-18 02:02:13 +00005538
5539 // C++11 [class.ctor]p5:
Richard Smith5704fe82012-03-29 19:00:10 +00005540 // -- any direct or virtual base class, or non-static data member with no
5541 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smithd951a1d2012-02-18 02:02:13 +00005542 // either M has no default constructor or overload resolution as applied
5543 // to M's default constructor results in an ambiguity or in a function
5544 // that is deleted or inaccessible
5545 // C++11 [class.copy]p11, C++11 [class.copy]p23:
5546 // -- a direct or virtual base class B that cannot be copied/moved because
5547 // overload resolution, as applied to B's corresponding special member,
5548 // results in an ambiguity or a function that is deleted or inaccessible
5549 // from the defaulted special member
Richard Smith852265f2012-03-30 20:53:28 +00005550 // C++11 [class.dtor]p5:
5551 // -- any direct or virtual base class [...] has a type with a destructor
5552 // that is deleted or inaccessible
5553 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005554 Field && Field->hasInClassInitializer()) &&
Richard Smith41c35d62013-11-27 03:39:20 +00005555 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
5556 false))
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005557 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00005558
Richard Smith852265f2012-03-30 20:53:28 +00005559 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
5560 // -- any direct or virtual base class or non-static data member has a
5561 // type with a destructor that is deleted or inaccessible
5562 if (IsConstructor) {
5563 Sema::SpecialMemberOverloadResult *SMOR =
5564 S.LookupSpecialMember(Class, Sema::CXXDestructor,
5565 false, false, false, false, false);
5566 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
5567 return true;
5568 }
5569
Richard Smith921bd202012-02-26 09:11:52 +00005570 return false;
5571}
5572
5573/// Check whether we should delete a special member function due to the class
5574/// having a particular direct or virtual base class.
Richard Smith852265f2012-03-30 20:53:28 +00005575bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005576 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
Richard Smithaf136f82012-07-18 03:51:16 +00005577 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
Richard Smithd951a1d2012-02-18 02:02:13 +00005578}
5579
5580/// Check whether we should delete a special member function due to the class
5581/// having a particular non-static data member.
5582bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
5583 QualType FieldType = S.Context.getBaseElementType(FD->getType());
5584 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
5585
5586 if (CSM == Sema::CXXDefaultConstructor) {
5587 // For a default constructor, all references must be initialized in-class
5588 // and, if a union, it must have a non-const member.
Richard Smith852265f2012-03-30 20:53:28 +00005589 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
5590 if (Diagnose)
5591 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
5592 << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smithd951a1d2012-02-18 02:02:13 +00005593 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005594 }
Richard Smith619ecdc2012-02-27 06:07:25 +00005595 // C++11 [class.ctor]p5: any non-variant non-static data member of
5596 // const-qualified type (or array thereof) with no
5597 // brace-or-equal-initializer does not have a user-provided default
5598 // constructor.
5599 if (!inUnion() && FieldType.isConstQualified() &&
5600 !FD->hasInClassInitializer() &&
Richard Smith852265f2012-03-30 20:53:28 +00005601 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
5602 if (Diagnose)
5603 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smithc5f98f32012-04-29 06:32:34 +00005604 << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith619ecdc2012-02-27 06:07:25 +00005605 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005606 }
5607
5608 if (inUnion() && !FieldType.isConstQualified())
5609 AllFieldsAreConst = false;
Richard Smithd951a1d2012-02-18 02:02:13 +00005610 } else if (CSM == Sema::CXXCopyConstructor) {
5611 // For a copy constructor, data members must not be of rvalue reference
5612 // type.
Richard Smith852265f2012-03-30 20:53:28 +00005613 if (FieldType->isRValueReferenceType()) {
5614 if (Diagnose)
5615 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
5616 << MD->getParent() << FD << FieldType;
Richard Smithd951a1d2012-02-18 02:02:13 +00005617 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005618 }
Richard Smithd951a1d2012-02-18 02:02:13 +00005619 } else if (IsAssignment) {
5620 // For an assignment operator, data members must not be of reference type.
Richard Smith852265f2012-03-30 20:53:28 +00005621 if (FieldType->isReferenceType()) {
5622 if (Diagnose)
5623 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
5624 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smithd951a1d2012-02-18 02:02:13 +00005625 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005626 }
5627 if (!FieldRecord && FieldType.isConstQualified()) {
5628 // C++11 [class.copy]p23:
5629 // -- a non-static data member of const non-class type (or array thereof)
5630 if (Diagnose)
5631 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smithc5f98f32012-04-29 06:32:34 +00005632 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith852265f2012-03-30 20:53:28 +00005633 return true;
5634 }
Richard Smithd951a1d2012-02-18 02:02:13 +00005635 }
5636
5637 if (FieldRecord) {
Richard Smithd951a1d2012-02-18 02:02:13 +00005638 // Some additional restrictions exist on the variant members.
5639 if (!inUnion() && FieldRecord->isUnion() &&
5640 FieldRecord->isAnonymousStructOrUnion()) {
5641 bool AllVariantFieldsAreConst = true;
5642
Richard Smith5704fe82012-03-29 19:00:10 +00005643 // FIXME: Handle anonymous unions declared within anonymous unions.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005644 for (auto *UI : FieldRecord->fields()) {
Richard Smithd951a1d2012-02-18 02:02:13 +00005645 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smithd951a1d2012-02-18 02:02:13 +00005646
5647 if (!UnionFieldType.isConstQualified())
5648 AllVariantFieldsAreConst = false;
5649
Richard Smith921bd202012-02-26 09:11:52 +00005650 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
5651 if (UnionFieldRecord &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005652 shouldDeleteForClassSubobject(UnionFieldRecord, UI,
Richard Smithaf136f82012-07-18 03:51:16 +00005653 UnionFieldType.getCVRQualifiers()))
Richard Smith921bd202012-02-26 09:11:52 +00005654 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00005655 }
5656
5657 // At least one member in each anonymous union must be non-const
Douglas Gregor232ee492012-02-24 21:25:53 +00005658 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005659 !FieldRecord->field_empty()) {
Richard Smith852265f2012-03-30 20:53:28 +00005660 if (Diagnose)
5661 S.Diag(FieldRecord->getLocation(),
5662 diag::note_deleted_default_ctor_all_const)
5663 << MD->getParent() << /*anonymous union*/1;
Richard Smithd951a1d2012-02-18 02:02:13 +00005664 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005665 }
Richard Smithd951a1d2012-02-18 02:02:13 +00005666
Richard Smith5704fe82012-03-29 19:00:10 +00005667 // Don't check the implicit member of the anonymous union type.
Richard Smithd951a1d2012-02-18 02:02:13 +00005668 // This is technically non-conformant, but sanity demands it.
5669 return false;
5670 }
5671
Richard Smithaf136f82012-07-18 03:51:16 +00005672 if (shouldDeleteForClassSubobject(FieldRecord, FD,
5673 FieldType.getCVRQualifiers()))
Richard Smith5704fe82012-03-29 19:00:10 +00005674 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00005675 }
5676
5677 return false;
5678}
5679
5680/// C++11 [class.ctor] p5:
5681/// A defaulted default constructor for a class X is defined as deleted if
5682/// X is a union and all of its variant members are of const-qualified type.
5683bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor232ee492012-02-24 21:25:53 +00005684 // This is a silly definition, because it gives an empty union a deleted
5685 // default constructor. Don't do that.
Richard Smith852265f2012-03-30 20:53:28 +00005686 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005687 !MD->getParent()->field_empty()) {
Richard Smith852265f2012-03-30 20:53:28 +00005688 if (Diagnose)
5689 S.Diag(MD->getParent()->getLocation(),
5690 diag::note_deleted_default_ctor_all_const)
5691 << MD->getParent() << /*not anonymous union*/0;
5692 return true;
5693 }
5694 return false;
Richard Smithd951a1d2012-02-18 02:02:13 +00005695}
5696
5697/// Determine whether a defaulted special member function should be defined as
5698/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
5699/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith852265f2012-03-30 20:53:28 +00005700bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
5701 bool Diagnose) {
Richard Smithf716bb82012-08-06 02:25:10 +00005702 if (MD->isInvalidDecl())
5703 return false;
Alexis Huntd6da8762011-10-10 06:18:57 +00005704 CXXRecordDecl *RD = MD->getParent();
Alexis Huntea6f0322011-05-11 22:34:38 +00005705 assert(!RD->isDependentType() && "do deletion after instantiation");
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005706 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
Alexis Huntea6f0322011-05-11 22:34:38 +00005707 return false;
5708
Richard Smithd951a1d2012-02-18 02:02:13 +00005709 // C++11 [expr.lambda.prim]p19:
5710 // The closure type associated with a lambda-expression has a
5711 // deleted (8.4.3) default constructor and a deleted copy
5712 // assignment operator.
5713 if (RD->isLambda() &&
Richard Smith852265f2012-03-30 20:53:28 +00005714 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
5715 if (Diagnose)
5716 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smithd951a1d2012-02-18 02:02:13 +00005717 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005718 }
5719
Richard Smith6f1e2c62012-04-02 20:59:25 +00005720 // For an anonymous struct or union, the copy and assignment special members
5721 // will never be used, so skip the check. For an anonymous union declared at
5722 // namespace scope, the constructor and destructor are used.
5723 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
5724 RD->isAnonymousStructOrUnion())
5725 return false;
5726
Richard Smith852265f2012-03-30 20:53:28 +00005727 // C++11 [class.copy]p7, p18:
5728 // If the class definition declares a move constructor or move assignment
5729 // operator, an implicitly declared copy constructor or copy assignment
5730 // operator is defined as deleted.
5731 if (MD->isImplicit() &&
5732 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005733 CXXMethodDecl *UserDeclaredMove = nullptr;
Richard Smith852265f2012-03-30 20:53:28 +00005734
5735 // In Microsoft mode, a user-declared move only causes the deletion of the
5736 // corresponding copy operation, not both copy operations.
5737 if (RD->hasUserDeclaredMoveConstructor() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00005738 (!getLangOpts().MSVCCompat || CSM == CXXCopyConstructor)) {
Richard Smith852265f2012-03-30 20:53:28 +00005739 if (!Diagnose) return true;
Richard Smith1a2532b2012-12-08 04:10:18 +00005740
5741 // Find any user-declared move constructor.
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005742 for (auto *I : RD->ctors()) {
Richard Smith1a2532b2012-12-08 04:10:18 +00005743 if (I->isMoveConstructor()) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005744 UserDeclaredMove = I;
Richard Smith1a2532b2012-12-08 04:10:18 +00005745 break;
5746 }
5747 }
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005748 assert(UserDeclaredMove);
Richard Smith852265f2012-03-30 20:53:28 +00005749 } else if (RD->hasUserDeclaredMoveAssignment() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00005750 (!getLangOpts().MSVCCompat || CSM == CXXCopyAssignment)) {
Richard Smith852265f2012-03-30 20:53:28 +00005751 if (!Diagnose) return true;
Richard Smith1a2532b2012-12-08 04:10:18 +00005752
5753 // Find any user-declared move assignment operator.
Aaron Ballman2b124d12014-03-13 16:36:16 +00005754 for (auto *I : RD->methods()) {
Richard Smith1a2532b2012-12-08 04:10:18 +00005755 if (I->isMoveAssignmentOperator()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00005756 UserDeclaredMove = I;
Richard Smith1a2532b2012-12-08 04:10:18 +00005757 break;
5758 }
5759 }
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005760 assert(UserDeclaredMove);
Richard Smith852265f2012-03-30 20:53:28 +00005761 }
5762
5763 if (UserDeclaredMove) {
5764 Diag(UserDeclaredMove->getLocation(),
5765 diag::note_deleted_copy_user_declared_move)
Richard Smithf989e512012-04-02 21:07:48 +00005766 << (CSM == CXXCopyAssignment) << RD
Richard Smith852265f2012-03-30 20:53:28 +00005767 << UserDeclaredMove->isMoveAssignmentOperator();
5768 return true;
5769 }
5770 }
Alexis Huntd6da8762011-10-10 06:18:57 +00005771
Richard Smith6f1e2c62012-04-02 20:59:25 +00005772 // Do access control from the special member function
5773 ContextRAII MethodContext(*this, MD);
5774
Richard Smith921bd202012-02-26 09:11:52 +00005775 // C++11 [class.dtor]p5:
5776 // -- for a virtual destructor, lookup of the non-array deallocation function
5777 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith852265f2012-03-30 20:53:28 +00005778 if (CSM == CXXDestructor && MD->isVirtual()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005779 FunctionDecl *OperatorDelete = nullptr;
Richard Smith921bd202012-02-26 09:11:52 +00005780 DeclarationName Name =
5781 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5782 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smith852265f2012-03-30 20:53:28 +00005783 OperatorDelete, false)) {
5784 if (Diagnose)
5785 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith921bd202012-02-26 09:11:52 +00005786 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005787 }
Richard Smith921bd202012-02-26 09:11:52 +00005788 }
5789
Richard Smith852265f2012-03-30 20:53:28 +00005790 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
Alexis Huntea6f0322011-05-11 22:34:38 +00005791
Aaron Ballman574705e2014-03-13 15:41:46 +00005792 for (auto &BI : RD->bases())
5793 if (!BI.isVirtual() &&
5794 SMI.shouldDeleteForBase(&BI))
Richard Smithd951a1d2012-02-18 02:02:13 +00005795 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00005796
Richard Smithd1627032013-07-22 18:06:23 +00005797 // Per DR1611, do not consider virtual bases of constructors of abstract
5798 // classes, since we are not going to construct them.
Richard Smithbc46e432013-07-22 02:56:56 +00005799 if (!RD->isAbstract() || !SMI.IsConstructor) {
Aaron Ballman445a9392014-03-13 16:15:17 +00005800 for (auto &BI : RD->vbases())
5801 if (SMI.shouldDeleteForBase(&BI))
Richard Smithbc46e432013-07-22 02:56:56 +00005802 return true;
5803 }
Alexis Huntea6f0322011-05-11 22:34:38 +00005804
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005805 for (auto *FI : RD->fields())
Richard Smithd951a1d2012-02-18 02:02:13 +00005806 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005807 SMI.shouldDeleteForField(FI))
Alexis Hunta671bca2011-05-20 21:43:47 +00005808 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00005809
Richard Smithd951a1d2012-02-18 02:02:13 +00005810 if (SMI.shouldDeleteForAllConstMembers())
Alexis Huntea6f0322011-05-11 22:34:38 +00005811 return true;
5812
Eli Bendersky9a220fc2014-09-29 20:38:29 +00005813 if (getLangOpts().CUDA) {
5814 // We should delete the special member in CUDA mode if target inference
5815 // failed.
5816 return inferCUDATargetForImplicitSpecialMember(RD, CSM, MD, SMI.ConstArg,
5817 Diagnose);
5818 }
5819
Alexis Huntea6f0322011-05-11 22:34:38 +00005820 return false;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005821}
5822
Richard Smith92f241f2012-12-08 02:53:02 +00005823/// Perform lookup for a special member of the specified kind, and determine
5824/// whether it is trivial. If the triviality can be determined without the
5825/// lookup, skip it. This is intended for use when determining whether a
5826/// special member of a containing object is trivial, and thus does not ever
5827/// perform overload resolution for default constructors.
5828///
5829/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
5830/// member that was most likely to be intended to be trivial, if any.
5831static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
5832 Sema::CXXSpecialMember CSM, unsigned Quals,
Richard Smith41c35d62013-11-27 03:39:20 +00005833 bool ConstRHS, CXXMethodDecl **Selected) {
Richard Smith92f241f2012-12-08 02:53:02 +00005834 if (Selected)
Craig Topperc3ec1492014-05-26 06:22:03 +00005835 *Selected = nullptr;
Richard Smith92f241f2012-12-08 02:53:02 +00005836
5837 switch (CSM) {
5838 case Sema::CXXInvalid:
5839 llvm_unreachable("not a special member");
5840
5841 case Sema::CXXDefaultConstructor:
5842 // C++11 [class.ctor]p5:
5843 // A default constructor is trivial if:
5844 // - all the [direct subobjects] have trivial default constructors
5845 //
5846 // Note, no overload resolution is performed in this case.
5847 if (RD->hasTrivialDefaultConstructor())
5848 return true;
5849
5850 if (Selected) {
5851 // If there's a default constructor which could have been trivial, dig it
5852 // out. Otherwise, if there's any user-provided default constructor, point
5853 // to that as an example of why there's not a trivial one.
Craig Topperc3ec1492014-05-26 06:22:03 +00005854 CXXConstructorDecl *DefCtor = nullptr;
Richard Smith92f241f2012-12-08 02:53:02 +00005855 if (RD->needsImplicitDefaultConstructor())
5856 S.DeclareImplicitDefaultConstructor(RD);
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005857 for (auto *CI : RD->ctors()) {
Richard Smith92f241f2012-12-08 02:53:02 +00005858 if (!CI->isDefaultConstructor())
5859 continue;
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005860 DefCtor = CI;
Richard Smith92f241f2012-12-08 02:53:02 +00005861 if (!DefCtor->isUserProvided())
5862 break;
5863 }
5864
5865 *Selected = DefCtor;
5866 }
5867
5868 return false;
5869
5870 case Sema::CXXDestructor:
5871 // C++11 [class.dtor]p5:
5872 // A destructor is trivial if:
5873 // - all the direct [subobjects] have trivial destructors
5874 if (RD->hasTrivialDestructor())
5875 return true;
5876
5877 if (Selected) {
5878 if (RD->needsImplicitDestructor())
5879 S.DeclareImplicitDestructor(RD);
5880 *Selected = RD->getDestructor();
5881 }
5882
5883 return false;
5884
5885 case Sema::CXXCopyConstructor:
5886 // C++11 [class.copy]p12:
5887 // A copy constructor is trivial if:
5888 // - the constructor selected to copy each direct [subobject] is trivial
5889 if (RD->hasTrivialCopyConstructor()) {
5890 if (Quals == Qualifiers::Const)
5891 // We must either select the trivial copy constructor or reach an
5892 // ambiguity; no need to actually perform overload resolution.
5893 return true;
5894 } else if (!Selected) {
5895 return false;
5896 }
5897 // In C++98, we are not supposed to perform overload resolution here, but we
5898 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
5899 // cases like B as having a non-trivial copy constructor:
5900 // struct A { template<typename T> A(T&); };
5901 // struct B { mutable A a; };
5902 goto NeedOverloadResolution;
5903
5904 case Sema::CXXCopyAssignment:
5905 // C++11 [class.copy]p25:
5906 // A copy assignment operator is trivial if:
5907 // - the assignment operator selected to copy each direct [subobject] is
5908 // trivial
5909 if (RD->hasTrivialCopyAssignment()) {
5910 if (Quals == Qualifiers::Const)
5911 return true;
5912 } else if (!Selected) {
5913 return false;
5914 }
5915 // In C++98, we are not supposed to perform overload resolution here, but we
5916 // treat that as a language defect.
5917 goto NeedOverloadResolution;
5918
5919 case Sema::CXXMoveConstructor:
5920 case Sema::CXXMoveAssignment:
5921 NeedOverloadResolution:
5922 Sema::SpecialMemberOverloadResult *SMOR =
Richard Smith41c35d62013-11-27 03:39:20 +00005923 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
Richard Smith92f241f2012-12-08 02:53:02 +00005924
5925 // The standard doesn't describe how to behave if the lookup is ambiguous.
5926 // We treat it as not making the member non-trivial, just like the standard
5927 // mandates for the default constructor. This should rarely matter, because
5928 // the member will also be deleted.
5929 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5930 return true;
5931
5932 if (!SMOR->getMethod()) {
5933 assert(SMOR->getKind() ==
5934 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5935 return false;
5936 }
5937
5938 // We deliberately don't check if we found a deleted special member. We're
5939 // not supposed to!
5940 if (Selected)
5941 *Selected = SMOR->getMethod();
5942 return SMOR->getMethod()->isTrivial();
5943 }
5944
5945 llvm_unreachable("unknown special method kind");
5946}
5947
Benjamin Kramer3e350262013-02-15 12:30:38 +00005948static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005949 for (auto *CI : RD->ctors())
Richard Smith92f241f2012-12-08 02:53:02 +00005950 if (!CI->isImplicit())
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005951 return CI;
Richard Smith92f241f2012-12-08 02:53:02 +00005952
5953 // Look for constructor templates.
5954 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
5955 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
5956 if (CXXConstructorDecl *CD =
5957 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
5958 return CD;
5959 }
5960
Craig Topperc3ec1492014-05-26 06:22:03 +00005961 return nullptr;
Richard Smith92f241f2012-12-08 02:53:02 +00005962}
5963
5964/// The kind of subobject we are checking for triviality. The values of this
5965/// enumeration are used in diagnostics.
5966enum TrivialSubobjectKind {
5967 /// The subobject is a base class.
5968 TSK_BaseClass,
5969 /// The subobject is a non-static data member.
5970 TSK_Field,
5971 /// The object is actually the complete object.
5972 TSK_CompleteObject
5973};
5974
5975/// Check whether the special member selected for a given type would be trivial.
5976static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
Richard Smith41c35d62013-11-27 03:39:20 +00005977 QualType SubType, bool ConstRHS,
Richard Smith92f241f2012-12-08 02:53:02 +00005978 Sema::CXXSpecialMember CSM,
5979 TrivialSubobjectKind Kind,
5980 bool Diagnose) {
5981 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
5982 if (!SubRD)
5983 return true;
5984
5985 CXXMethodDecl *Selected;
5986 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005987 ConstRHS, Diagnose ? &Selected : nullptr))
Richard Smith92f241f2012-12-08 02:53:02 +00005988 return true;
5989
5990 if (Diagnose) {
Richard Smith41c35d62013-11-27 03:39:20 +00005991 if (ConstRHS)
5992 SubType.addConst();
5993
Richard Smith92f241f2012-12-08 02:53:02 +00005994 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
5995 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
5996 << Kind << SubType.getUnqualifiedType();
5997 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
5998 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
5999 } else if (!Selected)
6000 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
6001 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
6002 else if (Selected->isUserProvided()) {
6003 if (Kind == TSK_CompleteObject)
6004 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
6005 << Kind << SubType.getUnqualifiedType() << CSM;
6006 else {
6007 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
6008 << Kind << SubType.getUnqualifiedType() << CSM;
6009 S.Diag(Selected->getLocation(), diag::note_declared_at);
6010 }
6011 } else {
6012 if (Kind != TSK_CompleteObject)
6013 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
6014 << Kind << SubType.getUnqualifiedType() << CSM;
6015
6016 // Explain why the defaulted or deleted special member isn't trivial.
6017 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
6018 }
6019 }
6020
6021 return false;
6022}
6023
6024/// Check whether the members of a class type allow a special member to be
6025/// trivial.
6026static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
6027 Sema::CXXSpecialMember CSM,
6028 bool ConstArg, bool Diagnose) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006029 for (const auto *FI : RD->fields()) {
Richard Smith92f241f2012-12-08 02:53:02 +00006030 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
6031 continue;
6032
6033 QualType FieldType = S.Context.getBaseElementType(FI->getType());
6034
6035 // Pretend anonymous struct or union members are members of this class.
6036 if (FI->isAnonymousStructOrUnion()) {
6037 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
6038 CSM, ConstArg, Diagnose))
6039 return false;
6040 continue;
6041 }
6042
6043 // C++11 [class.ctor]p5:
6044 // A default constructor is trivial if [...]
6045 // -- no non-static data member of its class has a
6046 // brace-or-equal-initializer
6047 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
6048 if (Diagnose)
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006049 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
Richard Smith92f241f2012-12-08 02:53:02 +00006050 return false;
6051 }
6052
6053 // Objective C ARC 4.3.5:
6054 // [...] nontrivally ownership-qualified types are [...] not trivially
6055 // default constructible, copy constructible, move constructible, copy
6056 // assignable, move assignable, or destructible [...]
6057 if (S.getLangOpts().ObjCAutoRefCount &&
6058 FieldType.hasNonTrivialObjCLifetime()) {
6059 if (Diagnose)
6060 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
6061 << RD << FieldType.getObjCLifetime();
6062 return false;
6063 }
6064
Richard Smith41c35d62013-11-27 03:39:20 +00006065 bool ConstRHS = ConstArg && !FI->isMutable();
6066 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
6067 CSM, TSK_Field, Diagnose))
Richard Smith92f241f2012-12-08 02:53:02 +00006068 return false;
6069 }
6070
6071 return true;
6072}
6073
6074/// Diagnose why the specified class does not have a trivial special member of
6075/// the given kind.
6076void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
6077 QualType Ty = Context.getRecordType(RD);
Richard Smith92f241f2012-12-08 02:53:02 +00006078
Richard Smith41c35d62013-11-27 03:39:20 +00006079 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
6080 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
Richard Smith92f241f2012-12-08 02:53:02 +00006081 TSK_CompleteObject, /*Diagnose*/true);
6082}
6083
6084/// Determine whether a defaulted or deleted special member function is trivial,
6085/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
6086/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
6087bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
6088 bool Diagnose) {
Richard Smith92f241f2012-12-08 02:53:02 +00006089 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
6090
6091 CXXRecordDecl *RD = MD->getParent();
6092
6093 bool ConstArg = false;
Richard Smith92f241f2012-12-08 02:53:02 +00006094
Richard Smith2002bfe2013-11-04 02:02:27 +00006095 // C++11 [class.copy]p12, p25: [DR1593]
6096 // A [special member] is trivial if [...] its parameter-type-list is
6097 // equivalent to the parameter-type-list of an implicit declaration [...]
Richard Smith92f241f2012-12-08 02:53:02 +00006098 switch (CSM) {
6099 case CXXDefaultConstructor:
6100 case CXXDestructor:
6101 // Trivial default constructors and destructors cannot have parameters.
6102 break;
6103
6104 case CXXCopyConstructor:
6105 case CXXCopyAssignment: {
6106 // Trivial copy operations always have const, non-volatile parameter types.
6107 ConstArg = true;
Jordan Rosed03d99d2013-03-05 01:27:54 +00006108 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smith92f241f2012-12-08 02:53:02 +00006109 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
6110 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
6111 if (Diagnose)
6112 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
6113 << Param0->getSourceRange() << Param0->getType()
6114 << Context.getLValueReferenceType(
6115 Context.getRecordType(RD).withConst());
6116 return false;
6117 }
6118 break;
6119 }
6120
6121 case CXXMoveConstructor:
6122 case CXXMoveAssignment: {
6123 // Trivial move operations always have non-cv-qualified parameters.
Jordan Rosed03d99d2013-03-05 01:27:54 +00006124 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smith92f241f2012-12-08 02:53:02 +00006125 const RValueReferenceType *RT =
6126 Param0->getType()->getAs<RValueReferenceType>();
6127 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
6128 if (Diagnose)
6129 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
6130 << Param0->getSourceRange() << Param0->getType()
6131 << Context.getRValueReferenceType(Context.getRecordType(RD));
6132 return false;
6133 }
6134 break;
6135 }
6136
6137 case CXXInvalid:
6138 llvm_unreachable("not a special member");
6139 }
6140
Richard Smith92f241f2012-12-08 02:53:02 +00006141 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
6142 if (Diagnose)
6143 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
6144 diag::note_nontrivial_default_arg)
6145 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
6146 return false;
6147 }
6148 if (MD->isVariadic()) {
6149 if (Diagnose)
6150 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
6151 return false;
6152 }
6153
6154 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
6155 // A copy/move [constructor or assignment operator] is trivial if
6156 // -- the [member] selected to copy/move each direct base class subobject
6157 // is trivial
6158 //
6159 // C++11 [class.copy]p12, C++11 [class.copy]p25:
6160 // A [default constructor or destructor] is trivial if
6161 // -- all the direct base classes have trivial [default constructors or
6162 // destructors]
Aaron Ballman574705e2014-03-13 15:41:46 +00006163 for (const auto &BI : RD->bases())
6164 if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(),
Richard Smith41c35d62013-11-27 03:39:20 +00006165 ConstArg, CSM, TSK_BaseClass, Diagnose))
Richard Smith92f241f2012-12-08 02:53:02 +00006166 return false;
6167
6168 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
6169 // A copy/move [constructor or assignment operator] for a class X is
6170 // trivial if
6171 // -- for each non-static data member of X that is of class type (or array
6172 // thereof), the constructor selected to copy/move that member is
6173 // trivial
6174 //
6175 // C++11 [class.copy]p12, C++11 [class.copy]p25:
6176 // A [default constructor or destructor] is trivial if
6177 // -- for all of the non-static data members of its class that are of class
6178 // type (or array thereof), each such class has a trivial [default
6179 // constructor or destructor]
6180 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
6181 return false;
6182
6183 // C++11 [class.dtor]p5:
6184 // A destructor is trivial if [...]
6185 // -- the destructor is not virtual
6186 if (CSM == CXXDestructor && MD->isVirtual()) {
6187 if (Diagnose)
6188 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
6189 return false;
6190 }
6191
6192 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
6193 // A [special member] for class X is trivial if [...]
6194 // -- class X has no virtual functions and no virtual base classes
6195 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
6196 if (!Diagnose)
6197 return false;
6198
6199 if (RD->getNumVBases()) {
6200 // Check for virtual bases. We already know that the corresponding
6201 // member in all bases is trivial, so vbases must all be direct.
6202 CXXBaseSpecifier &BS = *RD->vbases_begin();
6203 assert(BS.isVirtual());
6204 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
6205 return false;
6206 }
6207
6208 // Must have a virtual method.
Aaron Ballman2b124d12014-03-13 16:36:16 +00006209 for (const auto *MI : RD->methods()) {
Richard Smith92f241f2012-12-08 02:53:02 +00006210 if (MI->isVirtual()) {
6211 SourceLocation MLoc = MI->getLocStart();
6212 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
6213 return false;
6214 }
6215 }
6216
6217 llvm_unreachable("dynamic class with no vbases and no virtual functions");
6218 }
6219
6220 // Looks like it's trivial!
6221 return true;
6222}
6223
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006224/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramer024e6192011-03-04 13:12:48 +00006225namespace {
6226 struct FindHiddenVirtualMethodData {
6227 Sema *S;
6228 CXXMethodDecl *Method;
6229 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006230 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramer024e6192011-03-04 13:12:48 +00006231 };
6232}
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006233
David Blaikie282c92a2012-10-19 00:53:08 +00006234/// \brief Check whether any most overriden method from MD in Methods
6235static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
Craig Topper4dd9b432014-08-17 23:49:53 +00006236 const llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
David Blaikie282c92a2012-10-19 00:53:08 +00006237 if (MD->size_overridden_methods() == 0)
6238 return Methods.count(MD->getCanonicalDecl());
6239 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6240 E = MD->end_overridden_methods();
6241 I != E; ++I)
6242 if (CheckMostOverridenMethods(*I, Methods))
6243 return true;
6244 return false;
6245}
6246
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006247/// \brief Member lookup function that determines whether a given C++
6248/// method overloads virtual methods in a base class without overriding any,
6249/// to be used with CXXRecordDecl::lookupInBases().
6250static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
6251 CXXBasePath &Path,
6252 void *UserData) {
6253 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
6254
6255 FindHiddenVirtualMethodData &Data
6256 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
6257
6258 DeclarationName Name = Data.Method->getDeclName();
6259 assert(Name.getNameKind() == DeclarationName::Identifier);
6260
6261 bool foundSameNameMethod = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006262 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006263 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikieff7d47a2012-12-19 00:45:41 +00006264 !Path.Decls.empty();
6265 Path.Decls = Path.Decls.slice(1)) {
6266 NamedDecl *D = Path.Decls.front();
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006267 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00006268 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006269 foundSameNameMethod = true;
6270 // Interested only in hidden virtual methods.
6271 if (!MD->isVirtual())
6272 continue;
6273 // If the method we are checking overrides a method from its base
Aaron Ballman04559a72014-07-30 23:50:53 +00006274 // don't warn about the other overloaded methods. Clang deviates from GCC
6275 // by only diagnosing overloads of inherited virtual functions that do not
6276 // override any other virtual functions in the base. GCC's
6277 // -Woverloaded-virtual diagnoses any derived function hiding a virtual
6278 // function from a base class. These cases may be better served by a
6279 // warning (not specific to virtual functions) on call sites when the call
6280 // would select a different function from the base class, were it visible.
6281 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006282 if (!Data.S->IsOverload(Data.Method, MD, false))
6283 return true;
6284 // Collect the overload only if its hidden.
David Blaikie282c92a2012-10-19 00:53:08 +00006285 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006286 overloadedMethods.push_back(MD);
6287 }
6288 }
6289
6290 if (foundSameNameMethod)
6291 Data.OverloadedMethods.append(overloadedMethods.begin(),
6292 overloadedMethods.end());
6293 return foundSameNameMethod;
6294}
6295
David Blaikie282c92a2012-10-19 00:53:08 +00006296/// \brief Add the most overriden methods from MD to Methods
6297static void AddMostOverridenMethods(const CXXMethodDecl *MD,
Craig Topper4dd9b432014-08-17 23:49:53 +00006298 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
David Blaikie282c92a2012-10-19 00:53:08 +00006299 if (MD->size_overridden_methods() == 0)
6300 Methods.insert(MD->getCanonicalDecl());
6301 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6302 E = MD->end_overridden_methods();
6303 I != E; ++I)
6304 AddMostOverridenMethods(*I, Methods);
6305}
6306
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006307/// \brief Check if a method overloads virtual methods in a base class without
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006308/// overriding any.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006309void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
6310 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
Benjamin Kramer1458c1c2012-05-19 16:03:58 +00006311 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006312 return;
6313
6314 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
6315 /*bool RecordPaths=*/false,
6316 /*bool DetectVirtual=*/false);
6317 FindHiddenVirtualMethodData Data;
6318 Data.Method = MD;
6319 Data.S = this;
6320
6321 // Keep the base methods that were overriden or introduced in the subclass
6322 // by 'using' in a set. A base method not in this set is hidden.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006323 CXXRecordDecl *DC = MD->getParent();
David Blaikieff7d47a2012-12-19 00:45:41 +00006324 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
6325 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
6326 NamedDecl *ND = *I;
6327 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
David Blaikie282c92a2012-10-19 00:53:08 +00006328 ND = shad->getTargetDecl();
6329 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
6330 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006331 }
6332
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006333 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths))
6334 OverloadedMethods = Data.OverloadedMethods;
6335}
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006336
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006337void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
6338 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
6339 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
6340 CXXMethodDecl *overloadedMD = OverloadedMethods[i];
6341 PartialDiagnostic PD = PDiag(
6342 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
6343 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
6344 Diag(overloadedMD->getLocation(), PD);
6345 }
6346}
6347
6348/// \brief Diagnose methods which overload virtual methods in a base class
6349/// without overriding any.
6350void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
6351 if (MD->isInvalidDecl())
6352 return;
6353
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00006354 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006355 return;
6356
6357 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
6358 FindHiddenVirtualMethods(MD, OverloadedMethods);
6359 if (!OverloadedMethods.empty()) {
6360 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
6361 << MD << (OverloadedMethods.size() > 1);
6362
6363 NoteHiddenVirtualMethods(MD, OverloadedMethods);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006364 }
Douglas Gregorc99f1552009-12-03 18:33:45 +00006365}
6366
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00006367void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCall48871652010-08-21 09:40:31 +00006368 Decl *TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00006369 SourceLocation LBrac,
Douglas Gregorc48a10d2010-03-29 14:42:08 +00006370 SourceLocation RBrac,
6371 AttributeList *AttrList) {
Douglas Gregor71a57182009-06-22 23:20:33 +00006372 if (!TagDecl)
6373 return;
Mike Stump11289f42009-09-09 15:08:12 +00006374
Douglas Gregorc9f9b862009-05-11 19:58:34 +00006375 AdjustDeclIfTemplate(TagDecl);
Douglas Gregorc99f1552009-12-03 18:33:45 +00006376
Rafael Espindola06e1b132012-07-12 04:32:30 +00006377 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
6378 if (l->getKind() != AttributeList::AT_Visibility)
6379 continue;
6380 l->setInvalid();
6381 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
6382 l->getName();
6383 }
6384
David Blaikie751c5582011-09-22 02:58:26 +00006385 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCall48871652010-08-21 09:40:31 +00006386 // strict aliasing violation!
6387 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie751c5582011-09-22 02:58:26 +00006388 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor463421d2009-03-03 04:44:36 +00006389
Douglas Gregor0be31a22010-07-02 17:43:08 +00006390 CheckCompletedCXXClass(
John McCall48871652010-08-21 09:40:31 +00006391 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00006392}
6393
Douglas Gregor05379422008-11-03 17:51:48 +00006394/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
6395/// special functions, such as the default constructor, copy
6396/// constructor, or destructor, to the given C++ class (C++
6397/// [special]p1). This routine can only be executed just before the
6398/// definition of the class is complete.
Douglas Gregor0be31a22010-07-02 17:43:08 +00006399void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00006400 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00006401 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00006402
Richard Smith6b02d462012-12-08 08:32:28 +00006403 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00006404 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00006405
Richard Smith6b02d462012-12-08 08:32:28 +00006406 // If the properties or semantics of the copy constructor couldn't be
6407 // determined while the class was being declared, force a declaration
6408 // of it now.
6409 if (ClassDecl->needsOverloadResolutionForCopyConstructor())
6410 DeclareImplicitCopyConstructor(ClassDecl);
6411 }
6412
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006413 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
Richard Smith966c1fb2011-12-24 21:56:24 +00006414 ++ASTContext::NumImplicitMoveConstructors;
6415
Richard Smith6b02d462012-12-08 08:32:28 +00006416 if (ClassDecl->needsOverloadResolutionForMoveConstructor())
6417 DeclareImplicitMoveConstructor(ClassDecl);
6418 }
6419
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006420 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
6421 ++ASTContext::NumImplicitCopyAssignmentOperators;
Richard Smith6b02d462012-12-08 08:32:28 +00006422
6423 // If we have a dynamic class, then the copy assignment operator may be
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006424 // virtual, so we have to declare it immediately. This ensures that, e.g.,
Richard Smith6b02d462012-12-08 08:32:28 +00006425 // it shows up in the right place in the vtable and that we diagnose
6426 // problems with the implicit exception specification.
6427 if (ClassDecl->isDynamicClass() ||
6428 ClassDecl->needsOverloadResolutionForCopyAssignment())
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006429 DeclareImplicitCopyAssignment(ClassDecl);
6430 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00006431
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006432 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smith966c1fb2011-12-24 21:56:24 +00006433 ++ASTContext::NumImplicitMoveAssignmentOperators;
6434
6435 // Likewise for the move assignment operator.
Richard Smith6b02d462012-12-08 08:32:28 +00006436 if (ClassDecl->isDynamicClass() ||
6437 ClassDecl->needsOverloadResolutionForMoveAssignment())
Richard Smith966c1fb2011-12-24 21:56:24 +00006438 DeclareImplicitMoveAssignment(ClassDecl);
6439 }
6440
Douglas Gregor7454c562010-07-02 20:37:36 +00006441 if (!ClassDecl->hasUserDeclaredDestructor()) {
6442 ++ASTContext::NumImplicitDestructors;
Richard Smith6b02d462012-12-08 08:32:28 +00006443
6444 // If we have a dynamic class, then the destructor may be virtual, so we
Douglas Gregor7454c562010-07-02 20:37:36 +00006445 // have to declare the destructor immediately. This ensures that, e.g., it
6446 // shows up in the right place in the vtable and that we diagnose problems
6447 // with the implicit exception specification.
Richard Smith6b02d462012-12-08 08:32:28 +00006448 if (ClassDecl->isDynamicClass() ||
6449 ClassDecl->needsOverloadResolutionForDestructor())
Douglas Gregor7454c562010-07-02 20:37:36 +00006450 DeclareImplicitDestructor(ClassDecl);
6451 }
Douglas Gregor05379422008-11-03 17:51:48 +00006452}
6453
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00006454unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Francois Pichet1c229c02011-04-22 22:18:13 +00006455 if (!D)
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00006456 return 0;
Francois Pichet1c229c02011-04-22 22:18:13 +00006457
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00006458 // The order of template parameters is not important here. All names
6459 // get added to the same scope.
6460 SmallVector<TemplateParameterList *, 4> ParameterLists;
6461
6462 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
6463 D = TD->getTemplatedDecl();
6464
6465 if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
6466 ParameterLists.push_back(PSD->getTemplateParameters());
6467
6468 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
6469 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
6470 ParameterLists.push_back(DD->getTemplateParameterList(i));
6471
6472 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6473 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
6474 ParameterLists.push_back(FTD->getTemplateParameters());
6475 }
6476 }
6477
6478 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
6479 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
6480 ParameterLists.push_back(TD->getTemplateParameterList(i));
6481
6482 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
6483 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
6484 ParameterLists.push_back(CTD->getTemplateParameters());
6485 }
6486 }
6487
6488 unsigned Count = 0;
6489 for (TemplateParameterList *Params : ParameterLists) {
6490 if (Params->size() > 0)
6491 // Ignore explicit specializations; they don't contribute to the template
6492 // depth.
6493 ++Count;
6494 for (NamedDecl *Param : *Params) {
6495 if (Param->getDeclName()) {
6496 S->AddDecl(Param);
6497 IdResolver.AddDecl(Param);
Francois Pichet1c229c02011-04-22 22:18:13 +00006498 }
6499 }
6500 }
Francois Pichet1c229c02011-04-22 22:18:13 +00006501
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00006502 return Count;
Douglas Gregore44a2ad2009-05-27 23:11:45 +00006503}
6504
John McCall48871652010-08-21 09:40:31 +00006505void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00006506 if (!RecordD) return;
6507 AdjustDeclIfTemplate(RecordD);
John McCall48871652010-08-21 09:40:31 +00006508 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall6df5fef2009-12-19 10:49:29 +00006509 PushDeclContext(S, Record);
6510}
6511
John McCall48871652010-08-21 09:40:31 +00006512void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00006513 if (!RecordD) return;
6514 PopDeclContext();
6515}
6516
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006517/// This is used to implement the constant expression evaluation part of the
6518/// attribute enable_if extension. There is nothing in standard C++ which would
6519/// require reentering parameters.
6520void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
6521 if (!Param)
6522 return;
6523
6524 S->AddDecl(Param);
6525 if (Param->getDeclName())
6526 IdResolver.AddDecl(Param);
6527}
6528
Douglas Gregor4d87df52008-12-16 21:30:33 +00006529/// ActOnStartDelayedCXXMethodDeclaration - We have completed
6530/// parsing a top-level (non-nested) C++ class, and we are now
6531/// parsing those parts of the given Method declaration that could
6532/// not be parsed earlier (C++ [class.mem]p2), such as default
6533/// arguments. This action should enter the scope of the given
6534/// Method declaration as if we had just parsed the qualified method
6535/// name. However, it should not bring the parameters into scope;
6536/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCall48871652010-08-21 09:40:31 +00006537void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00006538}
6539
6540/// ActOnDelayedCXXMethodParameter - We've already started a delayed
6541/// C++ method declaration. We're (re-)introducing the given
6542/// function parameter into scope for use in parsing later parts of
6543/// the method declaration. For example, we could see an
6544/// ActOnParamDefaultArgument event for this parameter.
John McCall48871652010-08-21 09:40:31 +00006545void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00006546 if (!ParamD)
6547 return;
Mike Stump11289f42009-09-09 15:08:12 +00006548
John McCall48871652010-08-21 09:40:31 +00006549 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor58354032008-12-24 00:01:03 +00006550
6551 // If this parameter has an unparsed default argument, clear it out
6552 // to make way for the parsed default argument.
6553 if (Param->hasUnparsedDefaultArg())
Craig Topperc3ec1492014-05-26 06:22:03 +00006554 Param->setDefaultArg(nullptr);
Douglas Gregor58354032008-12-24 00:01:03 +00006555
John McCall48871652010-08-21 09:40:31 +00006556 S->AddDecl(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006557 if (Param->getDeclName())
6558 IdResolver.AddDecl(Param);
6559}
6560
6561/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
6562/// processing the delayed method declaration for Method. The method
6563/// declaration is now considered finished. There may be a separate
6564/// ActOnStartOfFunctionDef action later (not necessarily
6565/// immediately!) for this method, if it was also defined inside the
6566/// class body.
John McCall48871652010-08-21 09:40:31 +00006567void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00006568 if (!MethodD)
6569 return;
Mike Stump11289f42009-09-09 15:08:12 +00006570
Douglas Gregorc8c277a2009-08-24 11:57:43 +00006571 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00006572
John McCall48871652010-08-21 09:40:31 +00006573 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006574
6575 // Now that we have our default arguments, check the constructor
6576 // again. It could produce additional diagnostics or affect whether
6577 // the class has implicitly-declared destructors, among other
6578 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006579 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
6580 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006581
6582 // Check the default arguments, which we may have added.
6583 if (!Method->isInvalidDecl())
6584 CheckCXXDefaultArguments(Method);
6585}
6586
Douglas Gregor831c93f2008-11-05 20:51:48 +00006587/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00006588/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00006589/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00006590/// emit diagnostics and set the invalid bit to true. In any case, the type
6591/// will be updated to reflect a well-formed type for the constructor and
6592/// returned.
6593QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00006594 StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006595 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006596
6597 // C++ [class.ctor]p3:
6598 // A constructor shall not be virtual (10.3) or static (9.4). A
6599 // constructor can be invoked for a const, volatile or const
6600 // volatile object. A constructor shall not be declared const,
6601 // volatile, or const volatile (9.3.2).
6602 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00006603 if (!D.isInvalidType())
6604 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6605 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
6606 << SourceRange(D.getIdentifierLoc());
6607 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006608 }
John McCall8e7d6562010-08-26 03:08:43 +00006609 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00006610 if (!D.isInvalidType())
6611 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6612 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6613 << SourceRange(D.getIdentifierLoc());
6614 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00006615 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00006616 }
Mike Stump11289f42009-09-09 15:08:12 +00006617
David Majnemer03f705f2014-07-08 18:18:04 +00006618 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
6619 diagnoseIgnoredQualifiers(
6620 diag::err_constructor_return_type, TypeQuals, SourceLocation(),
6621 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
6622 D.getDeclSpec().getRestrictSpecLoc(),
6623 D.getDeclSpec().getAtomicSpecLoc());
6624 D.setInvalidType();
6625 }
6626
Abramo Bagnara924a8f32010-12-10 16:29:40 +00006627 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00006628 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00006629 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00006630 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6631 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006632 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00006633 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6634 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006635 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00006636 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6637 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalldb40c7f2010-12-14 08:05:40 +00006638 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006639 }
Mike Stump11289f42009-09-09 15:08:12 +00006640
Douglas Gregordb9d6642011-01-26 05:01:58 +00006641 // C++0x [class.ctor]p4:
6642 // A constructor shall not be declared with a ref-qualifier.
6643 if (FTI.hasRefQualifier()) {
6644 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
6645 << FTI.RefQualifierIsLValueRef
6646 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6647 D.setInvalidType();
6648 }
6649
Douglas Gregor831c93f2008-11-05 20:51:48 +00006650 // Rebuild the function type "R" without any type qualifiers (in
6651 // case any of the errors above fired) and with "void" as the
Douglas Gregor95755162010-07-01 05:10:53 +00006652 // return type, since constructors don't have return types.
John McCall9dd450b2009-09-21 23:43:11 +00006653 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +00006654 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
John McCalldb40c7f2010-12-14 08:05:40 +00006655 return R;
6656
6657 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6658 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00006659 EPI.RefQualifier = RQ_None;
Alp Toker9cacbab2014-01-20 20:26:09 +00006660
6661 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00006662}
6663
Douglas Gregor4d87df52008-12-16 21:30:33 +00006664/// CheckConstructor - Checks a fully-formed constructor for
6665/// well-formedness, issuing any diagnostics required. Returns true if
6666/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006667void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00006668 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00006669 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
6670 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006671 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00006672
6673 // C++ [class.copy]p3:
6674 // A declaration of a constructor for a class X is ill-formed if
6675 // its first parameter is of type (optionally cv-qualified) X and
6676 // either there are no other parameters or else all other
6677 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00006678 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00006679 ((Constructor->getNumParams() == 1) ||
6680 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00006681 Constructor->getParamDecl(1)->hasDefaultArg())) &&
6682 Constructor->getTemplateSpecializationKind()
6683 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00006684 QualType ParamType = Constructor->getParamDecl(0)->getType();
6685 QualType ClassTy = Context.getTagDeclType(ClassDecl);
6686 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00006687 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregorfd42e952010-05-27 21:28:21 +00006688 const char *ConstRef
6689 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
6690 : " const &";
Douglas Gregor170512f2009-04-01 23:51:29 +00006691 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregorfd42e952010-05-27 21:28:21 +00006692 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregorffe14e32009-11-14 01:20:54 +00006693
6694 // FIXME: Rather that making the constructor invalid, we should endeavor
6695 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006696 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00006697 }
6698 }
Douglas Gregor4d87df52008-12-16 21:30:33 +00006699}
6700
John McCalldeb646e2010-08-04 01:04:25 +00006701/// CheckDestructor - Checks a fully-formed destructor definition for
6702/// well-formedness, issuing any diagnostics required. Returns true
6703/// on error.
Anders Carlssonf98849e2009-12-02 17:15:43 +00006704bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00006705 CXXRecordDecl *RD = Destructor->getParent();
6706
Peter Collingbourneb289fe62013-05-20 14:12:25 +00006707 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00006708 SourceLocation Loc;
6709
6710 if (!Destructor->isImplicit())
6711 Loc = Destructor->getLocation();
6712 else
6713 Loc = RD->getLocation();
6714
6715 // If we have a virtual destructor, look up the deallocation function
Craig Topperc3ec1492014-05-26 06:22:03 +00006716 FunctionDecl *OperatorDelete = nullptr;
Anders Carlsson2a50e952009-11-15 22:49:34 +00006717 DeclarationName Name =
6718 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlssonf98849e2009-12-02 17:15:43 +00006719 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson26a807d2009-11-30 21:24:50 +00006720 return true;
Richard Smithf03bd302013-12-05 08:30:59 +00006721 // If there's no class-specific operator delete, look up the global
6722 // non-array delete.
6723 if (!OperatorDelete)
6724 OperatorDelete = FindUsualDeallocationFunction(Loc, true, Name);
John McCall1e5d75d2010-07-03 18:33:00 +00006725
Eli Friedmanfa0df832012-02-02 03:46:19 +00006726 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson26a807d2009-11-30 21:24:50 +00006727
6728 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson2a50e952009-11-15 22:49:34 +00006729 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00006730
6731 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00006732}
6733
Douglas Gregor831c93f2008-11-05 20:51:48 +00006734/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
6735/// the well-formednes of the destructor declarator @p D with type @p
6736/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00006737/// emit diagnostics and set the declarator to invalid. Even if this happens,
6738/// will be updated to reflect a well-formed type for the destructor and
6739/// returned.
Douglas Gregor95755162010-07-01 05:10:53 +00006740QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00006741 StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006742 // C++ [class.dtor]p1:
6743 // [...] A typedef-name that names a class is a class-name
6744 // (7.1.3); however, a typedef-name that names a class shall not
6745 // be used as the identifier in the declarator for a destructor
6746 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00006747 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smithdda56e42011-04-15 14:24:37 +00006748 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner38378bf2009-04-25 08:28:21 +00006749 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smithdda56e42011-04-15 14:24:37 +00006750 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00006751 else if (const TemplateSpecializationType *TST =
6752 DeclaratorType->getAs<TemplateSpecializationType>())
6753 if (TST->isTypeAlias())
6754 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6755 << DeclaratorType << 1;
Douglas Gregor831c93f2008-11-05 20:51:48 +00006756
6757 // C++ [class.dtor]p2:
6758 // A destructor is used to destroy objects of its class type. A
6759 // destructor takes no parameters, and no return type can be
6760 // specified for it (not even void). The address of a destructor
6761 // shall not be taken. A destructor shall not be static. A
6762 // destructor can be invoked for a const, volatile or const
6763 // volatile object. A destructor shall not be declared const,
6764 // volatile or const volatile (9.3.2).
John McCall8e7d6562010-08-26 03:08:43 +00006765 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00006766 if (!D.isInvalidType())
6767 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
6768 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregor95755162010-07-01 05:10:53 +00006769 << SourceRange(D.getIdentifierLoc())
6770 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6771
John McCall8e7d6562010-08-26 03:08:43 +00006772 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00006773 }
David Majnemer03f705f2014-07-08 18:18:04 +00006774 if (!D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006775 // Destructors don't have return types, but the parser will
6776 // happily parse something like:
6777 //
6778 // class X {
6779 // float ~X();
6780 // };
6781 //
6782 // The return type will be eliminated later.
David Majnemer03f705f2014-07-08 18:18:04 +00006783 if (D.getDeclSpec().hasTypeSpecifier())
6784 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
6785 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6786 << SourceRange(D.getIdentifierLoc());
6787 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
6788 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
6789 SourceLocation(),
6790 D.getDeclSpec().getConstSpecLoc(),
6791 D.getDeclSpec().getVolatileSpecLoc(),
6792 D.getDeclSpec().getRestrictSpecLoc(),
6793 D.getDeclSpec().getAtomicSpecLoc());
6794 D.setInvalidType();
6795 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00006796 }
Mike Stump11289f42009-09-09 15:08:12 +00006797
Abramo Bagnara924a8f32010-12-10 16:29:40 +00006798 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00006799 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00006800 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00006801 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6802 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006803 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00006804 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6805 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006806 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00006807 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6808 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00006809 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006810 }
6811
Douglas Gregordb9d6642011-01-26 05:01:58 +00006812 // C++0x [class.dtor]p2:
6813 // A destructor shall not be declared with a ref-qualifier.
6814 if (FTI.hasRefQualifier()) {
6815 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
6816 << FTI.RefQualifierIsLValueRef
6817 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6818 D.setInvalidType();
6819 }
6820
Douglas Gregor831c93f2008-11-05 20:51:48 +00006821 // Make sure we don't have any parameters.
Alp Toker4284c6e2014-05-11 16:05:55 +00006822 if (FTIHasNonVoidParameters(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006823 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
6824
6825 // Delete the parameters.
Alp Tokerc5350722014-02-26 22:27:52 +00006826 FTI.freeParams();
Chris Lattner38378bf2009-04-25 08:28:21 +00006827 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006828 }
6829
Mike Stump11289f42009-09-09 15:08:12 +00006830 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00006831 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006832 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00006833 D.setInvalidType();
6834 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00006835
6836 // Rebuild the function type "R" without any type qualifiers or
6837 // parameters (in case any of the errors above fired) and with
6838 // "void" as the return type, since destructors don't have return
Douglas Gregor95755162010-07-01 05:10:53 +00006839 // types.
John McCalldb40c7f2010-12-14 08:05:40 +00006840 if (!D.isInvalidType())
6841 return R;
6842
Douglas Gregor95755162010-07-01 05:10:53 +00006843 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00006844 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6845 EPI.Variadic = false;
6846 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00006847 EPI.RefQualifier = RQ_None;
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00006848 return Context.getFunctionType(Context.VoidTy, None, EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00006849}
6850
Richard Smitha865a162014-12-19 02:07:47 +00006851static void extendLeft(SourceRange &R, const SourceRange &Before) {
6852 if (Before.isInvalid())
6853 return;
6854 R.setBegin(Before.getBegin());
6855 if (R.getEnd().isInvalid())
6856 R.setEnd(Before.getEnd());
6857}
6858
6859static void extendRight(SourceRange &R, const SourceRange &After) {
6860 if (After.isInvalid())
6861 return;
6862 if (R.getBegin().isInvalid())
6863 R.setBegin(After.getBegin());
6864 R.setEnd(After.getEnd());
6865}
6866
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006867/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6868/// well-formednes of the conversion function declarator @p D with
6869/// type @p R. If there are any errors in the declarator, this routine
6870/// will emit diagnostics and return true. Otherwise, it will return
6871/// false. Either way, the type @p R will be updated to reflect a
6872/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006873void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCall8e7d6562010-08-26 03:08:43 +00006874 StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006875 // C++ [class.conv.fct]p1:
6876 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00006877 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00006878 // parameter returning conversion-type-id."
John McCall8e7d6562010-08-26 03:08:43 +00006879 if (SC == SC_Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006880 if (!D.isInvalidType())
6881 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
Eli Friedman600bc242013-06-20 20:58:02 +00006882 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6883 << D.getName().getSourceRange();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006884 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00006885 SC = SC_None;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006886 }
John McCall212fa2e2010-04-13 00:04:31 +00006887
Richard Smitha865a162014-12-19 02:07:47 +00006888 TypeSourceInfo *ConvTSI = nullptr;
6889 QualType ConvType =
6890 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
John McCall212fa2e2010-04-13 00:04:31 +00006891
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006892 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006893 // Conversion functions don't have return types, but the parser will
6894 // happily parse something like:
6895 //
6896 // class X {
6897 // float operator bool();
6898 // };
6899 //
6900 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00006901 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
6902 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6903 << SourceRange(D.getIdentifierLoc());
John McCall212fa2e2010-04-13 00:04:31 +00006904 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006905 }
6906
John McCall212fa2e2010-04-13 00:04:31 +00006907 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6908
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006909 // Make sure we don't have any parameters.
Alp Toker9cacbab2014-01-20 20:26:09 +00006910 if (Proto->getNumParams() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006911 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
6912
6913 // Delete the parameters.
Alp Tokerc5350722014-02-26 22:27:52 +00006914 D.getFunctionTypeInfo().freeParams();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006915 D.setInvalidType();
John McCall212fa2e2010-04-13 00:04:31 +00006916 } else if (Proto->isVariadic()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006917 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006918 D.setInvalidType();
6919 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006920
John McCall212fa2e2010-04-13 00:04:31 +00006921 // Diagnose "&operator bool()" and other such nonsense. This
6922 // is actually a gcc extension which we don't support.
Alp Toker314cc812014-01-25 16:55:45 +00006923 if (Proto->getReturnType() != ConvType) {
Richard Smitha865a162014-12-19 02:07:47 +00006924 bool NeedsTypedef = false;
6925 SourceRange Before, After;
6926
6927 // Walk the chunks and extract information on them for our diagnostic.
6928 bool PastFunctionChunk = false;
6929 for (auto &Chunk : D.type_objects()) {
6930 switch (Chunk.Kind) {
6931 case DeclaratorChunk::Function:
6932 if (!PastFunctionChunk) {
6933 if (Chunk.Fun.HasTrailingReturnType) {
6934 TypeSourceInfo *TRT = nullptr;
6935 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
6936 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
6937 }
6938 PastFunctionChunk = true;
6939 break;
6940 }
6941 // Fall through.
6942 case DeclaratorChunk::Array:
6943 NeedsTypedef = true;
6944 extendRight(After, Chunk.getSourceRange());
6945 break;
6946
6947 case DeclaratorChunk::Pointer:
6948 case DeclaratorChunk::BlockPointer:
6949 case DeclaratorChunk::Reference:
6950 case DeclaratorChunk::MemberPointer:
6951 extendLeft(Before, Chunk.getSourceRange());
6952 break;
6953
6954 case DeclaratorChunk::Paren:
6955 extendLeft(Before, Chunk.Loc);
6956 extendRight(After, Chunk.EndLoc);
6957 break;
6958 }
6959 }
6960
6961 SourceLocation Loc = Before.isValid() ? Before.getBegin() :
6962 After.isValid() ? After.getBegin() :
6963 D.getIdentifierLoc();
6964 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
6965 DB << Before << After;
6966
6967 if (!NeedsTypedef) {
6968 DB << /*don't need a typedef*/0;
6969
6970 // If we can provide a correct fix-it hint, do so.
6971 if (After.isInvalid() && ConvTSI) {
6972 SourceLocation InsertLoc =
6973 PP.getLocForEndOfToken(ConvTSI->getTypeLoc().getLocEnd());
6974 DB << FixItHint::CreateInsertion(InsertLoc, " ")
6975 << FixItHint::CreateInsertionFromRange(
6976 InsertLoc, CharSourceRange::getTokenRange(Before))
6977 << FixItHint::CreateRemoval(Before);
6978 }
6979 } else if (!Proto->getReturnType()->isDependentType()) {
6980 DB << /*typedef*/1 << Proto->getReturnType();
6981 } else if (getLangOpts().CPlusPlus11) {
6982 DB << /*alias template*/2 << Proto->getReturnType();
6983 } else {
6984 DB << /*might not be fixable*/3;
6985 }
6986
6987 // Recover by incorporating the other type chunks into the result type.
6988 // Note, this does *not* change the name of the function. This is compatible
6989 // with the GCC extension:
6990 // struct S { &operator int(); } s;
6991 // int &r = s.operator int(); // ok in GCC
6992 // S::operator int&() {} // error in GCC, function name is 'operator int'.
Alp Toker314cc812014-01-25 16:55:45 +00006993 ConvType = Proto->getReturnType();
John McCall212fa2e2010-04-13 00:04:31 +00006994 }
6995
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006996 // C++ [class.conv.fct]p4:
6997 // The conversion-type-id shall not represent a function type nor
6998 // an array type.
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006999 if (ConvType->isArrayType()) {
7000 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
7001 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00007002 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007003 } else if (ConvType->isFunctionType()) {
7004 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
7005 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00007006 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007007 }
7008
7009 // Rebuild the function type "R" without any parameters (in case any
7010 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00007011 // return type.
John McCalldb40c7f2010-12-14 08:05:40 +00007012 if (D.isInvalidType())
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00007013 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007014
Douglas Gregor5fb53972009-01-14 15:45:31 +00007015 // C++0x explicit conversion operators.
Richard Smith0bf8a4922011-10-18 20:49:44 +00007016 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump11289f42009-09-09 15:08:12 +00007017 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007018 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00007019 diag::warn_cxx98_compat_explicit_conversion_functions :
7020 diag::ext_explicit_conversion_functions)
Douglas Gregor5fb53972009-01-14 15:45:31 +00007021 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007022}
7023
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007024/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
7025/// the declaration of the given C++ conversion function. This routine
7026/// is responsible for recording the conversion function in the C++
7027/// class, if possible.
John McCall48871652010-08-21 09:40:31 +00007028Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007029 assert(Conversion && "Expected to receive a conversion function declaration");
7030
Douglas Gregor4287b372008-12-12 08:25:50 +00007031 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007032
7033 // Make sure we aren't redeclaring the conversion function.
7034 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007035
7036 // C++ [class.conv.fct]p1:
7037 // [...] A conversion function is never used to convert a
7038 // (possibly cv-qualified) object to the (possibly cv-qualified)
7039 // same object type (or a reference to it), to a (possibly
7040 // cv-qualified) base class of that type (or a reference to it),
7041 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00007042 // FIXME: Suppress this warning if the conversion function ends up being a
7043 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00007044 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007045 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007046 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007047 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregor6309e3d2010-09-12 07:22:28 +00007048 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
7049 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregore47191c2010-09-13 16:44:26 +00007050 /* Suppress diagnostics for instantiations. */;
Douglas Gregor6309e3d2010-09-12 07:22:28 +00007051 else if (ConvType->isRecordType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007052 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
7053 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00007054 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007055 << ClassType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007056 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00007057 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007058 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007059 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00007060 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007061 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007062 }
7063
Douglas Gregor457104e2010-09-29 04:25:11 +00007064 if (FunctionTemplateDecl *ConversionTemplate
7065 = Conversion->getDescribedFunctionTemplate())
7066 return ConversionTemplate;
7067
John McCall48871652010-08-21 09:40:31 +00007068 return Conversion;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007069}
7070
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007071//===----------------------------------------------------------------------===//
7072// Namespace Handling
7073//===----------------------------------------------------------------------===//
7074
Richard Smith45bb8852012-10-04 22:13:39 +00007075/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
7076/// reopened.
7077static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
7078 SourceLocation Loc,
7079 IdentifierInfo *II, bool *IsInline,
7080 NamespaceDecl *PrevNS) {
7081 assert(*IsInline != PrevNS->isInline());
John McCallb1be5232010-08-26 09:15:37 +00007082
Richard Smithf501cc32012-10-05 01:46:25 +00007083 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
7084 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
7085 // inline namespaces, with the intention of bringing names into namespace std.
7086 //
7087 // We support this just well enough to get that case working; this is not
7088 // sufficient to support reopening namespaces as inline in general.
Richard Smith45bb8852012-10-04 22:13:39 +00007089 if (*IsInline && II && II->getName().startswith("__atomic") &&
7090 S.getSourceManager().isInSystemHeader(Loc)) {
Richard Smithf501cc32012-10-05 01:46:25 +00007091 // Mark all prior declarations of the namespace as inline.
Richard Smith45bb8852012-10-04 22:13:39 +00007092 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
7093 NS = NS->getPreviousDecl())
7094 NS->setInline(*IsInline);
7095 // Patch up the lookup table for the containing namespace. This isn't really
7096 // correct, but it's good enough for this particular case.
Aaron Ballman629afae2014-03-07 19:56:05 +00007097 for (auto *I : PrevNS->decls())
7098 if (auto *ND = dyn_cast<NamedDecl>(I))
Richard Smith45bb8852012-10-04 22:13:39 +00007099 PrevNS->getParent()->makeDeclVisibleInContext(ND);
7100 return;
7101 }
7102
7103 if (PrevNS->isInline())
7104 // The user probably just forgot the 'inline', so suggest that it
7105 // be added back.
7106 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
7107 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
7108 else
Richard Smith5b5d21e2014-03-12 23:36:42 +00007109 S.Diag(Loc, diag::err_inline_namespace_mismatch) << *IsInline;
Richard Smith45bb8852012-10-04 22:13:39 +00007110
7111 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
7112 *IsInline = PrevNS->isInline();
7113}
John McCallb1be5232010-08-26 09:15:37 +00007114
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007115/// ActOnStartNamespaceDef - This is called at the start of a namespace
7116/// definition.
John McCall48871652010-08-21 09:40:31 +00007117Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redl67667942010-08-27 23:12:46 +00007118 SourceLocation InlineLoc,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00007119 SourceLocation NamespaceLoc,
John McCallb1be5232010-08-26 09:15:37 +00007120 SourceLocation IdentLoc,
7121 IdentifierInfo *II,
7122 SourceLocation LBrace,
7123 AttributeList *AttrList) {
Abramo Bagnarab5545be2011-03-08 12:38:20 +00007124 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
7125 // For anonymous namespace, take the location of the left brace.
7126 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregore57e7522012-01-07 09:11:48 +00007127 bool IsInline = InlineLoc.isValid();
Douglas Gregor21b3b292012-01-10 22:14:10 +00007128 bool IsInvalid = false;
Douglas Gregore57e7522012-01-07 09:11:48 +00007129 bool IsStd = false;
7130 bool AddToKnown = false;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007131 Scope *DeclRegionScope = NamespcScope->getParent();
7132
Craig Topperc3ec1492014-05-26 06:22:03 +00007133 NamespaceDecl *PrevNS = nullptr;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007134 if (II) {
7135 // C++ [namespace.def]p2:
Douglas Gregor412c3622010-10-22 15:24:46 +00007136 // The identifier in an original-namespace-definition shall not
7137 // have been previously defined in the declarative region in
7138 // which the original-namespace-definition appears. The
7139 // identifier in an original-namespace-definition is the name of
7140 // the namespace. Subsequently in that declarative region, it is
7141 // treated as an original-namespace-name.
7142 //
7143 // Since namespace names are unique in their scope, and we don't
Douglas Gregorb578fbe2011-05-06 23:28:47 +00007144 // look through using directives, just look for any ordinary names.
7145
7146 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregore57e7522012-01-07 09:11:48 +00007147 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
7148 Decl::IDNS_Namespace;
Craig Topperc3ec1492014-05-26 06:22:03 +00007149 NamedDecl *PrevDecl = nullptr;
David Blaikieff7d47a2012-12-19 00:45:41 +00007150 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
7151 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
7152 ++I) {
7153 if ((*I)->getIdentifierNamespace() & IDNS) {
7154 PrevDecl = *I;
Douglas Gregorb578fbe2011-05-06 23:28:47 +00007155 break;
7156 }
7157 }
7158
Douglas Gregore57e7522012-01-07 09:11:48 +00007159 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
7160
7161 if (PrevNS) {
Douglas Gregor91f84212008-12-11 16:49:14 +00007162 // This is an extended namespace definition.
Richard Smith45bb8852012-10-04 22:13:39 +00007163 if (IsInline != PrevNS->isInline())
7164 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
7165 &IsInline, PrevNS);
Douglas Gregor91f84212008-12-11 16:49:14 +00007166 } else if (PrevDecl) {
7167 // This is an invalid name redefinition.
Douglas Gregore57e7522012-01-07 09:11:48 +00007168 Diag(Loc, diag::err_redefinition_different_kind)
7169 << II;
Douglas Gregor91f84212008-12-11 16:49:14 +00007170 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor21b3b292012-01-10 22:14:10 +00007171 IsInvalid = true;
Douglas Gregor91f84212008-12-11 16:49:14 +00007172 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregore57e7522012-01-07 09:11:48 +00007173 } else if (II->isStr("std") &&
Sebastian Redl50c68252010-08-31 00:36:30 +00007174 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00007175 // This is the first "real" definition of the namespace "std", so update
7176 // our cache of the "std" namespace to point at this definition.
Douglas Gregore57e7522012-01-07 09:11:48 +00007177 PrevNS = getStdNamespace();
7178 IsStd = true;
7179 AddToKnown = !IsInline;
7180 } else {
7181 // We've seen this namespace for the first time.
7182 AddToKnown = !IsInline;
Mike Stump11289f42009-09-09 15:08:12 +00007183 }
Douglas Gregor91f84212008-12-11 16:49:14 +00007184 } else {
John McCall4fa53422009-10-01 00:25:31 +00007185 // Anonymous namespaces.
Douglas Gregore57e7522012-01-07 09:11:48 +00007186
7187 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl50c68252010-08-31 00:36:30 +00007188 DeclContext *Parent = CurContext->getRedeclContext();
John McCall0db42252009-12-16 02:06:49 +00007189 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregore57e7522012-01-07 09:11:48 +00007190 PrevNS = TU->getAnonymousNamespace();
John McCall0db42252009-12-16 02:06:49 +00007191 } else {
7192 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregore57e7522012-01-07 09:11:48 +00007193 PrevNS = ND->getAnonymousNamespace();
John McCall0db42252009-12-16 02:06:49 +00007194 }
7195
Richard Smith45bb8852012-10-04 22:13:39 +00007196 if (PrevNS && IsInline != PrevNS->isInline())
7197 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
7198 &IsInline, PrevNS);
Douglas Gregore57e7522012-01-07 09:11:48 +00007199 }
7200
7201 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
7202 StartLoc, Loc, II, PrevNS);
Douglas Gregor21b3b292012-01-10 22:14:10 +00007203 if (IsInvalid)
7204 Namespc->setInvalidDecl();
Douglas Gregore57e7522012-01-07 09:11:48 +00007205
7206 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00007207
Douglas Gregore57e7522012-01-07 09:11:48 +00007208 // FIXME: Should we be merging attributes?
7209 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola6d65d7b2012-02-01 23:24:59 +00007210 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregore57e7522012-01-07 09:11:48 +00007211
7212 if (IsStd)
7213 StdNamespace = Namespc;
7214 if (AddToKnown)
7215 KnownNamespaces[Namespc] = false;
7216
7217 if (II) {
7218 PushOnScopeChains(Namespc, DeclRegionScope);
7219 } else {
7220 // Link the anonymous namespace into its parent.
7221 DeclContext *Parent = CurContext->getRedeclContext();
7222 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
7223 TU->setAnonymousNamespace(Namespc);
7224 } else {
7225 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall0db42252009-12-16 02:06:49 +00007226 }
John McCall4fa53422009-10-01 00:25:31 +00007227
Douglas Gregorf9f54ea2010-03-24 00:46:35 +00007228 CurContext->addDecl(Namespc);
7229
John McCall4fa53422009-10-01 00:25:31 +00007230 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
7231 // behaves as if it were replaced by
7232 // namespace unique { /* empty body */ }
7233 // using namespace unique;
7234 // namespace unique { namespace-body }
7235 // where all occurrences of 'unique' in a translation unit are
7236 // replaced by the same identifier and this identifier differs
7237 // from all other identifiers in the entire program.
7238
7239 // We just create the namespace with an empty name and then add an
7240 // implicit using declaration, just like the standard suggests.
7241 //
7242 // CodeGen enforces the "universally unique" aspect by giving all
7243 // declarations semantically contained within an anonymous
7244 // namespace internal linkage.
7245
Douglas Gregore57e7522012-01-07 09:11:48 +00007246 if (!PrevNS) {
John McCall0db42252009-12-16 02:06:49 +00007247 UsingDirectiveDecl* UD
Nick Lewycky38115822012-11-04 20:21:54 +00007248 = UsingDirectiveDecl::Create(Context, Parent,
John McCall0db42252009-12-16 02:06:49 +00007249 /* 'using' */ LBrace,
7250 /* 'namespace' */ SourceLocation(),
Douglas Gregor12441b32011-02-25 16:33:46 +00007251 /* qualifier */ NestedNameSpecifierLoc(),
John McCall0db42252009-12-16 02:06:49 +00007252 /* identifier */ SourceLocation(),
7253 Namespc,
Nick Lewycky38115822012-11-04 20:21:54 +00007254 /* Ancestor */ Parent);
John McCall0db42252009-12-16 02:06:49 +00007255 UD->setImplicit();
Nick Lewycky38115822012-11-04 20:21:54 +00007256 Parent->addDecl(UD);
John McCall0db42252009-12-16 02:06:49 +00007257 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007258 }
7259
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00007260 ActOnDocumentableDecl(Namespc);
7261
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007262 // Although we could have an invalid decl (i.e. the namespace name is a
7263 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00007264 // FIXME: We should be able to push Namespc here, so that the each DeclContext
7265 // for the namespace has the declarations that showed up in that particular
7266 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00007267 PushDeclContext(NamespcScope, Namespc);
John McCall48871652010-08-21 09:40:31 +00007268 return Namespc;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007269}
7270
Sebastian Redla6602e92009-11-23 15:34:23 +00007271/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
7272/// is a namespace alias, returns the namespace it points to.
7273static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
7274 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
7275 return AD->getNamespace();
7276 return dyn_cast_or_null<NamespaceDecl>(D);
7277}
7278
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007279/// ActOnFinishNamespaceDef - This callback is called after a namespace is
7280/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCall48871652010-08-21 09:40:31 +00007281void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007282 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
7283 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnarab5545be2011-03-08 12:38:20 +00007284 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007285 PopDeclContext();
Eli Friedman570024a2010-08-05 06:57:20 +00007286 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola6d65d7b2012-02-01 23:24:59 +00007287 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007288}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00007289
John McCall28a0cf72010-08-25 07:42:41 +00007290CXXRecordDecl *Sema::getStdBadAlloc() const {
7291 return cast_or_null<CXXRecordDecl>(
7292 StdBadAlloc.get(Context.getExternalSource()));
7293}
7294
7295NamespaceDecl *Sema::getStdNamespace() const {
7296 return cast_or_null<NamespaceDecl>(
7297 StdNamespace.get(Context.getExternalSource()));
7298}
7299
Douglas Gregorcdf87022010-06-29 17:53:46 +00007300/// \brief Retrieve the special "std" namespace, which may require us to
7301/// implicitly define the namespace.
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00007302NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregorcdf87022010-06-29 17:53:46 +00007303 if (!StdNamespace) {
7304 // The "std" namespace has not yet been defined, so build one implicitly.
7305 StdNamespace = NamespaceDecl::Create(Context,
7306 Context.getTranslationUnitDecl(),
Douglas Gregore57e7522012-01-07 09:11:48 +00007307 /*Inline=*/false,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00007308 SourceLocation(), SourceLocation(),
Douglas Gregore57e7522012-01-07 09:11:48 +00007309 &PP.getIdentifierTable().get("std"),
Craig Topperc3ec1492014-05-26 06:22:03 +00007310 /*PrevDecl=*/nullptr);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00007311 getStdNamespace()->setImplicit(true);
Douglas Gregorcdf87022010-06-29 17:53:46 +00007312 }
Eli Bendersky9a220fc2014-09-29 20:38:29 +00007313
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00007314 return getStdNamespace();
Douglas Gregorcdf87022010-06-29 17:53:46 +00007315}
7316
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007317bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007318 assert(getLangOpts().CPlusPlus &&
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007319 "Looking for std::initializer_list outside of C++.");
7320
7321 // We're looking for implicit instantiations of
7322 // template <typename E> class std::initializer_list.
7323
7324 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
7325 return false;
7326
Craig Topperc3ec1492014-05-26 06:22:03 +00007327 ClassTemplateDecl *Template = nullptr;
7328 const TemplateArgument *Arguments = nullptr;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007329
Sebastian Redl43144e72012-01-17 22:49:58 +00007330 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007331
Sebastian Redl43144e72012-01-17 22:49:58 +00007332 ClassTemplateSpecializationDecl *Specialization =
7333 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
7334 if (!Specialization)
7335 return false;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007336
Sebastian Redl43144e72012-01-17 22:49:58 +00007337 Template = Specialization->getSpecializedTemplate();
7338 Arguments = Specialization->getTemplateArgs().data();
7339 } else if (const TemplateSpecializationType *TST =
7340 Ty->getAs<TemplateSpecializationType>()) {
7341 Template = dyn_cast_or_null<ClassTemplateDecl>(
7342 TST->getTemplateName().getAsTemplateDecl());
7343 Arguments = TST->getArgs();
7344 }
7345 if (!Template)
7346 return false;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007347
7348 if (!StdInitializerList) {
7349 // Haven't recognized std::initializer_list yet, maybe this is it.
7350 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
7351 if (TemplateClass->getIdentifier() !=
7352 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redl09edce02012-01-23 22:09:39 +00007353 !getStdNamespace()->InEnclosingNamespaceSetOf(
7354 TemplateClass->getDeclContext()))
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007355 return false;
7356 // This is a template called std::initializer_list, but is it the right
7357 // template?
7358 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redl09edce02012-01-23 22:09:39 +00007359 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007360 return false;
7361 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
7362 return false;
7363
7364 // It's the right template.
7365 StdInitializerList = Template;
7366 }
7367
7368 if (Template != StdInitializerList)
7369 return false;
7370
7371 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl43144e72012-01-17 22:49:58 +00007372 if (Element)
7373 *Element = Arguments[0].getAsType();
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007374 return true;
7375}
7376
Sebastian Redl42acd4a2012-01-17 22:50:08 +00007377static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
7378 NamespaceDecl *Std = S.getStdNamespace();
7379 if (!Std) {
7380 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
Craig Topperc3ec1492014-05-26 06:22:03 +00007381 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00007382 }
7383
7384 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
7385 Loc, Sema::LookupOrdinaryName);
7386 if (!S.LookupQualifiedName(Result, Std)) {
7387 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
Craig Topperc3ec1492014-05-26 06:22:03 +00007388 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00007389 }
7390 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
7391 if (!Template) {
7392 Result.suppressDiagnostics();
7393 // We found something weird. Complain about the first thing we found.
7394 NamedDecl *Found = *Result.begin();
7395 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
Craig Topperc3ec1492014-05-26 06:22:03 +00007396 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00007397 }
7398
7399 // We found some template called std::initializer_list. Now verify that it's
7400 // correct.
7401 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redl09edce02012-01-23 22:09:39 +00007402 if (Params->getMinRequiredArguments() != 1 ||
7403 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl42acd4a2012-01-17 22:50:08 +00007404 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
Craig Topperc3ec1492014-05-26 06:22:03 +00007405 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00007406 }
7407
7408 return Template;
7409}
7410
7411QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
7412 if (!StdInitializerList) {
7413 StdInitializerList = LookupStdInitializerList(*this, Loc);
7414 if (!StdInitializerList)
7415 return QualType();
7416 }
7417
7418 TemplateArgumentListInfo Args(Loc, Loc);
7419 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
7420 Context.getTrivialTypeSourceInfo(Element,
7421 Loc)));
7422 return Context.getCanonicalType(
7423 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
7424}
7425
Sebastian Redlbe24ec22012-01-17 22:50:14 +00007426bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
7427 // C++ [dcl.init.list]p2:
7428 // A constructor is an initializer-list constructor if its first parameter
7429 // is of type std::initializer_list<E> or reference to possibly cv-qualified
7430 // std::initializer_list<E> for some type E, and either there are no other
7431 // parameters or else all other parameters have default arguments.
7432 if (Ctor->getNumParams() < 1 ||
7433 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
7434 return false;
7435
7436 QualType ArgType = Ctor->getParamDecl(0)->getType();
7437 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
7438 ArgType = RT->getPointeeType().getUnqualifiedType();
7439
Craig Topperc3ec1492014-05-26 06:22:03 +00007440 return isStdInitializerList(ArgType, nullptr);
Sebastian Redlbe24ec22012-01-17 22:50:14 +00007441}
7442
Douglas Gregora172e082011-03-26 22:25:30 +00007443/// \brief Determine whether a using statement is in a context where it will be
7444/// apply in all contexts.
7445static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
7446 switch (CurContext->getDeclKind()) {
7447 case Decl::TranslationUnit:
7448 return true;
7449 case Decl::LinkageSpec:
7450 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
7451 default:
7452 return false;
7453 }
7454}
7455
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00007456namespace {
7457
7458// Callback to only accept typo corrections that are namespaces.
7459class NamespaceValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007460public:
Craig Toppera798a9d2014-03-02 09:32:10 +00007461 bool ValidateCandidate(const TypoCorrection &candidate) override {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007462 if (NamedDecl *ND = candidate.getCorrectionDecl())
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00007463 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00007464 return false;
7465 }
7466};
7467
7468}
7469
Douglas Gregorc2fa1692011-06-28 16:20:02 +00007470static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
7471 CXXScopeSpec &SS,
7472 SourceLocation IdentLoc,
7473 IdentifierInfo *Ident) {
7474 R.clear();
Kaelyn Takata89c881b2014-10-27 18:07:29 +00007475 if (TypoCorrection Corrected =
7476 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS,
7477 llvm::make_unique<NamespaceValidatorCCC>(),
7478 Sema::CTK_ErrorRecovery)) {
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00007479 if (DeclContext *DC = S.computeDeclContext(SS, false)) {
Richard Smithf9b15102013-08-17 00:46:16 +00007480 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
7481 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00007482 Ident->getName().equals(CorrectedStr);
Richard Smithf9b15102013-08-17 00:46:16 +00007483 S.diagnoseTypo(Corrected,
7484 S.PDiag(diag::err_using_directive_member_suggest)
7485 << Ident << DC << DroppedSpecifier << SS.getRange(),
7486 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00007487 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00007488 S.diagnoseTypo(Corrected,
7489 S.PDiag(diag::err_using_directive_suggest) << Ident,
7490 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00007491 }
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00007492 R.addDecl(Corrected.getCorrectionDecl());
7493 return true;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00007494 }
7495 return false;
7496}
7497
John McCall48871652010-08-21 09:40:31 +00007498Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattner83f095c2009-03-28 19:18:32 +00007499 SourceLocation UsingLoc,
7500 SourceLocation NamespcLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00007501 CXXScopeSpec &SS,
Chris Lattner83f095c2009-03-28 19:18:32 +00007502 SourceLocation IdentLoc,
7503 IdentifierInfo *NamespcName,
7504 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00007505 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
7506 assert(NamespcName && "Invalid NamespcName.");
7507 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall9b72f892010-11-10 02:40:36 +00007508
7509 // This can only happen along a recovery path.
7510 while (S->getFlags() & Scope::TemplateParamScope)
7511 S = S->getParent();
Douglas Gregor889ceb72009-02-03 19:21:40 +00007512 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00007513
Craig Topperc3ec1492014-05-26 06:22:03 +00007514 UsingDirectiveDecl *UDir = nullptr;
7515 NestedNameSpecifier *Qualifier = nullptr;
Douglas Gregorcdf87022010-06-29 17:53:46 +00007516 if (SS.isSet())
Aaron Ballman4a979672014-01-03 13:56:08 +00007517 Qualifier = SS.getScopeRep();
Douglas Gregorcdf87022010-06-29 17:53:46 +00007518
Douglas Gregor34074322009-01-14 22:20:51 +00007519 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00007520 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
7521 LookupParsedName(R, S, &SS);
7522 if (R.isAmbiguous())
Craig Topperc3ec1492014-05-26 06:22:03 +00007523 return nullptr;
John McCall27b18f82009-11-17 02:14:36 +00007524
Douglas Gregorcdf87022010-06-29 17:53:46 +00007525 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00007526 R.clear();
Douglas Gregorcdf87022010-06-29 17:53:46 +00007527 // Allow "using namespace std;" or "using namespace ::std;" even if
7528 // "std" hasn't been defined yet, for GCC compatibility.
7529 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
7530 NamespcName->isStr("std")) {
7531 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00007532 R.addDecl(getOrCreateStdNamespace());
Douglas Gregorcdf87022010-06-29 17:53:46 +00007533 R.resolveKind();
7534 }
7535 // Otherwise, attempt typo correction.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00007536 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregorcdf87022010-06-29 17:53:46 +00007537 }
7538
John McCall9f3059a2009-10-09 21:13:30 +00007539 if (!R.empty()) {
Sebastian Redla6602e92009-11-23 15:34:23 +00007540 NamedDecl *Named = R.getFoundDecl();
7541 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
7542 && "expected namespace decl");
Aaron Ballman43f40102014-11-14 22:34:56 +00007543
Nico Riecke50e59a2014-11-24 17:29:52 +00007544 // The use of a nested name specifier may trigger deprecation warnings.
7545 DiagnoseUseOfDecl(Named, IdentLoc);
Aaron Ballman43f40102014-11-14 22:34:56 +00007546
Douglas Gregor889ceb72009-02-03 19:21:40 +00007547 // C++ [namespace.udir]p1:
7548 // A using-directive specifies that the names in the nominated
7549 // namespace can be used in the scope in which the
7550 // using-directive appears after the using-directive. During
7551 // unqualified name lookup (3.4.1), the names appear as if they
7552 // were declared in the nearest enclosing namespace which
7553 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00007554 // namespace. [Note: in this context, "contains" means "contains
7555 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00007556
7557 // Find enclosing context containing both using-directive and
7558 // nominated namespace.
Sebastian Redla6602e92009-11-23 15:34:23 +00007559 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor889ceb72009-02-03 19:21:40 +00007560 DeclContext *CommonAncestor = cast<DeclContext>(NS);
7561 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
7562 CommonAncestor = CommonAncestor->getParent();
7563
Sebastian Redla6602e92009-11-23 15:34:23 +00007564 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor12441b32011-02-25 16:33:46 +00007565 SS.getWithLocInContext(Context),
Sebastian Redla6602e92009-11-23 15:34:23 +00007566 IdentLoc, Named, CommonAncestor);
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00007567
Douglas Gregora172e082011-03-26 22:25:30 +00007568 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Eli Friedman5ba37d52013-08-22 00:27:10 +00007569 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00007570 Diag(IdentLoc, diag::warn_using_directive_in_header);
7571 }
7572
Douglas Gregor889ceb72009-02-03 19:21:40 +00007573 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00007574 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00007575 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00007576 }
7577
Richard Smith54ecd982013-02-20 19:22:51 +00007578 if (UDir)
7579 ProcessDeclAttributeList(S, UDir, AttrList);
7580
John McCall48871652010-08-21 09:40:31 +00007581 return UDir;
Douglas Gregor889ceb72009-02-03 19:21:40 +00007582}
7583
7584void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith05afe5e2012-03-13 03:12:56 +00007585 // If the scope has an associated entity and the using directive is at
7586 // namespace or translation unit scope, add the UsingDirectiveDecl into
7587 // its lookup structure so qualified name lookup can find it.
Ted Kremenekc37877d2013-10-08 17:08:03 +00007588 DeclContext *Ctx = S->getEntity();
Richard Smith05afe5e2012-03-13 03:12:56 +00007589 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00007590 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00007591 else
Yaron Keren065da7c2014-05-20 18:23:05 +00007592 // Otherwise, it is at block scope. The using-directives will affect lookup
Richard Smith05afe5e2012-03-13 03:12:56 +00007593 // only to the end of the scope.
John McCall48871652010-08-21 09:40:31 +00007594 S->PushUsingDirective(UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00007595}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00007596
Douglas Gregorfec52632009-06-20 00:51:54 +00007597
John McCall48871652010-08-21 09:40:31 +00007598Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall9b72f892010-11-10 02:40:36 +00007599 AccessSpecifier AS,
7600 bool HasUsingKeyword,
7601 SourceLocation UsingLoc,
7602 CXXScopeSpec &SS,
7603 UnqualifiedId &Name,
7604 AttributeList *AttrList,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007605 bool HasTypenameKeyword,
John McCall9b72f892010-11-10 02:40:36 +00007606 SourceLocation TypenameLoc) {
Douglas Gregorfec52632009-06-20 00:51:54 +00007607 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00007608
Douglas Gregor220f4272009-11-04 16:30:06 +00007609 switch (Name.getKind()) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00007610 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor220f4272009-11-04 16:30:06 +00007611 case UnqualifiedId::IK_Identifier:
7612 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00007613 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00007614 case UnqualifiedId::IK_ConversionFunctionId:
7615 break;
7616
7617 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor9de54ea2010-01-13 17:31:36 +00007618 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smithd494c502012-04-27 19:33:05 +00007619 // C++11 inheriting constructors.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007620 Diag(Name.getLocStart(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007621 getLangOpts().CPlusPlus11 ?
Richard Smithc2bc61b2013-03-18 21:12:30 +00007622 diag::warn_cxx98_compat_using_decl_constructor :
Richard Smith0bf8a4922011-10-18 20:49:44 +00007623 diag::err_using_decl_constructor)
7624 << SS.getRange();
7625
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007626 if (getLangOpts().CPlusPlus11) break;
John McCall3969e302009-12-08 07:46:18 +00007627
Craig Topperc3ec1492014-05-26 06:22:03 +00007628 return nullptr;
7629
Douglas Gregor220f4272009-11-04 16:30:06 +00007630 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007631 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor220f4272009-11-04 16:30:06 +00007632 << SS.getRange();
Craig Topperc3ec1492014-05-26 06:22:03 +00007633 return nullptr;
7634
Douglas Gregor220f4272009-11-04 16:30:06 +00007635 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007636 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor220f4272009-11-04 16:30:06 +00007637 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00007638 return nullptr;
Douglas Gregor220f4272009-11-04 16:30:06 +00007639 }
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007640
7641 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
7642 DeclarationName TargetName = TargetNameInfo.getName();
John McCall3969e302009-12-08 07:46:18 +00007643 if (!TargetName)
Craig Topperc3ec1492014-05-26 06:22:03 +00007644 return nullptr;
John McCall3969e302009-12-08 07:46:18 +00007645
Richard Smithc2bc61b2013-03-18 21:12:30 +00007646 // Warn about access declarations.
John McCalla0097262009-12-11 02:10:03 +00007647 if (!HasUsingKeyword) {
Enea Zaffanellac70b2512013-07-17 17:28:56 +00007648 Diag(Name.getLocStart(),
Richard Smithf026b602013-06-13 02:12:17 +00007649 getLangOpts().CPlusPlus11 ? diag::err_access_decl
7650 : diag::warn_access_decl_deprecated)
Douglas Gregora771f462010-03-31 17:46:05 +00007651 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCalla0097262009-12-11 02:10:03 +00007652 }
7653
Douglas Gregorc4356532010-12-16 00:46:58 +00007654 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
7655 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
Craig Topperc3ec1492014-05-26 06:22:03 +00007656 return nullptr;
Douglas Gregorc4356532010-12-16 00:46:58 +00007657
John McCall3f746822009-11-17 05:59:44 +00007658 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007659 TargetNameInfo, AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00007660 /* IsInstantiation */ false,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007661 HasTypenameKeyword, TypenameLoc);
John McCallb96ec562009-12-04 22:46:56 +00007662 if (UD)
7663 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00007664
John McCall48871652010-08-21 09:40:31 +00007665 return UD;
Anders Carlsson696a3f12009-08-28 05:40:36 +00007666}
7667
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007668/// \brief Determine whether a using declaration considers the given
7669/// declarations as "equivalent", e.g., if they are redeclarations of
7670/// the same entity or are both typedefs of the same type.
Richard Smithfd8634a2013-10-23 02:17:46 +00007671static bool
7672IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
7673 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007674 return true;
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007675
Richard Smithdda56e42011-04-15 14:24:37 +00007676 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
Richard Smithfd8634a2013-10-23 02:17:46 +00007677 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007678 return Context.hasSameType(TD1->getUnderlyingType(),
7679 TD2->getUnderlyingType());
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007680
7681 return false;
7682}
7683
7684
John McCall84d87672009-12-10 09:41:52 +00007685/// Determines whether to create a using shadow decl for a particular
7686/// decl, given the set of decls existing prior to this using lookup.
7687bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
Richard Smithfd8634a2013-10-23 02:17:46 +00007688 const LookupResult &Previous,
7689 UsingShadowDecl *&PrevShadow) {
John McCall84d87672009-12-10 09:41:52 +00007690 // Diagnose finding a decl which is not from a base class of the
7691 // current class. We do this now because there are cases where this
7692 // function will silently decide not to build a shadow decl, which
7693 // will pre-empt further diagnostics.
7694 //
7695 // We don't need to do this in C++0x because we do the check once on
7696 // the qualifier.
7697 //
7698 // FIXME: diagnose the following if we care enough:
7699 // struct A { int foo; };
7700 // struct B : A { using A::foo; };
7701 // template <class T> struct C : A {};
7702 // template <class T> struct D : C<T> { using B::foo; } // <---
7703 // This is invalid (during instantiation) in C++03 because B::foo
7704 // resolves to the using decl in B, which is not a base class of D<T>.
7705 // We can't diagnose it immediately because C<T> is an unknown
7706 // specialization. The UsingShadowDecl in D<T> then points directly
7707 // to A::foo, which will look well-formed when we instantiate.
7708 // The right solution is to not collapse the shadow-decl chain.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007709 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
John McCall84d87672009-12-10 09:41:52 +00007710 DeclContext *OrigDC = Orig->getDeclContext();
7711
7712 // Handle enums and anonymous structs.
7713 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
7714 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
7715 while (OrigRec->isAnonymousStructOrUnion())
7716 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
7717
7718 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
7719 if (OrigDC == CurContext) {
7720 Diag(Using->getLocation(),
7721 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007722 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00007723 Diag(Orig->getLocation(), diag::note_using_decl_target);
7724 return true;
7725 }
7726
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007727 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall84d87672009-12-10 09:41:52 +00007728 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007729 << Using->getQualifier()
John McCall84d87672009-12-10 09:41:52 +00007730 << cast<CXXRecordDecl>(CurContext)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007731 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00007732 Diag(Orig->getLocation(), diag::note_using_decl_target);
7733 return true;
7734 }
7735 }
7736
7737 if (Previous.empty()) return false;
7738
7739 NamedDecl *Target = Orig;
7740 if (isa<UsingShadowDecl>(Target))
7741 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7742
John McCalla17e83e2009-12-11 02:33:26 +00007743 // If the target happens to be one of the previous declarations, we
7744 // don't have a conflict.
7745 //
7746 // FIXME: but we might be increasing its access, in which case we
7747 // should redeclare it.
Craig Topperc3ec1492014-05-26 06:22:03 +00007748 NamedDecl *NonTag = nullptr, *Tag = nullptr;
Richard Smithfd8634a2013-10-23 02:17:46 +00007749 bool FoundEquivalentDecl = false;
John McCalla17e83e2009-12-11 02:33:26 +00007750 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7751 I != E; ++I) {
7752 NamedDecl *D = (*I)->getUnderlyingDecl();
Richard Smithfd8634a2013-10-23 02:17:46 +00007753 if (IsEquivalentForUsingDecl(Context, D, Target)) {
7754 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
7755 PrevShadow = Shadow;
7756 FoundEquivalentDecl = true;
7757 }
John McCalla17e83e2009-12-11 02:33:26 +00007758
7759 (isa<TagDecl>(D) ? Tag : NonTag) = D;
7760 }
7761
Richard Smithfd8634a2013-10-23 02:17:46 +00007762 if (FoundEquivalentDecl)
7763 return false;
7764
Alp Tokera2794f92014-01-22 07:29:52 +00007765 if (FunctionDecl *FD = Target->getAsFunction()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007766 NamedDecl *OldDecl = nullptr;
7767 switch (CheckOverload(nullptr, FD, Previous, OldDecl,
7768 /*IsForUsingDecl*/ true)) {
John McCall84d87672009-12-10 09:41:52 +00007769 case Ovl_Overload:
7770 return false;
7771
7772 case Ovl_NonFunction:
John McCalle29c5cd2009-12-10 19:51:03 +00007773 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007774 break;
Richard Smith18819302014-02-06 01:31:33 +00007775
John McCall84d87672009-12-10 09:41:52 +00007776 // We found a decl with the exact signature.
7777 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00007778 // If we're in a record, we want to hide the target, so we
7779 // return true (without a diagnostic) to tell the caller not to
7780 // build a shadow decl.
7781 if (CurContext->isRecord())
7782 return true;
7783
7784 // If we're not in a record, this is an error.
John McCalle29c5cd2009-12-10 19:51:03 +00007785 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007786 break;
7787 }
7788
7789 Diag(Target->getLocation(), diag::note_using_decl_target);
7790 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
7791 return true;
7792 }
7793
7794 // Target is not a function.
7795
John McCall84d87672009-12-10 09:41:52 +00007796 if (isa<TagDecl>(Target)) {
7797 // No conflict between a tag and a non-tag.
7798 if (!Tag) return false;
7799
John McCalle29c5cd2009-12-10 19:51:03 +00007800 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007801 Diag(Target->getLocation(), diag::note_using_decl_target);
7802 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
7803 return true;
7804 }
7805
7806 // No conflict between a tag and a non-tag.
7807 if (!NonTag) return false;
7808
John McCalle29c5cd2009-12-10 19:51:03 +00007809 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007810 Diag(Target->getLocation(), diag::note_using_decl_target);
7811 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
7812 return true;
7813}
7814
John McCall3f746822009-11-17 05:59:44 +00007815/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall3969e302009-12-08 07:46:18 +00007816UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall3969e302009-12-08 07:46:18 +00007817 UsingDecl *UD,
Richard Smithfd8634a2013-10-23 02:17:46 +00007818 NamedDecl *Orig,
7819 UsingShadowDecl *PrevDecl) {
John McCall3f746822009-11-17 05:59:44 +00007820
7821 // If we resolved to another shadow declaration, just coalesce them.
John McCall3969e302009-12-08 07:46:18 +00007822 NamedDecl *Target = Orig;
7823 if (isa<UsingShadowDecl>(Target)) {
7824 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7825 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall3f746822009-11-17 05:59:44 +00007826 }
Richard Smithfd8634a2013-10-23 02:17:46 +00007827
John McCall3f746822009-11-17 05:59:44 +00007828 UsingShadowDecl *Shadow
John McCall3969e302009-12-08 07:46:18 +00007829 = UsingShadowDecl::Create(Context, CurContext,
7830 UD->getLocation(), UD, Target);
John McCall3f746822009-11-17 05:59:44 +00007831 UD->addShadowDecl(Shadow);
Richard Smithfd8634a2013-10-23 02:17:46 +00007832
Douglas Gregor457104e2010-09-29 04:25:11 +00007833 Shadow->setAccess(UD->getAccess());
7834 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
7835 Shadow->setInvalidDecl();
Richard Smithfd8634a2013-10-23 02:17:46 +00007836
7837 Shadow->setPreviousDecl(PrevDecl);
7838
John McCall3f746822009-11-17 05:59:44 +00007839 if (S)
John McCall3969e302009-12-08 07:46:18 +00007840 PushOnScopeChains(Shadow, S);
John McCall3f746822009-11-17 05:59:44 +00007841 else
John McCall3969e302009-12-08 07:46:18 +00007842 CurContext->addDecl(Shadow);
John McCall3f746822009-11-17 05:59:44 +00007843
John McCall3969e302009-12-08 07:46:18 +00007844
John McCall84d87672009-12-10 09:41:52 +00007845 return Shadow;
7846}
John McCall3969e302009-12-08 07:46:18 +00007847
John McCall84d87672009-12-10 09:41:52 +00007848/// Hides a using shadow declaration. This is required by the current
7849/// using-decl implementation when a resolvable using declaration in a
7850/// class is followed by a declaration which would hide or override
7851/// one or more of the using decl's targets; for example:
7852///
7853/// struct Base { void foo(int); };
7854/// struct Derived : Base {
7855/// using Base::foo;
7856/// void foo(int);
7857/// };
7858///
7859/// The governing language is C++03 [namespace.udecl]p12:
7860///
7861/// When a using-declaration brings names from a base class into a
7862/// derived class scope, member functions in the derived class
7863/// override and/or hide member functions with the same name and
7864/// parameter types in a base class (rather than conflicting).
7865///
7866/// There are two ways to implement this:
7867/// (1) optimistically create shadow decls when they're not hidden
7868/// by existing declarations, or
7869/// (2) don't create any shadow decls (or at least don't make them
7870/// visible) until we've fully parsed/instantiated the class.
7871/// The problem with (1) is that we might have to retroactively remove
7872/// a shadow decl, which requires several O(n) operations because the
7873/// decl structures are (very reasonably) not designed for removal.
7874/// (2) avoids this but is very fiddly and phase-dependent.
7875void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCallda4458e2010-03-31 01:36:47 +00007876 if (Shadow->getDeclName().getNameKind() ==
7877 DeclarationName::CXXConversionFunctionName)
7878 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
7879
John McCall84d87672009-12-10 09:41:52 +00007880 // Remove it from the DeclContext...
7881 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00007882
John McCall84d87672009-12-10 09:41:52 +00007883 // ...and the scope, if applicable...
7884 if (S) {
John McCall48871652010-08-21 09:40:31 +00007885 S->RemoveDecl(Shadow);
John McCall84d87672009-12-10 09:41:52 +00007886 IdResolver.RemoveDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00007887 }
7888
John McCall84d87672009-12-10 09:41:52 +00007889 // ...and the using decl.
7890 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
7891
7892 // TODO: complain somehow if Shadow was used. It shouldn't
John McCallda4458e2010-03-31 01:36:47 +00007893 // be possible for this to happen, because...?
John McCall3f746822009-11-17 05:59:44 +00007894}
7895
Richard Smith09d5b3a2014-05-01 00:35:04 +00007896/// Find the base specifier for a base class with the given type.
7897static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
7898 QualType DesiredBase,
7899 bool &AnyDependentBases) {
7900 // Check whether the named type is a direct base class.
7901 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
7902 for (auto &Base : Derived->bases()) {
7903 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
7904 if (CanonicalDesiredBase == BaseType)
7905 return &Base;
7906 if (BaseType->isDependentType())
7907 AnyDependentBases = true;
7908 }
Craig Topperc3ec1492014-05-26 06:22:03 +00007909 return nullptr;
Richard Smith09d5b3a2014-05-01 00:35:04 +00007910}
7911
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007912namespace {
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007913class UsingValidatorCCC : public CorrectionCandidateCallback {
7914public:
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +00007915 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
Richard Smith09d5b3a2014-05-01 00:35:04 +00007916 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007917 : HasTypenameKeyword(HasTypenameKeyword),
Richard Smith09d5b3a2014-05-01 00:35:04 +00007918 IsInstantiation(IsInstantiation), OldNNS(NNS),
7919 RequireMemberOf(RequireMemberOf) {}
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007920
Craig Toppera798a9d2014-03-02 09:32:10 +00007921 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007922 NamedDecl *ND = Candidate.getCorrectionDecl();
7923
7924 // Keywords are not valid here.
7925 if (!ND || isa<NamespaceDecl>(ND))
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007926 return false;
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007927
7928 // Completely unqualified names are invalid for a 'using' declaration.
7929 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
7930 return false;
7931
Richard Smith09d5b3a2014-05-01 00:35:04 +00007932 if (RequireMemberOf) {
7933 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
7934 if (FoundRecord && FoundRecord->isInjectedClassName()) {
7935 // No-one ever wants a using-declaration to name an injected-class-name
7936 // of a base class, unless they're declaring an inheriting constructor.
7937 ASTContext &Ctx = ND->getASTContext();
7938 if (!Ctx.getLangOpts().CPlusPlus11)
7939 return false;
7940 QualType FoundType = Ctx.getRecordType(FoundRecord);
7941
7942 // Check that the injected-class-name is named as a member of its own
7943 // type; we don't want to suggest 'using Derived::Base;', since that
7944 // means something else.
7945 NestedNameSpecifier *Specifier =
7946 Candidate.WillReplaceSpecifier()
7947 ? Candidate.getCorrectionSpecifier()
7948 : OldNNS;
7949 if (!Specifier->getAsType() ||
7950 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
7951 return false;
7952
7953 // Check that this inheriting constructor declaration actually names a
7954 // direct base class of the current class.
7955 bool AnyDependentBases = false;
7956 if (!findDirectBaseWithType(RequireMemberOf,
7957 Ctx.getRecordType(FoundRecord),
7958 AnyDependentBases) &&
7959 !AnyDependentBases)
7960 return false;
7961 } else {
7962 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
7963 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
7964 return false;
7965
7966 // FIXME: Check that the base class member is accessible?
7967 }
7968 }
7969
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007970 if (isa<TypeDecl>(ND))
7971 return HasTypenameKeyword || !IsInstantiation;
7972
7973 return !HasTypenameKeyword;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007974 }
7975
7976private:
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007977 bool HasTypenameKeyword;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007978 bool IsInstantiation;
Richard Smith09d5b3a2014-05-01 00:35:04 +00007979 NestedNameSpecifier *OldNNS;
Richard Smith21866c32014-04-30 18:03:21 +00007980 CXXRecordDecl *RequireMemberOf;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007981};
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007982} // end anonymous namespace
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007983
John McCalle61f2ba2009-11-18 02:36:19 +00007984/// Builds a using declaration.
7985///
7986/// \param IsInstantiation - Whether this call arises from an
7987/// instantiation of an unresolved using declaration. We treat
7988/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00007989NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
7990 SourceLocation UsingLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00007991 CXXScopeSpec &SS,
Richard Smith09d5b3a2014-05-01 00:35:04 +00007992 DeclarationNameInfo NameInfo,
Anders Carlsson696a3f12009-08-28 05:40:36 +00007993 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00007994 bool IsInstantiation,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007995 bool HasTypenameKeyword,
John McCalle61f2ba2009-11-18 02:36:19 +00007996 SourceLocation TypenameLoc) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00007997 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007998 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlsson696a3f12009-08-28 05:40:36 +00007999 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00008000
Anders Carlssonf038fc22009-08-28 05:49:21 +00008001 // FIXME: We ignore attributes for now.
Mike Stump11289f42009-09-09 15:08:12 +00008002
Anders Carlsson59140b32009-08-28 03:16:11 +00008003 if (SS.isEmpty()) {
8004 Diag(IdentLoc, diag::err_using_requires_qualname);
Craig Topperc3ec1492014-05-26 06:22:03 +00008005 return nullptr;
Anders Carlsson59140b32009-08-28 03:16:11 +00008006 }
Mike Stump11289f42009-09-09 15:08:12 +00008007
John McCall84d87672009-12-10 09:41:52 +00008008 // Do the redeclaration lookup in the current scope.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00008009 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall84d87672009-12-10 09:41:52 +00008010 ForRedeclaration);
8011 Previous.setHideTags(false);
8012 if (S) {
8013 LookupName(Previous, S);
8014
8015 // It is really dumb that we have to do this.
8016 LookupResult::Filter F = Previous.makeFilter();
8017 while (F.hasNext()) {
8018 NamedDecl *D = F.next();
8019 if (!isDeclInScope(D, CurContext, S))
8020 F.erase();
Richard Smith83e78f52014-04-11 01:03:38 +00008021 // If we found a local extern declaration that's not ordinarily visible,
8022 // and this declaration is being added to a non-block scope, ignore it.
8023 // We're only checking for scope conflicts here, not also for violations
8024 // of the linkage rules.
8025 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
8026 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
8027 F.erase();
John McCall84d87672009-12-10 09:41:52 +00008028 }
8029 F.done();
8030 } else {
8031 assert(IsInstantiation && "no scope in non-instantiation");
8032 assert(CurContext->isRecord() && "scope not record in instantiation");
8033 LookupQualifiedName(Previous, CurContext);
8034 }
8035
John McCall84d87672009-12-10 09:41:52 +00008036 // Check for invalid redeclarations.
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008037 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
8038 SS, IdentLoc, Previous))
Craig Topperc3ec1492014-05-26 06:22:03 +00008039 return nullptr;
John McCall84d87672009-12-10 09:41:52 +00008040
8041 // Check for bad qualifiers.
Richard Smith7ad0b882014-04-02 21:44:35 +00008042 if (CheckUsingDeclQualifier(UsingLoc, SS, NameInfo, IdentLoc))
Craig Topperc3ec1492014-05-26 06:22:03 +00008043 return nullptr;
John McCallb96ec562009-12-04 22:46:56 +00008044
John McCall84c16cf2009-11-12 03:15:40 +00008045 DeclContext *LookupContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00008046 NamedDecl *D;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008047 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall84c16cf2009-11-12 03:15:40 +00008048 if (!LookupContext) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008049 if (HasTypenameKeyword) {
John McCallb96ec562009-12-04 22:46:56 +00008050 // FIXME: not all declaration name kinds are legal here
8051 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
8052 UsingLoc, TypenameLoc,
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008053 QualifierLoc,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00008054 IdentLoc, NameInfo.getName());
John McCallb96ec562009-12-04 22:46:56 +00008055 } else {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008056 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
8057 QualifierLoc, NameInfo);
John McCalle61f2ba2009-11-18 02:36:19 +00008058 }
Richard Smith09d5b3a2014-05-01 00:35:04 +00008059 D->setAccess(AS);
8060 CurContext->addDecl(D);
8061 return D;
Anders Carlssonf038fc22009-08-28 05:49:21 +00008062 }
John McCallb96ec562009-12-04 22:46:56 +00008063
Richard Smith09d5b3a2014-05-01 00:35:04 +00008064 auto Build = [&](bool Invalid) {
8065 UsingDecl *UD =
8066 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, NameInfo,
8067 HasTypenameKeyword);
8068 UD->setAccess(AS);
8069 CurContext->addDecl(UD);
8070 UD->setInvalidDecl(Invalid);
John McCall3969e302009-12-08 07:46:18 +00008071 return UD;
Richard Smith09d5b3a2014-05-01 00:35:04 +00008072 };
8073 auto BuildInvalid = [&]{ return Build(true); };
8074 auto BuildValid = [&]{ return Build(false); };
8075
8076 if (RequireCompleteDeclContext(SS, LookupContext))
8077 return BuildInvalid();
Anders Carlsson59140b32009-08-28 03:16:11 +00008078
Richard Smith23d55872012-04-02 01:30:27 +00008079 // The normal rules do not apply to inheriting constructor declarations.
Sebastian Redl08905022011-02-05 19:23:19 +00008080 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Richard Smith09d5b3a2014-05-01 00:35:04 +00008081 UsingDecl *UD = BuildValid();
8082 CheckInheritingConstructorUsingDecl(UD);
Sebastian Redl08905022011-02-05 19:23:19 +00008083 return UD;
8084 }
8085
8086 // Otherwise, look up the target name.
John McCall3969e302009-12-08 07:46:18 +00008087
Abramo Bagnara8de74e92010-08-12 11:46:03 +00008088 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle61f2ba2009-11-18 02:36:19 +00008089
John McCall3969e302009-12-08 07:46:18 +00008090 // Unlike most lookups, we don't always want to hide tag
8091 // declarations: tag names are visible through the using declaration
8092 // even if hidden by ordinary names, *except* in a dependent context
8093 // where it's important for the sanity of two-phase lookup.
John McCalle61f2ba2009-11-18 02:36:19 +00008094 if (!IsInstantiation)
8095 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00008096
John McCall5dadb652012-04-07 03:04:20 +00008097 // For the purposes of this lookup, we have a base object type
8098 // equal to that of the current context.
8099 if (CurContext->isRecord()) {
8100 R.setBaseObjectType(
8101 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
8102 }
8103
John McCall27b18f82009-11-17 02:14:36 +00008104 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00008105
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00008106 // Try to correct typos if possible.
John McCall9f3059a2009-10-09 21:13:30 +00008107 if (R.empty()) {
Kaelyn Takata89c881b2014-10-27 18:07:29 +00008108 if (TypoCorrection Corrected = CorrectTypo(
8109 R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
8110 llvm::make_unique<UsingValidatorCCC>(
8111 HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
8112 dyn_cast<CXXRecordDecl>(CurContext)),
8113 CTK_ErrorRecovery)) {
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00008114 // We reject any correction for which ND would be NULL.
8115 NamedDecl *ND = Corrected.getCorrectionDecl();
Richard Smith09d5b3a2014-05-01 00:35:04 +00008116
Richard Smithf9b15102013-08-17 00:46:16 +00008117 // We reject candidates where DroppedSpecifier == true, hence the
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00008118 // literal '0' below.
Richard Smithf9b15102013-08-17 00:46:16 +00008119 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
8120 << NameInfo.getName() << LookupContext << 0
8121 << SS.getRange());
Richard Smith09d5b3a2014-05-01 00:35:04 +00008122
8123 // If we corrected to an inheriting constructor, handle it as one.
8124 auto *RD = dyn_cast<CXXRecordDecl>(ND);
8125 if (RD && RD->isInjectedClassName()) {
8126 // Fix up the information we'll use to build the using declaration.
8127 if (Corrected.WillReplaceSpecifier()) {
8128 NestedNameSpecifierLocBuilder Builder;
8129 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
8130 QualifierLoc.getSourceRange());
8131 QualifierLoc = Builder.getWithLocInContext(Context);
8132 }
8133
8134 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
8135 Context.getCanonicalType(Context.getRecordType(RD))));
Craig Topperc3ec1492014-05-26 06:22:03 +00008136 NameInfo.setNamedTypeInfo(nullptr);
Richard Smith09d5b3a2014-05-01 00:35:04 +00008137
8138 // Build it and process it as an inheriting constructor.
8139 UsingDecl *UD = BuildValid();
8140 CheckInheritingConstructorUsingDecl(UD);
8141 return UD;
8142 }
8143
8144 // FIXME: Pick up all the declarations if we found an overloaded function.
8145 R.setLookupName(Corrected.getCorrection());
8146 R.addDecl(ND);
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00008147 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00008148 Diag(IdentLoc, diag::err_no_member)
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00008149 << NameInfo.getName() << LookupContext << SS.getRange();
Richard Smith09d5b3a2014-05-01 00:35:04 +00008150 return BuildInvalid();
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00008151 }
Douglas Gregorfec52632009-06-20 00:51:54 +00008152 }
8153
Richard Smith09d5b3a2014-05-01 00:35:04 +00008154 if (R.isAmbiguous())
8155 return BuildInvalid();
Mike Stump11289f42009-09-09 15:08:12 +00008156
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008157 if (HasTypenameKeyword) {
John McCalle61f2ba2009-11-18 02:36:19 +00008158 // If we asked for a typename and got a non-type decl, error out.
John McCallb96ec562009-12-04 22:46:56 +00008159 if (!R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00008160 Diag(IdentLoc, diag::err_using_typename_non_type);
8161 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
8162 Diag((*I)->getUnderlyingDecl()->getLocation(),
8163 diag::note_using_decl_target);
Richard Smith09d5b3a2014-05-01 00:35:04 +00008164 return BuildInvalid();
John McCalle61f2ba2009-11-18 02:36:19 +00008165 }
8166 } else {
8167 // If we asked for a non-typename and we got a type, error out,
8168 // but only if this is an instantiation of an unresolved using
8169 // decl. Otherwise just silently find the type name.
John McCallb96ec562009-12-04 22:46:56 +00008170 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00008171 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
8172 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
Richard Smith09d5b3a2014-05-01 00:35:04 +00008173 return BuildInvalid();
John McCalle61f2ba2009-11-18 02:36:19 +00008174 }
Anders Carlsson59140b32009-08-28 03:16:11 +00008175 }
8176
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00008177 // C++0x N2914 [namespace.udecl]p6:
8178 // A using-declaration shall not name a namespace.
John McCallb96ec562009-12-04 22:46:56 +00008179 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00008180 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
8181 << SS.getRange();
Richard Smith09d5b3a2014-05-01 00:35:04 +00008182 return BuildInvalid();
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00008183 }
Mike Stump11289f42009-09-09 15:08:12 +00008184
Richard Smith09d5b3a2014-05-01 00:35:04 +00008185 UsingDecl *UD = BuildValid();
John McCall84d87672009-12-10 09:41:52 +00008186 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
Craig Topperc3ec1492014-05-26 06:22:03 +00008187 UsingShadowDecl *PrevDecl = nullptr;
Richard Smithfd8634a2013-10-23 02:17:46 +00008188 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
8189 BuildUsingShadowDecl(S, UD, *I, PrevDecl);
John McCall84d87672009-12-10 09:41:52 +00008190 }
John McCall3f746822009-11-17 05:59:44 +00008191
8192 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00008193}
8194
Sebastian Redl08905022011-02-05 19:23:19 +00008195/// Additional checks for a using declaration referring to a constructor name.
Richard Smith23d55872012-04-02 01:30:27 +00008196bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008197 assert(!UD->hasTypename() && "expecting a constructor name");
Sebastian Redl08905022011-02-05 19:23:19 +00008198
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008199 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redl08905022011-02-05 19:23:19 +00008200 assert(SourceType &&
8201 "Using decl naming constructor doesn't have type in scope spec.");
8202 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
8203
8204 // Check whether the named type is a direct base class.
Richard Smith09d5b3a2014-05-01 00:35:04 +00008205 bool AnyDependentBases = false;
8206 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
8207 AnyDependentBases);
8208 if (!Base && !AnyDependentBases) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008209 Diag(UD->getUsingLoc(),
Sebastian Redl08905022011-02-05 19:23:19 +00008210 diag::err_using_decl_constructor_not_in_direct_base)
8211 << UD->getNameInfo().getSourceRange()
8212 << QualType(SourceType, 0) << TargetClass;
Richard Smith09d5b3a2014-05-01 00:35:04 +00008213 UD->setInvalidDecl();
Sebastian Redl08905022011-02-05 19:23:19 +00008214 return true;
8215 }
8216
Richard Smith09d5b3a2014-05-01 00:35:04 +00008217 if (Base)
8218 Base->setInheritConstructors();
Sebastian Redl08905022011-02-05 19:23:19 +00008219
8220 return false;
8221}
8222
John McCall84d87672009-12-10 09:41:52 +00008223/// Checks that the given using declaration is not an invalid
8224/// redeclaration. Note that this is checking only for the using decl
8225/// itself, not for any ill-formedness among the UsingShadowDecls.
8226bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008227 bool HasTypenameKeyword,
John McCall84d87672009-12-10 09:41:52 +00008228 const CXXScopeSpec &SS,
8229 SourceLocation NameLoc,
8230 const LookupResult &Prev) {
8231 // C++03 [namespace.udecl]p8:
8232 // C++0x [namespace.udecl]p10:
8233 // A using-declaration is a declaration and can therefore be used
8234 // repeatedly where (and only where) multiple declarations are
8235 // allowed.
Douglas Gregor4b718ee2010-05-06 23:31:27 +00008236 //
John McCall032092f2010-11-29 18:01:58 +00008237 // That's in non-member contexts.
8238 if (!CurContext->getRedeclContext()->isRecord())
John McCall84d87672009-12-10 09:41:52 +00008239 return false;
8240
Aaron Ballman4a979672014-01-03 13:56:08 +00008241 NestedNameSpecifier *Qual = SS.getScopeRep();
John McCall84d87672009-12-10 09:41:52 +00008242
8243 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
8244 NamedDecl *D = *I;
8245
8246 bool DTypename;
8247 NestedNameSpecifier *DQual;
8248 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008249 DTypename = UD->hasTypename();
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008250 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00008251 } else if (UnresolvedUsingValueDecl *UD
8252 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
8253 DTypename = false;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008254 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00008255 } else if (UnresolvedUsingTypenameDecl *UD
8256 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
8257 DTypename = true;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008258 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00008259 } else continue;
8260
8261 // using decls differ if one says 'typename' and the other doesn't.
8262 // FIXME: non-dependent using decls?
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008263 if (HasTypenameKeyword != DTypename) continue;
John McCall84d87672009-12-10 09:41:52 +00008264
8265 // using decls differ if they name different scopes (but note that
8266 // template instantiation can cause this check to trigger when it
8267 // didn't before instantiation).
8268 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
8269 Context.getCanonicalNestedNameSpecifier(DQual))
8270 continue;
8271
8272 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCalle29c5cd2009-12-10 19:51:03 +00008273 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall84d87672009-12-10 09:41:52 +00008274 return true;
8275 }
8276
8277 return false;
8278}
8279
John McCall3969e302009-12-08 07:46:18 +00008280
John McCallb96ec562009-12-04 22:46:56 +00008281/// Checks that the given nested-name qualifier used in a using decl
8282/// in the current context is appropriately related to the current
8283/// scope. If an error is found, diagnoses it and returns true.
8284bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
8285 const CXXScopeSpec &SS,
Richard Smith7ad0b882014-04-02 21:44:35 +00008286 const DeclarationNameInfo &NameInfo,
John McCallb96ec562009-12-04 22:46:56 +00008287 SourceLocation NameLoc) {
John McCall3969e302009-12-08 07:46:18 +00008288 DeclContext *NamedContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00008289
John McCall3969e302009-12-08 07:46:18 +00008290 if (!CurContext->isRecord()) {
8291 // C++03 [namespace.udecl]p3:
8292 // C++0x [namespace.udecl]p8:
8293 // A using-declaration for a class member shall be a member-declaration.
8294
8295 // If we weren't able to compute a valid scope, it must be a
8296 // dependent class scope.
8297 if (!NamedContext || NamedContext->isRecord()) {
David Majnemer4d2de1b02014-12-17 02:41:36 +00008298 auto *RD = dyn_cast_or_null<CXXRecordDecl>(NamedContext);
Richard Smith7ad0b882014-04-02 21:44:35 +00008299 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
Craig Topperc3ec1492014-05-26 06:22:03 +00008300 RD = nullptr;
Richard Smith7ad0b882014-04-02 21:44:35 +00008301
John McCall3969e302009-12-08 07:46:18 +00008302 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
8303 << SS.getRange();
Richard Smith7ad0b882014-04-02 21:44:35 +00008304
8305 // If we have a complete, non-dependent source type, try to suggest a
8306 // way to get the same effect.
8307 if (!RD)
8308 return true;
8309
8310 // Find what this using-declaration was referring to.
8311 LookupResult R(*this, NameInfo, LookupOrdinaryName);
8312 R.setHideTags(false);
8313 R.suppressDiagnostics();
8314 LookupQualifiedName(R, RD);
8315
8316 if (R.getAsSingle<TypeDecl>()) {
8317 if (getLangOpts().CPlusPlus11) {
8318 // Convert 'using X::Y;' to 'using Y = X::Y;'.
8319 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
8320 << 0 // alias declaration
8321 << FixItHint::CreateInsertion(SS.getBeginLoc(),
8322 NameInfo.getName().getAsString() +
8323 " = ");
8324 } else {
8325 // Convert 'using X::Y;' to 'typedef X::Y Y;'.
8326 SourceLocation InsertLoc =
8327 PP.getLocForEndOfToken(NameInfo.getLocEnd());
8328 Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
8329 << 1 // typedef declaration
8330 << FixItHint::CreateReplacement(UsingLoc, "typedef")
8331 << FixItHint::CreateInsertion(
8332 InsertLoc, " " + NameInfo.getName().getAsString());
8333 }
8334 } else if (R.getAsSingle<VarDecl>()) {
8335 // Don't provide a fixit outside C++11 mode; we don't want to suggest
8336 // repeating the type of the static data member here.
8337 FixItHint FixIt;
8338 if (getLangOpts().CPlusPlus11) {
8339 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
8340 FixIt = FixItHint::CreateReplacement(
8341 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
8342 }
8343
8344 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
8345 << 2 // reference declaration
8346 << FixIt;
8347 }
John McCall3969e302009-12-08 07:46:18 +00008348 return true;
8349 }
8350
8351 // Otherwise, everything is known to be fine.
8352 return false;
8353 }
8354
8355 // The current scope is a record.
8356
8357 // If the named context is dependent, we can't decide much.
8358 if (!NamedContext) {
8359 // FIXME: in C++0x, we can diagnose if we can prove that the
8360 // nested-name-specifier does not refer to a base class, which is
8361 // still possible in some cases.
8362
8363 // Otherwise we have to conservatively report that things might be
8364 // okay.
8365 return false;
8366 }
8367
8368 if (!NamedContext->isRecord()) {
8369 // Ideally this would point at the last name in the specifier,
8370 // but we don't have that level of source info.
8371 Diag(SS.getRange().getBegin(),
8372 diag::err_using_decl_nested_name_specifier_is_not_class)
Aaron Ballman5fe6c802014-01-03 13:45:46 +00008373 << SS.getScopeRep() << SS.getRange();
John McCall3969e302009-12-08 07:46:18 +00008374 return true;
8375 }
8376
Douglas Gregor7c842292010-12-21 07:41:49 +00008377 if (!NamedContext->isDependentContext() &&
8378 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
8379 return true;
8380
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008381 if (getLangOpts().CPlusPlus11) {
John McCall3969e302009-12-08 07:46:18 +00008382 // C++0x [namespace.udecl]p3:
8383 // In a using-declaration used as a member-declaration, the
8384 // nested-name-specifier shall name a base class of the class
8385 // being defined.
8386
8387 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
8388 cast<CXXRecordDecl>(NamedContext))) {
8389 if (CurContext == NamedContext) {
8390 Diag(NameLoc,
8391 diag::err_using_decl_nested_name_specifier_is_current_class)
8392 << SS.getRange();
8393 return true;
8394 }
8395
8396 Diag(SS.getRange().getBegin(),
8397 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Aaron Ballman4a979672014-01-03 13:56:08 +00008398 << SS.getScopeRep()
John McCall3969e302009-12-08 07:46:18 +00008399 << cast<CXXRecordDecl>(CurContext)
8400 << SS.getRange();
8401 return true;
8402 }
8403
8404 return false;
8405 }
8406
8407 // C++03 [namespace.udecl]p4:
8408 // A using-declaration used as a member-declaration shall refer
8409 // to a member of a base class of the class being defined [etc.].
8410
8411 // Salient point: SS doesn't have to name a base class as long as
8412 // lookup only finds members from base classes. Therefore we can
8413 // diagnose here only if we can prove that that can't happen,
8414 // i.e. if the class hierarchies provably don't intersect.
8415
8416 // TODO: it would be nice if "definitely valid" results were cached
8417 // in the UsingDecl and UsingShadowDecl so that these checks didn't
8418 // need to be repeated.
8419
8420 struct UserData {
Benjamin Kramer3adbe1c2012-02-23 16:06:01 +00008421 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
John McCall3969e302009-12-08 07:46:18 +00008422
8423 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
8424 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
8425 Data->Bases.insert(Base);
8426 return true;
8427 }
8428
8429 bool hasDependentBases(const CXXRecordDecl *Class) {
8430 return !Class->forallBases(collect, this);
8431 }
8432
8433 /// Returns true if the base is dependent or is one of the
8434 /// accumulated base classes.
8435 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
8436 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
8437 return !Data->Bases.count(Base);
8438 }
8439
8440 bool mightShareBases(const CXXRecordDecl *Class) {
8441 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
8442 }
8443 };
8444
8445 UserData Data;
8446
8447 // Returns false if we find a dependent base.
8448 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
8449 return false;
8450
8451 // Returns false if the class has a dependent base or if it or one
8452 // of its bases is present in the base set of the current context.
8453 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
8454 return false;
8455
8456 Diag(SS.getRange().getBegin(),
8457 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Aaron Ballman4a979672014-01-03 13:56:08 +00008458 << SS.getScopeRep()
John McCall3969e302009-12-08 07:46:18 +00008459 << cast<CXXRecordDecl>(CurContext)
8460 << SS.getRange();
8461
8462 return true;
John McCallb96ec562009-12-04 22:46:56 +00008463}
8464
Richard Smithdda56e42011-04-15 14:24:37 +00008465Decl *Sema::ActOnAliasDeclaration(Scope *S,
8466 AccessSpecifier AS,
Richard Smith3f1b5d02011-05-05 21:57:07 +00008467 MultiTemplateParamsArg TemplateParamLists,
Richard Smithdda56e42011-04-15 14:24:37 +00008468 SourceLocation UsingLoc,
8469 UnqualifiedId &Name,
Richard Smith54ecd982013-02-20 19:22:51 +00008470 AttributeList *AttrList,
Richard Smithdda56e42011-04-15 14:24:37 +00008471 TypeResult Type) {
Richard Smith3f1b5d02011-05-05 21:57:07 +00008472 // Skip up to the relevant declaration scope.
8473 while (S->getFlags() & Scope::TemplateParamScope)
8474 S = S->getParent();
Richard Smithdda56e42011-04-15 14:24:37 +00008475 assert((S->getFlags() & Scope::DeclScope) &&
8476 "got alias-declaration outside of declaration scope");
8477
8478 if (Type.isInvalid())
Craig Topperc3ec1492014-05-26 06:22:03 +00008479 return nullptr;
Richard Smithdda56e42011-04-15 14:24:37 +00008480
8481 bool Invalid = false;
8482 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
Craig Topperc3ec1492014-05-26 06:22:03 +00008483 TypeSourceInfo *TInfo = nullptr;
Nick Lewycky82e47802011-05-02 01:07:19 +00008484 GetTypeFromParser(Type.get(), &TInfo);
Richard Smithdda56e42011-04-15 14:24:37 +00008485
8486 if (DiagnoseClassNameShadow(CurContext, NameInfo))
Craig Topperc3ec1492014-05-26 06:22:03 +00008487 return nullptr;
Richard Smithdda56e42011-04-15 14:24:37 +00008488
8489 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3f1b5d02011-05-05 21:57:07 +00008490 UPPC_DeclarationType)) {
Richard Smithdda56e42011-04-15 14:24:37 +00008491 Invalid = true;
Richard Smith3f1b5d02011-05-05 21:57:07 +00008492 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
8493 TInfo->getTypeLoc().getBeginLoc());
8494 }
Richard Smithdda56e42011-04-15 14:24:37 +00008495
8496 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
8497 LookupName(Previous, S);
8498
8499 // Warn about shadowing the name of a template parameter.
8500 if (Previous.isSingleResult() &&
8501 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorf4ef4d22011-10-20 17:58:49 +00008502 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smithdda56e42011-04-15 14:24:37 +00008503 Previous.clear();
8504 }
8505
8506 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
8507 "name in alias declaration must be an identifier");
8508 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
8509 Name.StartLocation,
8510 Name.Identifier, TInfo);
8511
8512 NewTD->setAccess(AS);
8513
8514 if (Invalid)
8515 NewTD->setInvalidDecl();
8516
Richard Smith54ecd982013-02-20 19:22:51 +00008517 ProcessDeclAttributeList(S, NewTD, AttrList);
8518
Richard Smith3f1b5d02011-05-05 21:57:07 +00008519 CheckTypedefForVariablyModifiedType(S, NewTD);
8520 Invalid |= NewTD->isInvalidDecl();
8521
Richard Smithdda56e42011-04-15 14:24:37 +00008522 bool Redeclaration = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00008523
8524 NamedDecl *NewND;
8525 if (TemplateParamLists.size()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00008526 TypeAliasTemplateDecl *OldDecl = nullptr;
8527 TemplateParameterList *OldTemplateParams = nullptr;
Richard Smith3f1b5d02011-05-05 21:57:07 +00008528
8529 if (TemplateParamLists.size() != 1) {
8530 Diag(UsingLoc, diag::err_alias_template_extra_headers)
Benjamin Kramer62b95d82012-08-23 21:35:17 +00008531 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
8532 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
Richard Smith3f1b5d02011-05-05 21:57:07 +00008533 }
Benjamin Kramer62b95d82012-08-23 21:35:17 +00008534 TemplateParameterList *TemplateParams = TemplateParamLists[0];
Richard Smith3f1b5d02011-05-05 21:57:07 +00008535
8536 // Only consider previous declarations in the same scope.
8537 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
8538 /*ExplicitInstantiationOrSpecialization*/false);
8539 if (!Previous.empty()) {
8540 Redeclaration = true;
8541
8542 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
8543 if (!OldDecl && !Invalid) {
8544 Diag(UsingLoc, diag::err_redefinition_different_kind)
8545 << Name.Identifier;
8546
8547 NamedDecl *OldD = Previous.getRepresentativeDecl();
8548 if (OldD->getLocation().isValid())
8549 Diag(OldD->getLocation(), diag::note_previous_definition);
8550
8551 Invalid = true;
8552 }
8553
8554 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
8555 if (TemplateParameterListsAreEqual(TemplateParams,
8556 OldDecl->getTemplateParameters(),
8557 /*Complain=*/true,
8558 TPL_TemplateMatch))
8559 OldTemplateParams = OldDecl->getTemplateParameters();
8560 else
8561 Invalid = true;
8562
8563 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
8564 if (!Invalid &&
8565 !Context.hasSameType(OldTD->getUnderlyingType(),
8566 NewTD->getUnderlyingType())) {
8567 // FIXME: The C++0x standard does not clearly say this is ill-formed,
8568 // but we can't reasonably accept it.
8569 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
8570 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
8571 if (OldTD->getLocation().isValid())
8572 Diag(OldTD->getLocation(), diag::note_previous_definition);
8573 Invalid = true;
8574 }
8575 }
8576 }
8577
8578 // Merge any previous default template arguments into our parameters,
8579 // and check the parameter list.
8580 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
8581 TPC_TypeAliasTemplate))
Craig Topperc3ec1492014-05-26 06:22:03 +00008582 return nullptr;
Richard Smith3f1b5d02011-05-05 21:57:07 +00008583
8584 TypeAliasTemplateDecl *NewDecl =
8585 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
8586 Name.Identifier, TemplateParams,
8587 NewTD);
Richard Smith43ccec8e2014-08-26 03:52:16 +00008588 NewTD->setDescribedAliasTemplate(NewDecl);
Richard Smith3f1b5d02011-05-05 21:57:07 +00008589
8590 NewDecl->setAccess(AS);
8591
8592 if (Invalid)
8593 NewDecl->setInvalidDecl();
8594 else if (OldDecl)
Rafael Espindola8db352d2013-10-17 15:37:26 +00008595 NewDecl->setPreviousDecl(OldDecl);
Richard Smith3f1b5d02011-05-05 21:57:07 +00008596
8597 NewND = NewDecl;
8598 } else {
8599 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
8600 NewND = NewTD;
8601 }
Richard Smithdda56e42011-04-15 14:24:37 +00008602
8603 if (!Redeclaration)
Richard Smith3f1b5d02011-05-05 21:57:07 +00008604 PushOnScopeChains(NewND, S);
Richard Smithdda56e42011-04-15 14:24:37 +00008605
Dmitri Gribenko7f4b3772012-08-02 20:49:51 +00008606 ActOnDocumentableDecl(NewND);
Richard Smith3f1b5d02011-05-05 21:57:07 +00008607 return NewND;
Richard Smithdda56e42011-04-15 14:24:37 +00008608}
8609
Richard Smithf4634362014-09-03 23:11:22 +00008610Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
8611 SourceLocation AliasLoc,
8612 IdentifierInfo *Alias, CXXScopeSpec &SS,
8613 SourceLocation IdentLoc,
8614 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00008615
Anders Carlssonbb1e4722009-03-28 23:53:49 +00008616 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00008617 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
8618 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00008619
John McCall27b18f82009-11-17 02:14:36 +00008620 if (R.isAmbiguous())
Craig Topperc3ec1492014-05-26 06:22:03 +00008621 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00008622
John McCall9f3059a2009-10-09 21:13:30 +00008623 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00008624 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smitha9746882012-04-05 23:13:23 +00008625 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Craig Topperc3ec1492014-05-26 06:22:03 +00008626 return nullptr;
Douglas Gregor9629e9a2010-06-29 18:55:19 +00008627 }
Anders Carlssonac2c9652009-03-28 06:42:02 +00008628 }
Richard Smithf4634362014-09-03 23:11:22 +00008629 assert(!R.isAmbiguous() && !R.empty());
8630
8631 // Check if we have a previous declaration with the same name.
8632 NamedDecl *PrevDecl = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
8633 ForRedeclaration);
8634 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
8635 PrevDecl = nullptr;
8636
Aaron Ballman43f40102014-11-14 22:34:56 +00008637 NamedDecl *ND = R.getFoundDecl();
8638
Richard Smithf4634362014-09-03 23:11:22 +00008639 if (PrevDecl) {
8640 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
8641 // We already have an alias with the same name that points to the same
8642 // namespace; check that it matches.
Aaron Ballman43f40102014-11-14 22:34:56 +00008643 if (!AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
Richard Smithf4634362014-09-03 23:11:22 +00008644 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
8645 << Alias;
8646 Diag(PrevDecl->getLocation(), diag::note_previous_namespace_alias)
8647 << AD->getNamespace();
8648 return nullptr;
8649 }
8650 } else {
8651 unsigned DiagID = isa<NamespaceDecl>(PrevDecl)
8652 ? diag::err_redefinition
8653 : diag::err_redefinition_different_kind;
8654 Diag(AliasLoc, DiagID) << Alias;
8655 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
8656 return nullptr;
8657 }
8658 }
Mike Stump11289f42009-09-09 15:08:12 +00008659
Nico Riecke50e59a2014-11-24 17:29:52 +00008660 // The use of a nested name specifier may trigger deprecation warnings.
Aaron Ballman43f40102014-11-14 22:34:56 +00008661 DiagnoseUseOfDecl(ND, IdentLoc);
8662
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00008663 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00008664 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregorc05ba2e2011-02-25 17:08:07 +00008665 Alias, SS.getWithLocInContext(Context),
Aaron Ballman43f40102014-11-14 22:34:56 +00008666 IdentLoc, ND);
Richard Smithf4634362014-09-03 23:11:22 +00008667 if (PrevDecl)
8668 AliasDecl->setPreviousDecl(cast<NamespaceAliasDecl>(PrevDecl));
Mike Stump11289f42009-09-09 15:08:12 +00008669
John McCalld8d0d432010-02-16 06:53:13 +00008670 PushOnScopeChains(AliasDecl, S);
John McCall48871652010-08-21 09:40:31 +00008671 return AliasDecl;
Anders Carlsson9205d552009-03-28 05:27:17 +00008672}
8673
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008674Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +00008675Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
8676 CXXMethodDecl *MD) {
8677 CXXRecordDecl *ClassDecl = MD->getParent();
8678
Douglas Gregor6d880b12010-07-01 22:31:05 +00008679 // C++ [except.spec]p14:
8680 // An implicitly declared special member function (Clause 12) shall have an
8681 // exception-specification. [...]
Richard Smithf623c962012-04-17 00:58:00 +00008682 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00008683 if (ClassDecl->isInvalidDecl())
8684 return ExceptSpec;
Douglas Gregor6d880b12010-07-01 22:31:05 +00008685
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008686 // Direct base-class constructors.
Aaron Ballman574705e2014-03-13 15:41:46 +00008687 for (const auto &B : ClassDecl->bases()) {
8688 if (B.isVirtual()) // Handled below.
Douglas Gregor6d880b12010-07-01 22:31:05 +00008689 continue;
8690
Aaron Ballman574705e2014-03-13 15:41:46 +00008691 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Douglas Gregor9672f922010-07-03 00:47:00 +00008692 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00008693 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8694 // If this is a deleted function, add it anyway. This might be conformant
8695 // with the standard. This might not. I'm not sure. It might not matter.
8696 if (Constructor)
Aaron Ballman574705e2014-03-13 15:41:46 +00008697 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00008698 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00008699 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008700
8701 // Virtual base-class constructors.
Aaron Ballman445a9392014-03-13 16:15:17 +00008702 for (const auto &B : ClassDecl->vbases()) {
8703 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Douglas Gregor9672f922010-07-03 00:47:00 +00008704 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00008705 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8706 // If this is a deleted function, add it anyway. This might be conformant
8707 // with the standard. This might not. I'm not sure. It might not matter.
8708 if (Constructor)
Aaron Ballman445a9392014-03-13 16:15:17 +00008709 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00008710 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00008711 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008712
8713 // Field constructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008714 for (const auto *F : ClassDecl->fields()) {
Richard Smith938f40b2011-06-11 17:19:42 +00008715 if (F->hasInClassInitializer()) {
8716 if (Expr *E = F->getInClassInitializer())
8717 ExceptSpec.CalledExpr(E);
Richard Smith938f40b2011-06-11 17:19:42 +00008718 } else if (const RecordType *RecordTy
Douglas Gregor9672f922010-07-03 00:47:00 +00008719 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00008720 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8721 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8722 // If this is a deleted function, add it anyway. This might be conformant
8723 // with the standard. This might not. I'm not sure. It might not matter.
8724 // In particular, the problem is that this function never gets called. It
8725 // might just be ill-formed because this function attempts to refer to
8726 // a deleted function here.
8727 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +00008728 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00008729 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00008730 }
John McCalldb40c7f2010-12-14 08:05:40 +00008731
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008732 return ExceptSpec;
8733}
8734
Richard Smithc2bc61b2013-03-18 21:12:30 +00008735Sema::ImplicitExceptionSpecification
Richard Smithb7151b92013-04-10 06:11:48 +00008736Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
8737 CXXRecordDecl *ClassDecl = CD->getParent();
8738
8739 // C++ [except.spec]p14:
8740 // An inheriting constructor [...] shall have an exception-specification. [...]
Richard Smithc2bc61b2013-03-18 21:12:30 +00008741 ImplicitExceptionSpecification ExceptSpec(*this);
Richard Smithb7151b92013-04-10 06:11:48 +00008742 if (ClassDecl->isInvalidDecl())
8743 return ExceptSpec;
8744
8745 // Inherited constructor.
8746 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
8747 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
8748 // FIXME: Copying or moving the parameters could add extra exceptions to the
8749 // set, as could the default arguments for the inherited constructor. This
8750 // will be addressed when we implement the resolution of core issue 1351.
8751 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
8752
8753 // Direct base-class constructors.
Aaron Ballman574705e2014-03-13 15:41:46 +00008754 for (const auto &B : ClassDecl->bases()) {
8755 if (B.isVirtual()) // Handled below.
Richard Smithb7151b92013-04-10 06:11:48 +00008756 continue;
8757
Aaron Ballman574705e2014-03-13 15:41:46 +00008758 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Richard Smithb7151b92013-04-10 06:11:48 +00008759 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8760 if (BaseClassDecl == InheritedDecl)
8761 continue;
8762 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8763 if (Constructor)
Aaron Ballman574705e2014-03-13 15:41:46 +00008764 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Richard Smithb7151b92013-04-10 06:11:48 +00008765 }
8766 }
8767
8768 // Virtual base-class constructors.
Aaron Ballman445a9392014-03-13 16:15:17 +00008769 for (const auto &B : ClassDecl->vbases()) {
8770 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Richard Smithb7151b92013-04-10 06:11:48 +00008771 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8772 if (BaseClassDecl == InheritedDecl)
8773 continue;
8774 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8775 if (Constructor)
Aaron Ballman445a9392014-03-13 16:15:17 +00008776 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Richard Smithb7151b92013-04-10 06:11:48 +00008777 }
8778 }
8779
8780 // Field constructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008781 for (const auto *F : ClassDecl->fields()) {
Richard Smithb7151b92013-04-10 06:11:48 +00008782 if (F->hasInClassInitializer()) {
8783 if (Expr *E = F->getInClassInitializer())
8784 ExceptSpec.CalledExpr(E);
Richard Smithb7151b92013-04-10 06:11:48 +00008785 } else if (const RecordType *RecordTy
8786 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8787 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8788 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8789 if (Constructor)
8790 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
8791 }
8792 }
8793
Richard Smithc2bc61b2013-03-18 21:12:30 +00008794 return ExceptSpec;
8795}
8796
Richard Smith8bf22e52012-11-29 01:34:07 +00008797namespace {
8798/// RAII object to register a special member as being currently declared.
8799struct DeclaringSpecialMember {
8800 Sema &S;
8801 Sema::SpecialMemberDecl D;
8802 bool WasAlreadyBeingDeclared;
8803
8804 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
8805 : S(S), D(RD, CSM) {
David Blaikie82e95a32014-11-19 07:49:47 +00008806 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
Richard Smith8bf22e52012-11-29 01:34:07 +00008807 if (WasAlreadyBeingDeclared)
8808 // This almost never happens, but if it does, ensure that our cache
8809 // doesn't contain a stale result.
8810 S.SpecialMemberCache.clear();
8811
8812 // FIXME: Register a note to be produced if we encounter an error while
8813 // declaring the special member.
8814 }
8815 ~DeclaringSpecialMember() {
8816 if (!WasAlreadyBeingDeclared)
8817 S.SpecialMembersBeingDeclared.erase(D);
8818 }
8819
8820 /// \brief Are we already trying to declare this special member?
8821 bool isAlreadyBeingDeclared() const {
8822 return WasAlreadyBeingDeclared;
8823 }
8824};
8825}
8826
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008827CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
8828 CXXRecordDecl *ClassDecl) {
8829 // C++ [class.ctor]p5:
8830 // A default constructor for a class X is a constructor of class X
8831 // that can be called without an argument. If there is no
8832 // user-declared constructor for class X, a default constructor is
8833 // implicitly declared. An implicitly-declared default constructor
8834 // is an inline public member of its class.
Eli Bendersky9a220fc2014-09-29 20:38:29 +00008835 assert(ClassDecl->needsImplicitDefaultConstructor() &&
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008836 "Should not build implicit default constructor!");
8837
Richard Smith8bf22e52012-11-29 01:34:07 +00008838 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
8839 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +00008840 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +00008841
Richard Smithb5800092012-06-10 05:43:50 +00008842 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8843 CXXDefaultConstructor,
8844 false);
8845
Douglas Gregor6d880b12010-07-01 22:31:05 +00008846 // Create the actual constructor declaration.
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008847 CanQualType ClassType
8848 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00008849 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008850 DeclarationName Name
8851 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00008852 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smithcc36f692011-12-22 02:22:31 +00008853 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +00008854 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(),
8855 /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true,
8856 /*isImplicitlyDeclared=*/true, Constexpr);
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008857 DefaultCon->setAccess(AS_public);
Alexis Huntf92197c2011-05-12 03:51:51 +00008858 DefaultCon->setDefaulted();
Eli Bendersky9a220fc2014-09-29 20:38:29 +00008859
8860 if (getLangOpts().CUDA) {
8861 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
8862 DefaultCon,
8863 /* ConstRHS */ false,
8864 /* Diagnose */ false);
8865 }
Richard Smithd3b5c9082012-07-27 04:22:15 +00008866
8867 // Build an exception specification pointing back at this constructor.
Reid Kleckner78af0702013-08-27 23:08:25 +00008868 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00008869 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00008870
Richard Smith6b02d462012-12-08 08:32:28 +00008871 // We don't need to use SpecialMemberIsTrivial here; triviality for default
8872 // constructors is easy to compute.
8873 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
8874
8875 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Richard Smithb4d2a152013-04-02 19:38:47 +00008876 SetDeclDeleted(DefaultCon, ClassLoc);
Richard Smith6b02d462012-12-08 08:32:28 +00008877
Douglas Gregor9672f922010-07-03 00:47:00 +00008878 // Note that we have declared this constructor.
Douglas Gregor9672f922010-07-03 00:47:00 +00008879 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
Richard Smith6b02d462012-12-08 08:32:28 +00008880
Douglas Gregor0be31a22010-07-02 17:43:08 +00008881 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor9672f922010-07-03 00:47:00 +00008882 PushOnScopeChains(DefaultCon, S, false);
8883 ClassDecl->addDecl(DefaultCon);
Alexis Hunte77a28f2011-05-18 03:41:58 +00008884
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008885 return DefaultCon;
8886}
8887
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00008888void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
8889 CXXConstructorDecl *Constructor) {
Alexis Huntf92197c2011-05-12 03:51:51 +00008890 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Alexis Hunt61ae8d32011-05-23 23:14:04 +00008891 !Constructor->doesThisDeclarationHaveABody() &&
8892 !Constructor->isDeleted()) &&
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00008893 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00008894
Anders Carlsson423f5d82010-04-23 16:04:08 +00008895 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman9cf6b592009-11-09 19:20:36 +00008896 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +00008897
Eli Friedmaneaf34142012-10-18 20:14:08 +00008898 SynthesizedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00008899 DiagnosticErrorTrap Trap(Diags);
David Blaikie3fc2f912013-01-17 05:26:25 +00008900 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00008901 Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00008902 Diag(CurrentLocation, diag::note_member_synthesized_at)
Alexis Hunt80f00ff2011-05-10 19:08:14 +00008903 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00008904 Constructor->setInvalidDecl();
Douglas Gregor73193272010-09-20 16:48:21 +00008905 return;
Eli Friedman9cf6b592009-11-09 19:20:36 +00008906 }
Douglas Gregor73193272010-09-20 16:48:21 +00008907
Ben Langmuir2f8e6b82014-09-25 20:55:00 +00008908 // The exception specification is needed because we are defining the
8909 // function.
8910 ResolveExceptionSpec(CurrentLocation,
8911 Constructor->getType()->castAs<FunctionProtoType>());
8912
Daniel Jasperb3b0b802014-06-20 08:44:22 +00008913 SourceLocation Loc = Constructor->getLocEnd().isValid()
8914 ? Constructor->getLocEnd()
8915 : Constructor->getLocation();
Benjamin Kramere2a929d2012-07-04 17:03:41 +00008916 Constructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor73193272010-09-20 16:48:21 +00008917
Eli Friedman276dd182013-09-05 00:02:25 +00008918 Constructor->markUsed(Context);
Douglas Gregor73193272010-09-20 16:48:21 +00008919 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00008920
8921 if (ASTMutationListener *L = getASTMutationListener()) {
8922 L->CompletedImplicitDefinition(Constructor);
8923 }
Richard Trieuef64e942013-10-25 00:56:00 +00008924
8925 DiagnoseUninitializedFields(*this, Constructor);
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00008926}
8927
Richard Smith938f40b2011-06-11 17:19:42 +00008928void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
Alp Tokerae3a9442013-10-18 05:54:19 +00008929 // Perform any delayed checks on exception specifications.
8930 CheckDelayedMemberExceptionSpecs();
Richard Smith938f40b2011-06-11 17:19:42 +00008931}
8932
Richard Smith185be182013-04-10 05:48:59 +00008933namespace {
8934/// Information on inheriting constructors to declare.
8935class InheritingConstructorInfo {
8936public:
8937 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
8938 : SemaRef(SemaRef), Derived(Derived) {
8939 // Mark the constructors that we already have in the derived class.
8940 //
8941 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
8942 // unless there is a user-declared constructor with the same signature in
8943 // the class where the using-declaration appears.
8944 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
8945 }
8946
8947 void inheritAll(CXXRecordDecl *RD) {
8948 visitAll(RD, &InheritingConstructorInfo::inherit);
8949 }
8950
8951private:
8952 /// Information about an inheriting constructor.
8953 struct InheritingConstructor {
8954 InheritingConstructor()
Craig Topperc3ec1492014-05-26 06:22:03 +00008955 : DeclaredInDerived(false), BaseCtor(nullptr), DerivedCtor(nullptr) {}
Richard Smith185be182013-04-10 05:48:59 +00008956
8957 /// If \c true, a constructor with this signature is already declared
8958 /// in the derived class.
8959 bool DeclaredInDerived;
8960
8961 /// The constructor which is inherited.
8962 const CXXConstructorDecl *BaseCtor;
8963
8964 /// The derived constructor we declared.
8965 CXXConstructorDecl *DerivedCtor;
8966 };
8967
8968 /// Inheriting constructors with a given canonical type. There can be at
8969 /// most one such non-template constructor, and any number of templated
8970 /// constructors.
8971 struct InheritingConstructorsForType {
8972 InheritingConstructor NonTemplate;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008973 SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4>
8974 Templates;
Richard Smith185be182013-04-10 05:48:59 +00008975
8976 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
8977 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
8978 TemplateParameterList *ParamList = FTD->getTemplateParameters();
8979 for (unsigned I = 0, N = Templates.size(); I != N; ++I)
8980 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
8981 false, S.TPL_TemplateMatch))
8982 return Templates[I].second;
8983 Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
8984 return Templates.back().second;
Sebastian Redl08905022011-02-05 19:23:19 +00008985 }
Richard Smith185be182013-04-10 05:48:59 +00008986
8987 return NonTemplate;
8988 }
8989 };
8990
8991 /// Get or create the inheriting constructor record for a constructor.
8992 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
8993 QualType CtorType) {
8994 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
8995 .getEntry(SemaRef, Ctor);
8996 }
8997
8998 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
8999
9000 /// Process all constructors for a class.
9001 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00009002 for (const auto *Ctor : RD->ctors())
9003 (this->*Callback)(Ctor);
Richard Smith185be182013-04-10 05:48:59 +00009004 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
9005 I(RD->decls_begin()), E(RD->decls_end());
9006 I != E; ++I) {
9007 const FunctionDecl *FD = (*I)->getTemplatedDecl();
9008 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
9009 (this->*Callback)(CD);
Sebastian Redl08905022011-02-05 19:23:19 +00009010 }
9011 }
Richard Smith185be182013-04-10 05:48:59 +00009012
9013 /// Note that a constructor (or constructor template) was declared in Derived.
9014 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
9015 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
9016 }
9017
9018 /// Inherit a single constructor.
9019 void inherit(const CXXConstructorDecl *Ctor) {
9020 const FunctionProtoType *CtorType =
9021 Ctor->getType()->castAs<FunctionProtoType>();
Craig Topper5fc8fc22014-08-27 06:28:36 +00009022 ArrayRef<QualType> ArgTypes = CtorType->getParamTypes();
Richard Smith185be182013-04-10 05:48:59 +00009023 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
9024
9025 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
9026
9027 // Core issue (no number yet): the ellipsis is always discarded.
9028 if (EPI.Variadic) {
9029 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
9030 SemaRef.Diag(Ctor->getLocation(),
9031 diag::note_using_decl_constructor_ellipsis);
9032 EPI.Variadic = false;
9033 }
9034
9035 // Declare a constructor for each number of parameters.
9036 //
9037 // C++11 [class.inhctor]p1:
9038 // The candidate set of inherited constructors from the class X named in
9039 // the using-declaration consists of [... modulo defects ...] for each
9040 // constructor or constructor template of X, the set of constructors or
9041 // constructor templates that results from omitting any ellipsis parameter
9042 // specification and successively omitting parameters with a default
9043 // argument from the end of the parameter-type-list
Richard Smith3c626ed2013-04-17 19:00:52 +00009044 unsigned MinParams = minParamsToInherit(Ctor);
9045 unsigned Params = Ctor->getNumParams();
9046 if (Params >= MinParams) {
9047 do
9048 declareCtor(UsingLoc, Ctor,
9049 SemaRef.Context.getFunctionType(
Alp Toker314cc812014-01-25 16:55:45 +00009050 Ctor->getReturnType(), ArgTypes.slice(0, Params), EPI));
Richard Smith3c626ed2013-04-17 19:00:52 +00009051 while (Params > MinParams &&
9052 Ctor->getParamDecl(--Params)->hasDefaultArg());
9053 }
Richard Smith185be182013-04-10 05:48:59 +00009054 }
9055
9056 /// Find the using-declaration which specified that we should inherit the
9057 /// constructors of \p Base.
9058 SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
9059 // No fancy lookup required; just look for the base constructor name
9060 // directly within the derived class.
9061 ASTContext &Context = SemaRef.Context;
9062 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
9063 Context.getCanonicalType(Context.getRecordType(Base)));
9064 DeclContext::lookup_const_result Decls = Derived->lookup(Name);
9065 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
9066 }
9067
9068 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
9069 // C++11 [class.inhctor]p3:
9070 // [F]or each constructor template in the candidate set of inherited
9071 // constructors, a constructor template is implicitly declared
9072 if (Ctor->getDescribedFunctionTemplate())
9073 return 0;
9074
9075 // For each non-template constructor in the candidate set of inherited
9076 // constructors other than a constructor having no parameters or a
9077 // copy/move constructor having a single parameter, a constructor is
9078 // implicitly declared [...]
9079 if (Ctor->getNumParams() == 0)
9080 return 1;
9081 if (Ctor->isCopyOrMoveConstructor())
9082 return 2;
9083
9084 // Per discussion on core reflector, never inherit a constructor which
9085 // would become a default, copy, or move constructor of Derived either.
9086 const ParmVarDecl *PD = Ctor->getParamDecl(0);
9087 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
9088 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
9089 }
9090
9091 /// Declare a single inheriting constructor, inheriting the specified
9092 /// constructor, with the given type.
9093 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
9094 QualType DerivedType) {
9095 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
9096
9097 // C++11 [class.inhctor]p3:
9098 // ... a constructor is implicitly declared with the same constructor
9099 // characteristics unless there is a user-declared constructor with
9100 // the same signature in the class where the using-declaration appears
9101 if (Entry.DeclaredInDerived)
9102 return;
9103
9104 // C++11 [class.inhctor]p7:
9105 // If two using-declarations declare inheriting constructors with the
9106 // same signature, the program is ill-formed
9107 if (Entry.DerivedCtor) {
9108 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
9109 // Only diagnose this once per constructor.
9110 if (Entry.DerivedCtor->isInvalidDecl())
9111 return;
9112 Entry.DerivedCtor->setInvalidDecl();
9113
9114 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
9115 SemaRef.Diag(BaseCtor->getLocation(),
9116 diag::note_using_decl_constructor_conflict_current_ctor);
9117 SemaRef.Diag(Entry.BaseCtor->getLocation(),
9118 diag::note_using_decl_constructor_conflict_previous_ctor);
9119 SemaRef.Diag(Entry.DerivedCtor->getLocation(),
9120 diag::note_using_decl_constructor_conflict_previous_using);
9121 } else {
9122 // Core issue (no number): if the same inheriting constructor is
9123 // produced by multiple base class constructors from the same base
9124 // class, the inheriting constructor is defined as deleted.
9125 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
9126 }
9127
9128 return;
9129 }
9130
9131 ASTContext &Context = SemaRef.Context;
9132 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
9133 Context.getCanonicalType(Context.getRecordType(Derived)));
9134 DeclarationNameInfo NameInfo(Name, UsingLoc);
9135
Craig Topperc3ec1492014-05-26 06:22:03 +00009136 TemplateParameterList *TemplateParams = nullptr;
Richard Smith185be182013-04-10 05:48:59 +00009137 if (const FunctionTemplateDecl *FTD =
9138 BaseCtor->getDescribedFunctionTemplate()) {
9139 TemplateParams = FTD->getTemplateParameters();
9140 // We're reusing template parameters from a different DeclContext. This
9141 // is questionable at best, but works out because the template depth in
9142 // both places is guaranteed to be 0.
9143 // FIXME: Rebuild the template parameters in the new context, and
9144 // transform the function type to refer to them.
9145 }
9146
9147 // Build type source info pointing at the using-declaration. This is
9148 // required by template instantiation.
9149 TypeSourceInfo *TInfo =
9150 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
9151 FunctionProtoTypeLoc ProtoLoc =
9152 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
9153
9154 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
9155 Context, Derived, UsingLoc, NameInfo, DerivedType,
9156 TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
9157 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
9158
9159 // Build an unevaluated exception specification for this constructor.
9160 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
9161 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Richard Smith8acb4282014-07-31 21:57:55 +00009162 EPI.ExceptionSpec.Type = EST_Unevaluated;
9163 EPI.ExceptionSpec.SourceDecl = DerivedCtor;
Alp Toker314cc812014-01-25 16:55:45 +00009164 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00009165 FPT->getParamTypes(), EPI));
Richard Smith185be182013-04-10 05:48:59 +00009166
9167 // Build the parameter declarations.
9168 SmallVector<ParmVarDecl *, 16> ParamDecls;
Alp Toker9cacbab2014-01-20 20:26:09 +00009169 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
Richard Smith185be182013-04-10 05:48:59 +00009170 TypeSourceInfo *TInfo =
Alp Toker9cacbab2014-01-20 20:26:09 +00009171 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
Richard Smith185be182013-04-10 05:48:59 +00009172 ParmVarDecl *PD = ParmVarDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +00009173 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
9174 FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr);
Richard Smith185be182013-04-10 05:48:59 +00009175 PD->setScopeInfo(0, I);
9176 PD->setImplicit();
9177 ParamDecls.push_back(PD);
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00009178 ProtoLoc.setParam(I, PD);
Richard Smith185be182013-04-10 05:48:59 +00009179 }
9180
9181 // Set up the new constructor.
9182 DerivedCtor->setAccess(BaseCtor->getAccess());
9183 DerivedCtor->setParams(ParamDecls);
9184 DerivedCtor->setInheritedConstructor(BaseCtor);
9185 if (BaseCtor->isDeleted())
9186 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
9187
9188 // If this is a constructor template, build the template declaration.
9189 if (TemplateParams) {
9190 FunctionTemplateDecl *DerivedTemplate =
9191 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
9192 TemplateParams, DerivedCtor);
9193 DerivedTemplate->setAccess(BaseCtor->getAccess());
9194 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
9195 Derived->addDecl(DerivedTemplate);
9196 } else {
9197 Derived->addDecl(DerivedCtor);
9198 }
9199
9200 Entry.BaseCtor = BaseCtor;
9201 Entry.DerivedCtor = DerivedCtor;
9202 }
9203
9204 Sema &SemaRef;
9205 CXXRecordDecl *Derived;
9206 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
9207 MapType Map;
9208};
9209}
9210
9211void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
9212 // Defer declaring the inheriting constructors until the class is
9213 // instantiated.
9214 if (ClassDecl->isDependentContext())
Sebastian Redl08905022011-02-05 19:23:19 +00009215 return;
9216
Richard Smith185be182013-04-10 05:48:59 +00009217 // Find base classes from which we might inherit constructors.
9218 SmallVector<CXXRecordDecl*, 4> InheritedBases;
Aaron Ballman574705e2014-03-13 15:41:46 +00009219 for (const auto &BaseIt : ClassDecl->bases())
9220 if (BaseIt.getInheritConstructors())
9221 InheritedBases.push_back(BaseIt.getType()->getAsCXXRecordDecl());
Richard Smithc2bc61b2013-03-18 21:12:30 +00009222
Richard Smith185be182013-04-10 05:48:59 +00009223 // Go no further if we're not inheriting any constructors.
9224 if (InheritedBases.empty())
9225 return;
Sebastian Redl08905022011-02-05 19:23:19 +00009226
Richard Smith185be182013-04-10 05:48:59 +00009227 // Declare the inherited constructors.
9228 InheritingConstructorInfo ICI(*this, ClassDecl);
9229 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
9230 ICI.inheritAll(InheritedBases[I]);
Sebastian Redl08905022011-02-05 19:23:19 +00009231}
9232
Richard Smithc2bc61b2013-03-18 21:12:30 +00009233void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
9234 CXXConstructorDecl *Constructor) {
9235 CXXRecordDecl *ClassDecl = Constructor->getParent();
9236 assert(Constructor->getInheritedConstructor() &&
9237 !Constructor->doesThisDeclarationHaveABody() &&
9238 !Constructor->isDeleted());
9239
9240 SynthesizedFunctionScope Scope(*this, Constructor);
9241 DiagnosticErrorTrap Trap(Diags);
9242 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
9243 Trap.hasErrorOccurred()) {
9244 Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
9245 << Context.getTagDeclType(ClassDecl);
9246 Constructor->setInvalidDecl();
9247 return;
9248 }
9249
9250 SourceLocation Loc = Constructor->getLocation();
9251 Constructor->setBody(new (Context) CompoundStmt(Loc));
9252
Eli Friedman276dd182013-09-05 00:02:25 +00009253 Constructor->markUsed(Context);
Richard Smithc2bc61b2013-03-18 21:12:30 +00009254 MarkVTableUsed(CurrentLocation, ClassDecl);
9255
9256 if (ASTMutationListener *L = getASTMutationListener()) {
9257 L->CompletedImplicitDefinition(Constructor);
9258 }
9259}
9260
9261
Alexis Huntf91729462011-05-12 22:46:25 +00009262Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +00009263Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
9264 CXXRecordDecl *ClassDecl = MD->getParent();
9265
Douglas Gregorf1203042010-07-01 19:09:28 +00009266 // C++ [except.spec]p14:
9267 // An implicitly declared special member function (Clause 12) shall have
9268 // an exception-specification.
Richard Smithf623c962012-04-17 00:58:00 +00009269 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00009270 if (ClassDecl->isInvalidDecl())
9271 return ExceptSpec;
9272
Douglas Gregorf1203042010-07-01 19:09:28 +00009273 // Direct base-class destructors.
Aaron Ballman574705e2014-03-13 15:41:46 +00009274 for (const auto &B : ClassDecl->bases()) {
9275 if (B.isVirtual()) // Handled below.
Douglas Gregorf1203042010-07-01 19:09:28 +00009276 continue;
9277
Aaron Ballman574705e2014-03-13 15:41:46 +00009278 if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
9279 ExceptSpec.CalledDecl(B.getLocStart(),
Sebastian Redl623ea822011-05-19 05:13:44 +00009280 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00009281 }
Sebastian Redl623ea822011-05-19 05:13:44 +00009282
Douglas Gregorf1203042010-07-01 19:09:28 +00009283 // Virtual base-class destructors.
Aaron Ballman445a9392014-03-13 16:15:17 +00009284 for (const auto &B : ClassDecl->vbases()) {
9285 if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
9286 ExceptSpec.CalledDecl(B.getLocStart(),
Sebastian Redl623ea822011-05-19 05:13:44 +00009287 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00009288 }
Sebastian Redl623ea822011-05-19 05:13:44 +00009289
Douglas Gregorf1203042010-07-01 19:09:28 +00009290 // Field destructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009291 for (const auto *F : ClassDecl->fields()) {
Douglas Gregorf1203042010-07-01 19:09:28 +00009292 if (const RecordType *RecordTy
9293 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
Richard Smithf623c962012-04-17 00:58:00 +00009294 ExceptSpec.CalledDecl(F->getLocation(),
Sebastian Redl623ea822011-05-19 05:13:44 +00009295 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00009296 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00009297
Alexis Huntf91729462011-05-12 22:46:25 +00009298 return ExceptSpec;
9299}
9300
9301CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
9302 // C++ [class.dtor]p2:
9303 // If a class has no user-declared destructor, a destructor is
9304 // declared implicitly. An implicitly-declared destructor is an
9305 // inline public member of its class.
Richard Smith2be35f52012-12-01 02:35:44 +00009306 assert(ClassDecl->needsImplicitDestructor());
Alexis Huntf91729462011-05-12 22:46:25 +00009307
Richard Smith8bf22e52012-11-29 01:34:07 +00009308 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
9309 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +00009310 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +00009311
Douglas Gregor7454c562010-07-02 20:37:36 +00009312 // Create the actual destructor declaration.
Douglas Gregorf1203042010-07-01 19:09:28 +00009313 CanQualType ClassType
9314 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00009315 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorf1203042010-07-01 19:09:28 +00009316 DeclarationName Name
9317 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00009318 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorf1203042010-07-01 19:09:28 +00009319 CXXDestructorDecl *Destructor
Richard Smithd3b5c9082012-07-27 04:22:15 +00009320 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Craig Topperc3ec1492014-05-26 06:22:03 +00009321 QualType(), nullptr, /*isInline=*/true,
Sebastian Redlfa453cf2011-03-12 11:50:43 +00009322 /*isImplicitlyDeclared=*/true);
Douglas Gregorf1203042010-07-01 19:09:28 +00009323 Destructor->setAccess(AS_public);
Alexis Huntf91729462011-05-12 22:46:25 +00009324 Destructor->setDefaulted();
Eli Bendersky9a220fc2014-09-29 20:38:29 +00009325
9326 if (getLangOpts().CUDA) {
9327 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
9328 Destructor,
9329 /* ConstRHS */ false,
9330 /* Diagnose */ false);
9331 }
Richard Smithd3b5c9082012-07-27 04:22:15 +00009332
9333 // Build an exception specification pointing back at this destructor.
Reid Kleckner78af0702013-08-27 23:08:25 +00009334 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00009335 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00009336
Richard Smith6b02d462012-12-08 08:32:28 +00009337 AddOverriddenMethods(ClassDecl, Destructor);
9338
9339 // We don't need to use SpecialMemberIsTrivial here; triviality for
9340 // destructors is easy to compute.
9341 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
9342
9343 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
Richard Smithb4d2a152013-04-02 19:38:47 +00009344 SetDeclDeleted(Destructor, ClassLoc);
Richard Smith6b02d462012-12-08 08:32:28 +00009345
Douglas Gregor7454c562010-07-02 20:37:36 +00009346 // Note that we have declared this destructor.
Douglas Gregor7454c562010-07-02 20:37:36 +00009347 ++ASTContext::NumImplicitDestructorsDeclared;
Richard Smithd3b5c9082012-07-27 04:22:15 +00009348
Douglas Gregor7454c562010-07-02 20:37:36 +00009349 // Introduce this destructor into its scope.
Douglas Gregor0be31a22010-07-02 17:43:08 +00009350 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor7454c562010-07-02 20:37:36 +00009351 PushOnScopeChains(Destructor, S, false);
9352 ClassDecl->addDecl(Destructor);
Alexis Huntf91729462011-05-12 22:46:25 +00009353
Douglas Gregorf1203042010-07-01 19:09:28 +00009354 return Destructor;
9355}
9356
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009357void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00009358 CXXDestructorDecl *Destructor) {
Alexis Hunt61ae8d32011-05-23 23:14:04 +00009359 assert((Destructor->isDefaulted() &&
Richard Smith273c4e92012-02-26 07:51:39 +00009360 !Destructor->doesThisDeclarationHaveABody() &&
9361 !Destructor->isDeleted()) &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009362 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +00009363 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009364 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00009365
Douglas Gregor54818f02010-05-12 16:39:35 +00009366 if (Destructor->isInvalidDecl())
9367 return;
9368
Eli Friedmaneaf34142012-10-18 20:14:08 +00009369 SynthesizedFunctionScope Scope(*this, Destructor);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00009370
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00009371 DiagnosticErrorTrap Trap(Diags);
John McCalla6309952010-03-16 21:39:52 +00009372 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
9373 Destructor->getParent());
Mike Stump11289f42009-09-09 15:08:12 +00009374
Douglas Gregor54818f02010-05-12 16:39:35 +00009375 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00009376 Diag(CurrentLocation, diag::note_member_synthesized_at)
9377 << CXXDestructor << Context.getTagDeclType(ClassDecl);
9378
9379 Destructor->setInvalidDecl();
9380 return;
9381 }
9382
Ben Langmuir2f8e6b82014-09-25 20:55:00 +00009383 // The exception specification is needed because we are defining the
9384 // function.
9385 ResolveExceptionSpec(CurrentLocation,
9386 Destructor->getType()->castAs<FunctionProtoType>());
9387
Daniel Jasperb3b0b802014-06-20 08:44:22 +00009388 SourceLocation Loc = Destructor->getLocEnd().isValid()
9389 ? Destructor->getLocEnd()
9390 : Destructor->getLocation();
Benjamin Kramere2a929d2012-07-04 17:03:41 +00009391 Destructor->setBody(new (Context) CompoundStmt(Loc));
Eli Friedman276dd182013-09-05 00:02:25 +00009392 Destructor->markUsed(Context);
Douglas Gregor88d292c2010-05-13 16:44:06 +00009393 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00009394
9395 if (ASTMutationListener *L = getASTMutationListener()) {
9396 L->CompletedImplicitDefinition(Destructor);
9397 }
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009398}
9399
Richard Smith84973e52012-04-21 18:42:51 +00009400/// \brief Perform any semantic analysis which needs to be delayed until all
9401/// pending class member declarations have been parsed.
9402void Sema::ActOnFinishCXXMemberDecls() {
Douglas Gregorbc0e5c02013-02-01 04:49:10 +00009403 // If the context is an invalid C++ class, just suppress these checks.
9404 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
9405 if (Record->isInvalidDecl()) {
Alp Tokerae3a9442013-10-18 05:54:19 +00009406 DelayedDefaultedMemberExceptionSpecs.clear();
Richard Smith88f45492014-11-22 03:09:05 +00009407 DelayedExceptionSpecChecks.clear();
Douglas Gregorbc0e5c02013-02-01 04:49:10 +00009408 return;
9409 }
9410 }
Richard Smith84973e52012-04-21 18:42:51 +00009411}
9412
Richard Smithd3b5c9082012-07-27 04:22:15 +00009413void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
9414 CXXDestructorDecl *Destructor) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009415 assert(getLangOpts().CPlusPlus11 &&
Richard Smithd3b5c9082012-07-27 04:22:15 +00009416 "adjusting dtor exception specs was introduced in c++11");
9417
Sebastian Redl623ea822011-05-19 05:13:44 +00009418 // C++11 [class.dtor]p3:
9419 // A declaration of a destructor that does not have an exception-
9420 // specification is implicitly considered to have the same exception-
9421 // specification as an implicit declaration.
Richard Smithd3b5c9082012-07-27 04:22:15 +00009422 const FunctionProtoType *DtorType = Destructor->getType()->
Sebastian Redl623ea822011-05-19 05:13:44 +00009423 getAs<FunctionProtoType>();
Richard Smithd3b5c9082012-07-27 04:22:15 +00009424 if (DtorType->hasExceptionSpec())
Sebastian Redl623ea822011-05-19 05:13:44 +00009425 return;
9426
Chandler Carruth9a797572011-09-20 04:55:26 +00009427 // Replace the destructor's type, building off the existing one. Fortunately,
9428 // the only thing of interest in the destructor type is its extended info.
9429 // The return and arguments are fixed.
Richard Smithd3b5c9082012-07-27 04:22:15 +00009430 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
Richard Smith8acb4282014-07-31 21:57:55 +00009431 EPI.ExceptionSpec.Type = EST_Unevaluated;
9432 EPI.ExceptionSpec.SourceDecl = Destructor;
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00009433 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smith84973e52012-04-21 18:42:51 +00009434
Sebastian Redl623ea822011-05-19 05:13:44 +00009435 // FIXME: If the destructor has a body that could throw, and the newly created
9436 // spec doesn't allow exceptions, we should emit a warning, because this
9437 // change in behavior can break conforming C++03 programs at runtime.
Richard Smithd3b5c9082012-07-27 04:22:15 +00009438 // However, we don't have a body or an exception specification yet, so it
9439 // needs to be done somewhere else.
Sebastian Redl623ea822011-05-19 05:13:44 +00009440}
9441
Pavel Labath58934982013-08-30 08:52:28 +00009442namespace {
9443/// \brief An abstract base class for all helper classes used in building the
9444// copy/move operators. These classes serve as factory functions and help us
9445// avoid using the same Expr* in the AST twice.
9446class ExprBuilder {
9447 ExprBuilder(const ExprBuilder&) LLVM_DELETED_FUNCTION;
9448 ExprBuilder &operator=(const ExprBuilder&) LLVM_DELETED_FUNCTION;
9449
9450protected:
9451 static Expr *assertNotNull(Expr *E) {
9452 assert(E && "Expression construction must not fail.");
9453 return E;
9454 }
9455
9456public:
9457 ExprBuilder() {}
9458 virtual ~ExprBuilder() {}
9459
9460 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
9461};
9462
9463class RefBuilder: public ExprBuilder {
9464 VarDecl *Var;
9465 QualType VarType;
9466
9467public:
David Blaikie1cbb9712014-11-14 19:09:44 +00009468 Expr *build(Sema &S, SourceLocation Loc) const override {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009469 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get());
Pavel Labath58934982013-08-30 08:52:28 +00009470 }
9471
9472 RefBuilder(VarDecl *Var, QualType VarType)
9473 : Var(Var), VarType(VarType) {}
9474};
9475
9476class ThisBuilder: public ExprBuilder {
9477public:
David Blaikie1cbb9712014-11-14 19:09:44 +00009478 Expr *build(Sema &S, SourceLocation Loc) const override {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009479 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
Pavel Labath58934982013-08-30 08:52:28 +00009480 }
9481};
9482
9483class CastBuilder: public ExprBuilder {
9484 const ExprBuilder &Builder;
9485 QualType Type;
9486 ExprValueKind Kind;
9487 const CXXCastPath &Path;
9488
9489public:
David Blaikie1cbb9712014-11-14 19:09:44 +00009490 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009491 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
9492 CK_UncheckedDerivedToBase, Kind,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009493 &Path).get());
Pavel Labath58934982013-08-30 08:52:28 +00009494 }
9495
9496 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
9497 const CXXCastPath &Path)
9498 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
9499};
9500
9501class DerefBuilder: public ExprBuilder {
9502 const ExprBuilder &Builder;
9503
9504public:
David Blaikie1cbb9712014-11-14 19:09:44 +00009505 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009506 return assertNotNull(
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009507 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
Pavel Labath58934982013-08-30 08:52:28 +00009508 }
9509
9510 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9511};
9512
9513class MemberBuilder: public ExprBuilder {
9514 const ExprBuilder &Builder;
9515 QualType Type;
9516 CXXScopeSpec SS;
9517 bool IsArrow;
9518 LookupResult &MemberLookup;
9519
9520public:
David Blaikie1cbb9712014-11-14 19:09:44 +00009521 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009522 return assertNotNull(S.BuildMemberReferenceExpr(
Craig Topperc3ec1492014-05-26 06:22:03 +00009523 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009524 nullptr, MemberLookup, nullptr).get());
Pavel Labath58934982013-08-30 08:52:28 +00009525 }
9526
9527 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
9528 LookupResult &MemberLookup)
9529 : Builder(Builder), Type(Type), IsArrow(IsArrow),
9530 MemberLookup(MemberLookup) {}
9531};
9532
9533class MoveCastBuilder: public ExprBuilder {
9534 const ExprBuilder &Builder;
9535
9536public:
David Blaikie1cbb9712014-11-14 19:09:44 +00009537 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009538 return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
9539 }
9540
9541 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9542};
9543
9544class LvalueConvBuilder: public ExprBuilder {
9545 const ExprBuilder &Builder;
9546
9547public:
David Blaikie1cbb9712014-11-14 19:09:44 +00009548 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009549 return assertNotNull(
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009550 S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
Pavel Labath58934982013-08-30 08:52:28 +00009551 }
9552
9553 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9554};
9555
9556class SubscriptBuilder: public ExprBuilder {
9557 const ExprBuilder &Base;
9558 const ExprBuilder &Index;
9559
9560public:
David Blaikie1cbb9712014-11-14 19:09:44 +00009561 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009562 return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009563 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
Pavel Labath58934982013-08-30 08:52:28 +00009564 }
9565
9566 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
9567 : Base(Base), Index(Index) {}
9568};
9569
9570} // end anonymous namespace
9571
Richard Smith41ae3282012-11-14 00:50:40 +00009572/// When generating a defaulted copy or move assignment operator, if a field
9573/// should be copied with __builtin_memcpy rather than via explicit assignments,
9574/// do so. This optimization only applies for arrays of scalars, and for arrays
9575/// of class type where the selected copy/move-assignment operator is trivial.
9576static StmtResult
9577buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +00009578 const ExprBuilder &ToB, const ExprBuilder &FromB) {
Richard Smith41ae3282012-11-14 00:50:40 +00009579 // Compute the size of the memory buffer to be copied.
9580 QualType SizeType = S.Context.getSizeType();
9581 llvm::APInt Size(S.Context.getTypeSize(SizeType),
9582 S.Context.getTypeSizeInChars(T).getQuantity());
9583
9584 // Take the address of the field references for "from" and "to". We
9585 // directly construct UnaryOperators here because semantic analysis
9586 // does not permit us to take the address of an xvalue.
Pavel Labath58934982013-08-30 08:52:28 +00009587 Expr *From = FromB.build(S, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009588 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
9589 S.Context.getPointerType(From->getType()),
9590 VK_RValue, OK_Ordinary, Loc);
Pavel Labath58934982013-08-30 08:52:28 +00009591 Expr *To = ToB.build(S, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009592 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
9593 S.Context.getPointerType(To->getType()),
9594 VK_RValue, OK_Ordinary, Loc);
9595
9596 const Type *E = T->getBaseElementTypeUnsafe();
9597 bool NeedsCollectableMemCpy =
9598 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
9599
9600 // Create a reference to the __builtin_objc_memmove_collectable function
9601 StringRef MemCpyName = NeedsCollectableMemCpy ?
9602 "__builtin_objc_memmove_collectable" :
9603 "__builtin_memcpy";
9604 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
9605 Sema::LookupOrdinaryName);
9606 S.LookupName(R, S.TUScope, true);
9607
9608 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
9609 if (!MemCpy)
9610 // Something went horribly wrong earlier, and we will have complained
9611 // about it.
9612 return StmtError();
9613
9614 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
Craig Topperc3ec1492014-05-26 06:22:03 +00009615 VK_RValue, Loc, nullptr);
Richard Smith41ae3282012-11-14 00:50:40 +00009616 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
9617
9618 Expr *CallArgs[] = {
9619 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
9620 };
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009621 ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
Richard Smith41ae3282012-11-14 00:50:40 +00009622 Loc, CallArgs, Loc);
9623
9624 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00009625 return Call.getAs<Stmt>();
Richard Smith41ae3282012-11-14 00:50:40 +00009626}
9627
Sebastian Redl22653ba2011-08-30 19:58:05 +00009628/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregorb139cd52010-05-01 20:49:11 +00009629/// \c To.
9630///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009631/// This routine is used to copy/move the members of a class with an
9632/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregorb139cd52010-05-01 20:49:11 +00009633/// copied are arrays, this routine builds for loops to copy them.
9634///
9635/// \param S The Sema object used for type-checking.
9636///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009637/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregorb139cd52010-05-01 20:49:11 +00009638///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009639/// \param T The type of the expressions being copied/moved. Both expressions
9640/// must have this type.
Douglas Gregorb139cd52010-05-01 20:49:11 +00009641///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009642/// \param To The expression we are copying/moving to.
Douglas Gregorb139cd52010-05-01 20:49:11 +00009643///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009644/// \param From The expression we are copying/moving from.
Douglas Gregorb139cd52010-05-01 20:49:11 +00009645///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009646/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009647/// Otherwise, it's a non-static member subobject.
9648///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009649/// \param Copying Whether we're copying or moving.
9650///
Douglas Gregorb139cd52010-05-01 20:49:11 +00009651/// \param Depth Internal parameter recording the depth of the recursion.
9652///
Richard Smith41ae3282012-11-14 00:50:40 +00009653/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
9654/// if a memcpy should be used instead.
John McCalldadc5752010-08-24 06:29:42 +00009655static StmtResult
Richard Smith41ae3282012-11-14 00:50:40 +00009656buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +00009657 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith41ae3282012-11-14 00:50:40 +00009658 bool CopyingBaseSubobject, bool Copying,
9659 unsigned Depth = 0) {
Richard Smith52c0b582012-11-13 00:54:12 +00009660 // C++11 [class.copy]p28:
Douglas Gregorb139cd52010-05-01 20:49:11 +00009661 // Each subobject is assigned in the manner appropriate to its type:
9662 //
Sebastian Redl22653ba2011-08-30 19:58:05 +00009663 // - if the subobject is of class type, as if by a call to operator= with
9664 // the subobject as the object expression and the corresponding
9665 // subobject of x as a single function argument (as if by explicit
9666 // qualification; that is, ignoring any possible virtual overriding
9667 // functions in more derived classes);
Richard Smith52c0b582012-11-13 00:54:12 +00009668 //
9669 // C++03 [class.copy]p13:
9670 // - if the subobject is of class type, the copy assignment operator for
9671 // the class is used (as if by explicit qualification; that is,
9672 // ignoring any possible virtual overriding functions in more derived
9673 // classes);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009674 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
9675 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith52c0b582012-11-13 00:54:12 +00009676
Douglas Gregorb139cd52010-05-01 20:49:11 +00009677 // Look for operator=.
9678 DeclarationName Name
9679 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9680 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
9681 S.LookupQualifiedName(OpLookup, ClassDecl, false);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009682
Richard Smith52c0b582012-11-13 00:54:12 +00009683 // Prior to C++11, filter out any result that isn't a copy/move-assignment
9684 // operator.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009685 if (!S.getLangOpts().CPlusPlus11) {
Richard Smith52c0b582012-11-13 00:54:12 +00009686 LookupResult::Filter F = OpLookup.makeFilter();
9687 while (F.hasNext()) {
9688 NamedDecl *D = F.next();
9689 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
9690 if (Method->isCopyAssignmentOperator() ||
9691 (!Copying && Method->isMoveAssignmentOperator()))
9692 continue;
9693
9694 F.erase();
9695 }
9696 F.done();
John McCallab8c2732010-03-16 06:11:48 +00009697 }
Richard Smith52c0b582012-11-13 00:54:12 +00009698
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009699 // Suppress the protected check (C++ [class.protected]) for each of the
Richard Smith52c0b582012-11-13 00:54:12 +00009700 // assignment operators we found. This strange dance is required when
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009701 // we're assigning via a base classes's copy-assignment operator. To
Richard Smith52c0b582012-11-13 00:54:12 +00009702 // ensure that we're getting the right base class subobject (without
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009703 // ambiguities), we need to cast "this" to that subobject type; to
9704 // ensure that we don't go through the virtual call mechanism, we need
9705 // to qualify the operator= name with the base class (see below). However,
9706 // this means that if the base class has a protected copy assignment
9707 // operator, the protected member access check will fail. So, we
9708 // rewrite "protected" access to "public" access in this case, since we
9709 // know by construction that we're calling from a derived class.
9710 if (CopyingBaseSubobject) {
9711 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
9712 L != LEnd; ++L) {
9713 if (L.getAccess() == AS_protected)
9714 L.setAccess(AS_public);
9715 }
9716 }
Richard Smith52c0b582012-11-13 00:54:12 +00009717
Douglas Gregorb139cd52010-05-01 20:49:11 +00009718 // Create the nested-name-specifier that will be used to qualify the
9719 // reference to operator=; this is required to suppress the virtual
9720 // call mechanism.
9721 CXXScopeSpec SS;
Manuel Klimeke7167412012-02-06 21:51:39 +00009722 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Richard Smith52c0b582012-11-13 00:54:12 +00009723 SS.MakeTrivial(S.Context,
Craig Topperc3ec1492014-05-26 06:22:03 +00009724 NestedNameSpecifier::Create(S.Context, nullptr, false,
Manuel Klimeke7167412012-02-06 21:51:39 +00009725 CanonicalT),
Douglas Gregor869ad452011-02-24 17:54:50 +00009726 Loc);
Richard Smith52c0b582012-11-13 00:54:12 +00009727
Douglas Gregorb139cd52010-05-01 20:49:11 +00009728 // Create the reference to operator=.
John McCalldadc5752010-08-24 06:29:42 +00009729 ExprResult OpEqualRef
Pavel Labath58934982013-08-30 08:52:28 +00009730 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
9731 SS, /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00009732 /*FirstQualifierInScope=*/nullptr,
Abramo Bagnara7945c982012-01-27 09:46:47 +00009733 OpLookup,
Craig Topperc3ec1492014-05-26 06:22:03 +00009734 /*TemplateArgs=*/nullptr,
Douglas Gregorb139cd52010-05-01 20:49:11 +00009735 /*SuppressQualifierCheck=*/true);
9736 if (OpEqualRef.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009737 return StmtError();
Richard Smith52c0b582012-11-13 00:54:12 +00009738
Douglas Gregorb139cd52010-05-01 20:49:11 +00009739 // Build the call to the assignment operator.
John McCallb268a282010-08-23 23:25:46 +00009740
Pavel Labath58934982013-08-30 08:52:28 +00009741 Expr *FromInst = From.build(S, Loc);
Craig Topperc3ec1492014-05-26 06:22:03 +00009742 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009743 OpEqualRef.getAs<Expr>(),
Pavel Labath58934982013-08-30 08:52:28 +00009744 Loc, FromInst, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009745 if (Call.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009746 return StmtError();
Richard Smith52c0b582012-11-13 00:54:12 +00009747
Richard Smith41ae3282012-11-14 00:50:40 +00009748 // If we built a call to a trivial 'operator=' while copying an array,
9749 // bail out. We'll replace the whole shebang with a memcpy.
9750 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
9751 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
Craig Topperc3ec1492014-05-26 06:22:03 +00009752 return StmtResult((Stmt*)nullptr);
Richard Smith41ae3282012-11-14 00:50:40 +00009753
Richard Smith52c0b582012-11-13 00:54:12 +00009754 // Convert to an expression-statement, and clean up any produced
9755 // temporaries.
Richard Smith945f8d32013-01-14 22:39:08 +00009756 return S.ActOnExprStmt(Call);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009757 }
John McCallab8c2732010-03-16 06:11:48 +00009758
Richard Smith52c0b582012-11-13 00:54:12 +00009759 // - if the subobject is of scalar type, the built-in assignment
Douglas Gregorb139cd52010-05-01 20:49:11 +00009760 // operator is used.
Richard Smith52c0b582012-11-13 00:54:12 +00009761 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009762 if (!ArrayTy) {
Pavel Labath58934982013-08-30 08:52:28 +00009763 ExprResult Assignment = S.CreateBuiltinBinOp(
9764 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00009765 if (Assignment.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009766 return StmtError();
Richard Smith945f8d32013-01-14 22:39:08 +00009767 return S.ActOnExprStmt(Assignment);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009768 }
Richard Smith52c0b582012-11-13 00:54:12 +00009769
9770 // - if the subobject is an array, each element is assigned, in the
Douglas Gregorb139cd52010-05-01 20:49:11 +00009771 // manner appropriate to the element type;
Richard Smith52c0b582012-11-13 00:54:12 +00009772
Douglas Gregorb139cd52010-05-01 20:49:11 +00009773 // Construct a loop over the array bounds, e.g.,
9774 //
9775 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
9776 //
9777 // that will copy each of the array elements.
9778 QualType SizeType = S.Context.getSizeType();
Richard Smith41ae3282012-11-14 00:50:40 +00009779
Douglas Gregorb139cd52010-05-01 20:49:11 +00009780 // Create the iteration variable.
Craig Topperc3ec1492014-05-26 06:22:03 +00009781 IdentifierInfo *IterationVarName = nullptr;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009782 {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00009783 SmallString<8> Str;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009784 llvm::raw_svector_ostream OS(Str);
9785 OS << "__i" << Depth;
9786 IterationVarName = &S.Context.Idents.get(OS.str());
9787 }
Abramo Bagnaradff19302011-03-08 08:55:46 +00009788 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregorb139cd52010-05-01 20:49:11 +00009789 IterationVarName, SizeType,
9790 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00009791 SC_None);
Richard Smith41ae3282012-11-14 00:50:40 +00009792
Douglas Gregorb139cd52010-05-01 20:49:11 +00009793 // Initialize the iteration variable to zero.
9794 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00009795 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00009796
Pavel Labath58934982013-08-30 08:52:28 +00009797 // Creates a reference to the iteration variable.
9798 RefBuilder IterationVarRef(IterationVar, SizeType);
9799 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
Eli Friedman844f9452012-01-23 02:35:22 +00009800
Douglas Gregorb139cd52010-05-01 20:49:11 +00009801 // Create the DeclStmt that holds the iteration variable.
9802 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009803
Douglas Gregorb139cd52010-05-01 20:49:11 +00009804 // Subscript the "from" and "to" expressions with the iteration variable.
Pavel Labath58934982013-08-30 08:52:28 +00009805 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
9806 MoveCastBuilder FromIndexMove(FromIndexCopy);
9807 const ExprBuilder *FromIndex;
9808 if (Copying)
9809 FromIndex = &FromIndexCopy;
9810 else
9811 FromIndex = &FromIndexMove;
9812
9813 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009814
9815 // Build the copy/move for an individual element of the array.
Richard Smith41ae3282012-11-14 00:50:40 +00009816 StmtResult Copy =
9817 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
Pavel Labath58934982013-08-30 08:52:28 +00009818 ToIndex, *FromIndex, CopyingBaseSubobject,
Richard Smith41ae3282012-11-14 00:50:40 +00009819 Copying, Depth + 1);
9820 // Bail out if copying fails or if we determined that we should use memcpy.
9821 if (Copy.isInvalid() || !Copy.get())
9822 return Copy;
9823
9824 // Create the comparison against the array bound.
9825 llvm::APInt Upper
9826 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
9827 Expr *Comparison
Pavel Labath58934982013-08-30 08:52:28 +00009828 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
Richard Smith41ae3282012-11-14 00:50:40 +00009829 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
9830 BO_NE, S.Context.BoolTy,
9831 VK_RValue, OK_Ordinary, Loc, false);
9832
9833 // Create the pre-increment of the iteration variable.
9834 Expr *Increment
Pavel Labath58934982013-08-30 08:52:28 +00009835 = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
9836 SizeType, VK_LValue, OK_Ordinary, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009837
Douglas Gregorb139cd52010-05-01 20:49:11 +00009838 // Construct the loop that copies all elements of this array.
John McCallb268a282010-08-23 23:25:46 +00009839 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregorb139cd52010-05-01 20:49:11 +00009840 S.MakeFullExpr(Comparison),
Craig Topperc3ec1492014-05-26 06:22:03 +00009841 nullptr, S.MakeFullDiscardedValueExpr(Increment),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009842 Loc, Copy.get());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009843}
9844
Richard Smith41ae3282012-11-14 00:50:40 +00009845static StmtResult
9846buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +00009847 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith41ae3282012-11-14 00:50:40 +00009848 bool CopyingBaseSubobject, bool Copying) {
9849 // Maybe we should use a memcpy?
9850 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
9851 T.isTriviallyCopyableType(S.Context))
9852 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9853
9854 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
9855 CopyingBaseSubobject,
9856 Copying, 0));
9857
9858 // If we ended up picking a trivial assignment operator for an array of a
9859 // non-trivially-copyable class type, just emit a memcpy.
9860 if (!Result.isInvalid() && !Result.get())
9861 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9862
9863 return Result;
9864}
9865
Richard Smithd3b5c9082012-07-27 04:22:15 +00009866Sema::ImplicitExceptionSpecification
9867Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
9868 CXXRecordDecl *ClassDecl = MD->getParent();
9869
9870 ImplicitExceptionSpecification ExceptSpec(*this);
9871 if (ClassDecl->isInvalidDecl())
9872 return ExceptSpec;
9873
9874 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00009875 assert(T->getNumParams() == 1 && "not a copy assignment op");
9876 unsigned ArgQuals =
9877 T->getParamType(0).getNonReferenceType().getCVRQualifiers();
Richard Smithd3b5c9082012-07-27 04:22:15 +00009878
Douglas Gregor68e11362010-07-01 17:48:08 +00009879 // C++ [except.spec]p14:
Richard Smithd3b5c9082012-07-27 04:22:15 +00009880 // An implicitly declared special member function (Clause 12) shall have an
Douglas Gregor68e11362010-07-01 17:48:08 +00009881 // exception-specification. [...]
Alexis Hunt491ec602011-06-21 23:42:56 +00009882
9883 // It is unspecified whether or not an implicit copy assignment operator
9884 // attempts to deduplicate calls to assignment operators of virtual bases are
9885 // made. As such, this exception specification is effectively unspecified.
9886 // Based on a similar decision made for constness in C++0x, we're erring on
9887 // the side of assuming such calls to be made regardless of whether they
9888 // actually happen.
Aaron Ballman574705e2014-03-13 15:41:46 +00009889 for (const auto &Base : ClassDecl->bases()) {
9890 if (Base.isVirtual())
Alexis Hunt491ec602011-06-21 23:42:56 +00009891 continue;
9892
Douglas Gregor330b9cf2010-07-02 21:50:04 +00009893 CXXRecordDecl *BaseClassDecl
Aaron Ballman574705e2014-03-13 15:41:46 +00009894 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +00009895 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9896 ArgQuals, false, 0))
Aaron Ballman574705e2014-03-13 15:41:46 +00009897 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
Douglas Gregor68e11362010-07-01 17:48:08 +00009898 }
Alexis Hunt491ec602011-06-21 23:42:56 +00009899
Aaron Ballman445a9392014-03-13 16:15:17 +00009900 for (const auto &Base : ClassDecl->vbases()) {
Alexis Hunt491ec602011-06-21 23:42:56 +00009901 CXXRecordDecl *BaseClassDecl
Aaron Ballman445a9392014-03-13 16:15:17 +00009902 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +00009903 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9904 ArgQuals, false, 0))
Aaron Ballman445a9392014-03-13 16:15:17 +00009905 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
Alexis Hunt491ec602011-06-21 23:42:56 +00009906 }
9907
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009908 for (const auto *Field : ClassDecl->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00009909 QualType FieldType = Context.getBaseElementType(Field->getType());
Alexis Hunt491ec602011-06-21 23:42:56 +00009910 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9911 if (CXXMethodDecl *CopyAssign =
Richard Smith1c6461e2012-07-18 03:36:00 +00009912 LookupCopyingAssignment(FieldClassDecl,
9913 ArgQuals | FieldType.getCVRQualifiers(),
9914 false, 0))
Richard Smithf623c962012-04-17 00:58:00 +00009915 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00009916 }
Douglas Gregor68e11362010-07-01 17:48:08 +00009917 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00009918
Richard Smithd3b5c9082012-07-27 04:22:15 +00009919 return ExceptSpec;
Alexis Hunt119f3652011-05-14 05:23:20 +00009920}
9921
9922CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
9923 // Note: The following rules are largely analoguous to the copy
9924 // constructor rules. Note that virtual bases are not taken into account
9925 // for determining the argument type of the operator. Note also that
9926 // operators taking an object instead of a reference are allowed.
Richard Smith2be35f52012-12-01 02:35:44 +00009927 assert(ClassDecl->needsImplicitCopyAssignment());
Alexis Hunt119f3652011-05-14 05:23:20 +00009928
Richard Smith8bf22e52012-11-29 01:34:07 +00009929 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
9930 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +00009931 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +00009932
Alexis Hunt119f3652011-05-14 05:23:20 +00009933 QualType ArgType = Context.getTypeDeclType(ClassDecl);
9934 QualType RetType = Context.getLValueReferenceType(ArgType);
Richard Smith99005e62013-05-07 03:19:20 +00009935 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
9936 if (Const)
Alexis Hunt119f3652011-05-14 05:23:20 +00009937 ArgType = ArgType.withConst();
9938 ArgType = Context.getLValueReferenceType(ArgType);
9939
Richard Smith99005e62013-05-07 03:19:20 +00009940 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9941 CXXCopyAssignment,
9942 Const);
9943
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009944 // An implicitly-declared copy assignment operator is an inline public
9945 // member of its class.
9946 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaradff19302011-03-08 08:55:46 +00009947 SourceLocation ClassLoc = ClassDecl->getLocation();
9948 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith99005e62013-05-07 03:19:20 +00009949 CXXMethodDecl *CopyAssignment =
9950 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00009951 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
9952 /*isInline=*/true, Constexpr, SourceLocation());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009953 CopyAssignment->setAccess(AS_public);
Alexis Huntb2f27802011-05-14 05:23:24 +00009954 CopyAssignment->setDefaulted();
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009955 CopyAssignment->setImplicit();
Richard Smithd3b5c9082012-07-27 04:22:15 +00009956
Eli Bendersky9a220fc2014-09-29 20:38:29 +00009957 if (getLangOpts().CUDA) {
9958 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
9959 CopyAssignment,
9960 /* ConstRHS */ Const,
9961 /* Diagnose */ false);
9962 }
9963
Richard Smithd3b5c9082012-07-27 04:22:15 +00009964 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +00009965 FunctionProtoType::ExtProtoInfo EPI =
9966 getImplicitMethodEPI(*this, CopyAssignment);
Jordan Rose5c382722013-03-08 21:51:21 +00009967 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00009968
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009969 // Add the parameter to the operator.
9970 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Craig Topperc3ec1492014-05-26 06:22:03 +00009971 ClassLoc, ClassLoc,
9972 /*Id=*/nullptr, ArgType,
9973 /*TInfo=*/nullptr, SC_None,
9974 nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +00009975 CopyAssignment->setParams(FromParam);
Alexis Huntb2f27802011-05-14 05:23:24 +00009976
Richard Smith6b02d462012-12-08 08:32:28 +00009977 AddOverriddenMethods(ClassDecl, CopyAssignment);
9978
9979 CopyAssignment->setTrivial(
9980 ClassDecl->needsOverloadResolutionForCopyAssignment()
9981 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
9982 : ClassDecl->hasTrivialCopyAssignment());
9983
Richard Smith852265f2012-03-30 20:53:28 +00009984 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
Richard Smithb4d2a152013-04-02 19:38:47 +00009985 SetDeclDeleted(CopyAssignment, ClassLoc);
Richard Smith852265f2012-03-30 20:53:28 +00009986
Richard Smith6b02d462012-12-08 08:32:28 +00009987 // Note that we have added this copy-assignment operator.
9988 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
9989
9990 if (Scope *S = getScopeForContext(ClassDecl))
9991 PushOnScopeChains(CopyAssignment, S, false);
9992 ClassDecl->addDecl(CopyAssignment);
9993
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009994 return CopyAssignment;
9995}
9996
Richard Smithd577fbb2013-06-13 03:23:42 +00009997/// Diagnose an implicit copy operation for a class which is odr-used, but
9998/// which is deprecated because the class has a user-declared copy constructor,
9999/// copy assignment operator, or destructor.
10000static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
10001 SourceLocation UseLoc) {
10002 assert(CopyOp->isImplicit());
10003
10004 CXXRecordDecl *RD = CopyOp->getParent();
Craig Topperc3ec1492014-05-26 06:22:03 +000010005 CXXMethodDecl *UserDeclaredOperation = nullptr;
Richard Smithd577fbb2013-06-13 03:23:42 +000010006
10007 // In Microsoft mode, assignment operations don't affect constructors and
10008 // vice versa.
10009 if (RD->hasUserDeclaredDestructor()) {
10010 UserDeclaredOperation = RD->getDestructor();
10011 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
10012 RD->hasUserDeclaredCopyConstructor() &&
Alp Tokerbfa39342014-01-14 12:51:41 +000010013 !S.getLangOpts().MSVCCompat) {
Richard Smithd577fbb2013-06-13 03:23:42 +000010014 // Find any user-declared copy constructor.
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +000010015 for (auto *I : RD->ctors()) {
Richard Smithd577fbb2013-06-13 03:23:42 +000010016 if (I->isCopyConstructor()) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +000010017 UserDeclaredOperation = I;
Richard Smithd577fbb2013-06-13 03:23:42 +000010018 break;
10019 }
10020 }
10021 assert(UserDeclaredOperation);
10022 } else if (isa<CXXConstructorDecl>(CopyOp) &&
10023 RD->hasUserDeclaredCopyAssignment() &&
Alp Tokerbfa39342014-01-14 12:51:41 +000010024 !S.getLangOpts().MSVCCompat) {
Richard Smithd577fbb2013-06-13 03:23:42 +000010025 // Find any user-declared move assignment operator.
Aaron Ballman2b124d12014-03-13 16:36:16 +000010026 for (auto *I : RD->methods()) {
Richard Smithd577fbb2013-06-13 03:23:42 +000010027 if (I->isCopyAssignmentOperator()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +000010028 UserDeclaredOperation = I;
Richard Smithd577fbb2013-06-13 03:23:42 +000010029 break;
10030 }
10031 }
10032 assert(UserDeclaredOperation);
10033 }
10034
10035 if (UserDeclaredOperation) {
10036 S.Diag(UserDeclaredOperation->getLocation(),
10037 diag::warn_deprecated_copy_operation)
10038 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
10039 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
10040 S.Diag(UseLoc, diag::note_member_synthesized_at)
10041 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
10042 : Sema::CXXCopyAssignment)
10043 << RD;
10044 }
10045}
10046
Douglas Gregorb139cd52010-05-01 20:49:11 +000010047void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
10048 CXXMethodDecl *CopyAssignOperator) {
Alexis Huntb2f27802011-05-14 05:23:24 +000010049 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregorb139cd52010-05-01 20:49:11 +000010050 CopyAssignOperator->isOverloadedOperator() &&
10051 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith273c4e92012-02-26 07:51:39 +000010052 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
10053 !CopyAssignOperator->isDeleted()) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +000010054 "DefineImplicitCopyAssignment called for wrong function");
10055
10056 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
10057
10058 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
10059 CopyAssignOperator->setInvalidDecl();
10060 return;
10061 }
Richard Smithd577fbb2013-06-13 03:23:42 +000010062
10063 // C++11 [class.copy]p18:
10064 // The [definition of an implicitly declared copy assignment operator] is
10065 // deprecated if the class has a user-declared copy constructor or a
10066 // user-declared destructor.
10067 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
10068 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
10069
Eli Friedman276dd182013-09-05 00:02:25 +000010070 CopyAssignOperator->markUsed(Context);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010071
Eli Friedmaneaf34142012-10-18 20:14:08 +000010072 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +000010073 DiagnosticErrorTrap Trap(Diags);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010074
10075 // C++0x [class.copy]p30:
10076 // The implicitly-defined or explicitly-defaulted copy assignment operator
10077 // for a non-union class X performs memberwise copy assignment of its
10078 // subobjects. The direct base classes of X are assigned first, in the
10079 // order of their declaration in the base-specifier-list, and then the
10080 // immediate non-static data members of X are assigned, in the order in
10081 // which they were declared in the class definition.
10082
10083 // The statements that form the synthesized function body.
Benjamin Kramerf0623432012-08-23 22:51:59 +000010084 SmallVector<Stmt*, 8> Statements;
Douglas Gregorb139cd52010-05-01 20:49:11 +000010085
10086 // The parameter for the "other" object, which we are copying from.
10087 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
10088 Qualifiers OtherQuals = Other->getType().getQualifiers();
10089 QualType OtherRefType = Other->getType();
10090 if (const LValueReferenceType *OtherRef
10091 = OtherRefType->getAs<LValueReferenceType>()) {
10092 OtherRefType = OtherRef->getPointeeType();
10093 OtherQuals = OtherRefType.getQualifiers();
10094 }
10095
10096 // Our location for everything implicitly-generated.
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010097 SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid()
10098 ? CopyAssignOperator->getLocEnd()
10099 : CopyAssignOperator->getLocation();
10100
Pavel Labath58934982013-08-30 08:52:28 +000010101 // Builds a DeclRefExpr for the "other" object.
10102 RefBuilder OtherRef(Other, OtherRefType);
10103
10104 // Builds the "this" pointer.
10105 ThisBuilder This;
Douglas Gregorb139cd52010-05-01 20:49:11 +000010106
10107 // Assign base classes.
10108 bool Invalid = false;
Aaron Ballman574705e2014-03-13 15:41:46 +000010109 for (auto &Base : ClassDecl->bases()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +000010110 // Form the assignment:
10111 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
Aaron Ballman574705e2014-03-13 15:41:46 +000010112 QualType BaseType = Base.getType().getUnqualifiedType();
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +000010113 if (!BaseType->isRecordType()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +000010114 Invalid = true;
10115 continue;
10116 }
10117
John McCallcf142162010-08-07 06:22:56 +000010118 CXXCastPath BasePath;
Aaron Ballman574705e2014-03-13 15:41:46 +000010119 BasePath.push_back(&Base);
John McCallcf142162010-08-07 06:22:56 +000010120
Douglas Gregorb139cd52010-05-01 20:49:11 +000010121 // Construct the "from" expression, which is an implicit cast to the
10122 // appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +000010123 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
10124 VK_LValue, BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010125
10126 // Dereference "this".
Pavel Labath58934982013-08-30 08:52:28 +000010127 DerefBuilder DerefThis(This);
10128 CastBuilder To(DerefThis,
10129 Context.getCVRQualifiedType(
10130 BaseType, CopyAssignOperator->getTypeQualifiers()),
10131 VK_LValue, BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010132
10133 // Build the copy.
Richard Smith41ae3282012-11-14 00:50:40 +000010134 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath58934982013-08-30 08:52:28 +000010135 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +000010136 /*CopyingBaseSubobject=*/true,
10137 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010138 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +000010139 Diag(CurrentLocation, diag::note_member_synthesized_at)
10140 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10141 CopyAssignOperator->setInvalidDecl();
10142 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +000010143 }
10144
10145 // Success! Record the copy.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010146 Statements.push_back(Copy.getAs<Expr>());
Douglas Gregorb139cd52010-05-01 20:49:11 +000010147 }
10148
Douglas Gregorb139cd52010-05-01 20:49:11 +000010149 // Assign non-static members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010150 for (auto *Field : ClassDecl->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +000010151 if (Field->isUnnamedBitfield())
10152 continue;
Eli Friedmanc9817fd2013-06-07 01:48:56 +000010153
10154 if (Field->isInvalidDecl()) {
10155 Invalid = true;
10156 continue;
10157 }
10158
Douglas Gregorb139cd52010-05-01 20:49:11 +000010159 // Check for members of reference type; we can't copy those.
10160 if (Field->getType()->isReferenceType()) {
10161 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10162 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
10163 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +000010164 Diag(CurrentLocation, diag::note_member_synthesized_at)
10165 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010166 Invalid = true;
10167 continue;
10168 }
10169
10170 // Check for members of const-qualified, non-class type.
10171 QualType BaseType = Context.getBaseElementType(Field->getType());
10172 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
10173 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10174 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
10175 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +000010176 Diag(CurrentLocation, diag::note_member_synthesized_at)
10177 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010178 Invalid = true;
10179 continue;
10180 }
John McCall1b1a1db2011-06-17 00:18:42 +000010181
10182 // Suppress assigning zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +000010183 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
10184 continue;
Douglas Gregorb139cd52010-05-01 20:49:11 +000010185
10186 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +000010187 if (FieldType->isIncompleteArrayType()) {
10188 assert(ClassDecl->hasFlexibleArrayMember() &&
10189 "Incomplete array type is not valid");
10190 continue;
10191 }
Douglas Gregorb139cd52010-05-01 20:49:11 +000010192
10193 // Build references to the field in the object we're copying from and to.
10194 CXXScopeSpec SS; // Intentionally empty
10195 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
10196 LookupMemberName);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010197 MemberLookup.addDecl(Field);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010198 MemberLookup.resolveKind();
Pavel Labath58934982013-08-30 08:52:28 +000010199
10200 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
10201
10202 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010203
Douglas Gregorb139cd52010-05-01 20:49:11 +000010204 // Build the copy of this field.
Richard Smith41ae3282012-11-14 00:50:40 +000010205 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath58934982013-08-30 08:52:28 +000010206 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +000010207 /*CopyingBaseSubobject=*/false,
10208 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010209 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +000010210 Diag(CurrentLocation, diag::note_member_synthesized_at)
10211 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10212 CopyAssignOperator->setInvalidDecl();
10213 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +000010214 }
10215
10216 // Success! Record the copy.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010217 Statements.push_back(Copy.getAs<Stmt>());
Douglas Gregorb139cd52010-05-01 20:49:11 +000010218 }
10219
10220 if (!Invalid) {
10221 // Add a "return *this;"
Pavel Labath58934982013-08-30 08:52:28 +000010222 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +000010223
Nick Lewyckyd78f92f2014-05-03 00:41:18 +000010224 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
Douglas Gregorb139cd52010-05-01 20:49:11 +000010225 if (Return.isInvalid())
10226 Invalid = true;
10227 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010228 Statements.push_back(Return.getAs<Stmt>());
Douglas Gregor54818f02010-05-12 16:39:35 +000010229
10230 if (Trap.hasErrorOccurred()) {
10231 Diag(CurrentLocation, diag::note_member_synthesized_at)
10232 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10233 Invalid = true;
10234 }
Douglas Gregorb139cd52010-05-01 20:49:11 +000010235 }
10236 }
10237
Ben Langmuir2f8e6b82014-09-25 20:55:00 +000010238 // The exception specification is needed because we are defining the
10239 // function.
10240 ResolveExceptionSpec(CurrentLocation,
10241 CopyAssignOperator->getType()->castAs<FunctionProtoType>());
10242
Douglas Gregorb139cd52010-05-01 20:49:11 +000010243 if (Invalid) {
10244 CopyAssignOperator->setInvalidDecl();
10245 return;
10246 }
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010247
10248 StmtResult Body;
10249 {
10250 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010251 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010252 /*isStmtExpr=*/false);
10253 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
10254 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010255 CopyAssignOperator->setBody(Body.getAs<Stmt>());
Sebastian Redlab238a72011-04-24 16:28:06 +000010256
10257 if (ASTMutationListener *L = getASTMutationListener()) {
10258 L->CompletedImplicitDefinition(CopyAssignOperator);
10259 }
Fariborz Jahanian41f79272009-06-25 21:45:19 +000010260}
10261
Sebastian Redl22653ba2011-08-30 19:58:05 +000010262Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +000010263Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
10264 CXXRecordDecl *ClassDecl = MD->getParent();
Sebastian Redl22653ba2011-08-30 19:58:05 +000010265
Richard Smithd3b5c9082012-07-27 04:22:15 +000010266 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010267 if (ClassDecl->isInvalidDecl())
10268 return ExceptSpec;
10269
10270 // C++0x [except.spec]p14:
10271 // An implicitly declared special member function (Clause 12) shall have an
10272 // exception-specification. [...]
10273
10274 // It is unspecified whether or not an implicit move assignment operator
10275 // attempts to deduplicate calls to assignment operators of virtual bases are
10276 // made. As such, this exception specification is effectively unspecified.
10277 // Based on a similar decision made for constness in C++0x, we're erring on
10278 // the side of assuming such calls to be made regardless of whether they
10279 // actually happen.
10280 // Note that a move constructor is not implicitly declared when there are
10281 // virtual bases, but it can still be user-declared and explicitly defaulted.
Aaron Ballman574705e2014-03-13 15:41:46 +000010282 for (const auto &Base : ClassDecl->bases()) {
10283 if (Base.isVirtual())
Sebastian Redl22653ba2011-08-30 19:58:05 +000010284 continue;
10285
10286 CXXRecordDecl *BaseClassDecl
Aaron Ballman574705e2014-03-13 15:41:46 +000010287 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010288 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith1c6461e2012-07-18 03:36:00 +000010289 0, false, 0))
Aaron Ballman574705e2014-03-13 15:41:46 +000010290 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010291 }
10292
Aaron Ballman445a9392014-03-13 16:15:17 +000010293 for (const auto &Base : ClassDecl->vbases()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000010294 CXXRecordDecl *BaseClassDecl
Aaron Ballman445a9392014-03-13 16:15:17 +000010295 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010296 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith1c6461e2012-07-18 03:36:00 +000010297 0, false, 0))
Aaron Ballman445a9392014-03-13 16:15:17 +000010298 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010299 }
10300
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010301 for (const auto *Field : ClassDecl->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +000010302 QualType FieldType = Context.getBaseElementType(Field->getType());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010303 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith1c6461e2012-07-18 03:36:00 +000010304 if (CXXMethodDecl *MoveAssign =
10305 LookupMovingAssignment(FieldClassDecl,
10306 FieldType.getCVRQualifiers(),
10307 false, 0))
Richard Smithf623c962012-04-17 00:58:00 +000010308 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010309 }
10310 }
10311
10312 return ExceptSpec;
10313}
10314
10315CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +000010316 assert(ClassDecl->needsImplicitMoveAssignment());
10317
Richard Smith8bf22e52012-11-29 01:34:07 +000010318 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
10319 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000010320 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000010321
Sebastian Redl22653ba2011-08-30 19:58:05 +000010322 // Note: The following rules are largely analoguous to the move
10323 // constructor rules.
10324
Sebastian Redl22653ba2011-08-30 19:58:05 +000010325 QualType ArgType = Context.getTypeDeclType(ClassDecl);
10326 QualType RetType = Context.getLValueReferenceType(ArgType);
10327 ArgType = Context.getRValueReferenceType(ArgType);
10328
Richard Smith99005e62013-05-07 03:19:20 +000010329 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10330 CXXMoveAssignment,
10331 false);
10332
Sebastian Redl22653ba2011-08-30 19:58:05 +000010333 // An implicitly-declared move assignment operator is an inline public
10334 // member of its class.
Sebastian Redl22653ba2011-08-30 19:58:05 +000010335 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
10336 SourceLocation ClassLoc = ClassDecl->getLocation();
10337 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith99005e62013-05-07 03:19:20 +000010338 CXXMethodDecl *MoveAssignment =
10339 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Craig Topperc3ec1492014-05-26 06:22:03 +000010340 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
Richard Smith99005e62013-05-07 03:19:20 +000010341 /*isInline=*/true, Constexpr, SourceLocation());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010342 MoveAssignment->setAccess(AS_public);
10343 MoveAssignment->setDefaulted();
10344 MoveAssignment->setImplicit();
Sebastian Redl22653ba2011-08-30 19:58:05 +000010345
Eli Bendersky9a220fc2014-09-29 20:38:29 +000010346 if (getLangOpts().CUDA) {
10347 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
10348 MoveAssignment,
10349 /* ConstRHS */ false,
10350 /* Diagnose */ false);
10351 }
10352
Richard Smithd3b5c9082012-07-27 04:22:15 +000010353 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000010354 FunctionProtoType::ExtProtoInfo EPI =
10355 getImplicitMethodEPI(*this, MoveAssignment);
Jordan Rose5c382722013-03-08 21:51:21 +000010356 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000010357
Sebastian Redl22653ba2011-08-30 19:58:05 +000010358 // Add the parameter to the operator.
10359 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
Craig Topperc3ec1492014-05-26 06:22:03 +000010360 ClassLoc, ClassLoc,
10361 /*Id=*/nullptr, ArgType,
10362 /*TInfo=*/nullptr, SC_None,
10363 nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +000010364 MoveAssignment->setParams(FromParam);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010365
Richard Smith6b02d462012-12-08 08:32:28 +000010366 AddOverriddenMethods(ClassDecl, MoveAssignment);
10367
10368 MoveAssignment->setTrivial(
10369 ClassDecl->needsOverloadResolutionForMoveAssignment()
10370 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
10371 : ClassDecl->hasTrivialMoveAssignment());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010372
Richard Smithd951a1d2012-02-18 02:02:13 +000010373 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Richard Smith8b86f2d2013-11-04 01:48:18 +000010374 ClassDecl->setImplicitMoveAssignmentIsDeleted();
10375 SetDeclDeleted(MoveAssignment, ClassLoc);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010376 }
10377
Richard Smith6b02d462012-12-08 08:32:28 +000010378 // Note that we have added this copy-assignment operator.
10379 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
10380
Sebastian Redl22653ba2011-08-30 19:58:05 +000010381 if (Scope *S = getScopeForContext(ClassDecl))
10382 PushOnScopeChains(MoveAssignment, S, false);
10383 ClassDecl->addDecl(MoveAssignment);
10384
Sebastian Redl22653ba2011-08-30 19:58:05 +000010385 return MoveAssignment;
10386}
10387
Richard Smithb2504bd2013-11-04 04:26:14 +000010388/// Check if we're implicitly defining a move assignment operator for a class
10389/// with virtual bases. Such a move assignment might move-assign the virtual
10390/// base multiple times.
10391static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
10392 SourceLocation CurrentLocation) {
10393 assert(!Class->isDependentContext() && "should not define dependent move");
10394
10395 // Only a virtual base could get implicitly move-assigned multiple times.
10396 // Only a non-trivial move assignment can observe this. We only want to
10397 // diagnose if we implicitly define an assignment operator that assigns
10398 // two base classes, both of which move-assign the same virtual base.
10399 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
10400 Class->getNumBases() < 2)
10401 return;
10402
10403 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
10404 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
10405 VBaseMap VBases;
10406
Aaron Ballman574705e2014-03-13 15:41:46 +000010407 for (auto &BI : Class->bases()) {
10408 Worklist.push_back(&BI);
Richard Smithb2504bd2013-11-04 04:26:14 +000010409 while (!Worklist.empty()) {
10410 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
10411 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
10412
10413 // If the base has no non-trivial move assignment operators,
10414 // we don't care about moves from it.
10415 if (!Base->hasNonTrivialMoveAssignment())
10416 continue;
10417
10418 // If there's nothing virtual here, skip it.
10419 if (!BaseSpec->isVirtual() && !Base->getNumVBases())
10420 continue;
10421
10422 // If we're not actually going to call a move assignment for this base,
10423 // or the selected move assignment is trivial, skip it.
10424 Sema::SpecialMemberOverloadResult *SMOR =
10425 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
10426 /*ConstArg*/false, /*VolatileArg*/false,
10427 /*RValueThis*/true, /*ConstThis*/false,
10428 /*VolatileThis*/false);
10429 if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() ||
10430 !SMOR->getMethod()->isMoveAssignmentOperator())
10431 continue;
10432
10433 if (BaseSpec->isVirtual()) {
10434 // We're going to move-assign this virtual base, and its move
10435 // assignment operator is not trivial. If this can happen for
10436 // multiple distinct direct bases of Class, diagnose it. (If it
10437 // only happens in one base, we'll diagnose it when synthesizing
10438 // that base class's move assignment operator.)
10439 CXXBaseSpecifier *&Existing =
Aaron Ballman574705e2014-03-13 15:41:46 +000010440 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
Richard Smithb2504bd2013-11-04 04:26:14 +000010441 .first->second;
Aaron Ballman574705e2014-03-13 15:41:46 +000010442 if (Existing && Existing != &BI) {
Richard Smithb2504bd2013-11-04 04:26:14 +000010443 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
10444 << Class << Base;
10445 S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here)
10446 << (Base->getCanonicalDecl() ==
10447 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
10448 << Base << Existing->getType() << Existing->getSourceRange();
Aaron Ballman574705e2014-03-13 15:41:46 +000010449 S.Diag(BI.getLocStart(), diag::note_vbase_moved_here)
Richard Smithb2504bd2013-11-04 04:26:14 +000010450 << (Base->getCanonicalDecl() ==
Aaron Ballman574705e2014-03-13 15:41:46 +000010451 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
10452 << Base << BI.getType() << BaseSpec->getSourceRange();
Richard Smithb2504bd2013-11-04 04:26:14 +000010453
10454 // Only diagnose each vbase once.
Craig Topperc3ec1492014-05-26 06:22:03 +000010455 Existing = nullptr;
Richard Smithb2504bd2013-11-04 04:26:14 +000010456 }
10457 } else {
10458 // Only walk over bases that have defaulted move assignment operators.
10459 // We assume that any user-provided move assignment operator handles
10460 // the multiple-moves-of-vbase case itself somehow.
10461 if (!SMOR->getMethod()->isDefaulted())
10462 continue;
10463
10464 // We're going to move the base classes of Base. Add them to the list.
Aaron Ballman574705e2014-03-13 15:41:46 +000010465 for (auto &BI : Base->bases())
10466 Worklist.push_back(&BI);
Richard Smithb2504bd2013-11-04 04:26:14 +000010467 }
10468 }
10469 }
10470}
10471
Sebastian Redl22653ba2011-08-30 19:58:05 +000010472void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
10473 CXXMethodDecl *MoveAssignOperator) {
10474 assert((MoveAssignOperator->isDefaulted() &&
10475 MoveAssignOperator->isOverloadedOperator() &&
10476 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith273c4e92012-02-26 07:51:39 +000010477 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
10478 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl22653ba2011-08-30 19:58:05 +000010479 "DefineImplicitMoveAssignment called for wrong function");
10480
10481 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
10482
10483 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
10484 MoveAssignOperator->setInvalidDecl();
10485 return;
10486 }
10487
Eli Friedman276dd182013-09-05 00:02:25 +000010488 MoveAssignOperator->markUsed(Context);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010489
Eli Friedmaneaf34142012-10-18 20:14:08 +000010490 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010491 DiagnosticErrorTrap Trap(Diags);
10492
10493 // C++0x [class.copy]p28:
10494 // The implicitly-defined or move assignment operator for a non-union class
10495 // X performs memberwise move assignment of its subobjects. The direct base
10496 // classes of X are assigned first, in the order of their declaration in the
10497 // base-specifier-list, and then the immediate non-static data members of X
10498 // are assigned, in the order in which they were declared in the class
10499 // definition.
10500
Richard Smithb2504bd2013-11-04 04:26:14 +000010501 // Issue a warning if our implicit move assignment operator will move
10502 // from a virtual base more than once.
10503 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
Richard Smith8b86f2d2013-11-04 01:48:18 +000010504
Sebastian Redl22653ba2011-08-30 19:58:05 +000010505 // The statements that form the synthesized function body.
Benjamin Kramerf0623432012-08-23 22:51:59 +000010506 SmallVector<Stmt*, 8> Statements;
Sebastian Redl22653ba2011-08-30 19:58:05 +000010507
10508 // The parameter for the "other" object, which we are move from.
10509 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
10510 QualType OtherRefType = Other->getType()->
10511 getAs<RValueReferenceType>()->getPointeeType();
David Blaikie7d170102013-05-15 07:37:26 +000010512 assert(!OtherRefType.getQualifiers() &&
Sebastian Redl22653ba2011-08-30 19:58:05 +000010513 "Bad argument type of defaulted move assignment");
10514
10515 // Our location for everything implicitly-generated.
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010516 SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid()
10517 ? MoveAssignOperator->getLocEnd()
10518 : MoveAssignOperator->getLocation();
Sebastian Redl22653ba2011-08-30 19:58:05 +000010519
Pavel Labath58934982013-08-30 08:52:28 +000010520 // Builds a reference to the "other" object.
10521 RefBuilder OtherRef(Other, OtherRefType);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010522 // Cast to rvalue.
Pavel Labath58934982013-08-30 08:52:28 +000010523 MoveCastBuilder MoveOther(OtherRef);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010524
Pavel Labath58934982013-08-30 08:52:28 +000010525 // Builds the "this" pointer.
10526 ThisBuilder This;
Richard Smithcf8ec8d2012-04-02 18:40:40 +000010527
Sebastian Redl22653ba2011-08-30 19:58:05 +000010528 // Assign base classes.
10529 bool Invalid = false;
Aaron Ballman574705e2014-03-13 15:41:46 +000010530 for (auto &Base : ClassDecl->bases()) {
Richard Smithb2504bd2013-11-04 04:26:14 +000010531 // C++11 [class.copy]p28:
10532 // It is unspecified whether subobjects representing virtual base classes
10533 // are assigned more than once by the implicitly-defined copy assignment
10534 // operator.
10535 // FIXME: Do not assign to a vbase that will be assigned by some other base
10536 // class. For a move-assignment, this can result in the vbase being moved
10537 // multiple times.
10538
Sebastian Redl22653ba2011-08-30 19:58:05 +000010539 // Form the assignment:
10540 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
Aaron Ballman574705e2014-03-13 15:41:46 +000010541 QualType BaseType = Base.getType().getUnqualifiedType();
Sebastian Redl22653ba2011-08-30 19:58:05 +000010542 if (!BaseType->isRecordType()) {
10543 Invalid = true;
10544 continue;
10545 }
10546
10547 CXXCastPath BasePath;
Aaron Ballman574705e2014-03-13 15:41:46 +000010548 BasePath.push_back(&Base);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010549
10550 // Construct the "from" expression, which is an implicit cast to the
10551 // appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +000010552 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010553
10554 // Dereference "this".
Pavel Labath58934982013-08-30 08:52:28 +000010555 DerefBuilder DerefThis(This);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010556
10557 // Implicitly cast "this" to the appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +000010558 CastBuilder To(DerefThis,
10559 Context.getCVRQualifiedType(
10560 BaseType, MoveAssignOperator->getTypeQualifiers()),
10561 VK_LValue, BasePath);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010562
10563 // Build the move.
Richard Smith41ae3282012-11-14 00:50:40 +000010564 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath58934982013-08-30 08:52:28 +000010565 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +000010566 /*CopyingBaseSubobject=*/true,
10567 /*Copying=*/false);
10568 if (Move.isInvalid()) {
10569 Diag(CurrentLocation, diag::note_member_synthesized_at)
10570 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10571 MoveAssignOperator->setInvalidDecl();
10572 return;
10573 }
10574
10575 // Success! Record the move.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010576 Statements.push_back(Move.getAs<Expr>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010577 }
10578
Sebastian Redl22653ba2011-08-30 19:58:05 +000010579 // Assign non-static members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010580 for (auto *Field : ClassDecl->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +000010581 if (Field->isUnnamedBitfield())
10582 continue;
10583
Eli Friedmanc9817fd2013-06-07 01:48:56 +000010584 if (Field->isInvalidDecl()) {
10585 Invalid = true;
10586 continue;
10587 }
10588
Sebastian Redl22653ba2011-08-30 19:58:05 +000010589 // Check for members of reference type; we can't move those.
10590 if (Field->getType()->isReferenceType()) {
10591 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10592 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
10593 Diag(Field->getLocation(), diag::note_declared_at);
10594 Diag(CurrentLocation, diag::note_member_synthesized_at)
10595 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10596 Invalid = true;
10597 continue;
10598 }
10599
10600 // Check for members of const-qualified, non-class type.
10601 QualType BaseType = Context.getBaseElementType(Field->getType());
10602 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
10603 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10604 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
10605 Diag(Field->getLocation(), diag::note_declared_at);
10606 Diag(CurrentLocation, diag::note_member_synthesized_at)
10607 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10608 Invalid = true;
10609 continue;
10610 }
10611
10612 // Suppress assigning zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +000010613 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
10614 continue;
Sebastian Redl22653ba2011-08-30 19:58:05 +000010615
10616 QualType FieldType = Field->getType().getNonReferenceType();
10617 if (FieldType->isIncompleteArrayType()) {
10618 assert(ClassDecl->hasFlexibleArrayMember() &&
10619 "Incomplete array type is not valid");
10620 continue;
10621 }
10622
10623 // Build references to the field in the object we're copying from and to.
Sebastian Redl22653ba2011-08-30 19:58:05 +000010624 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
10625 LookupMemberName);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010626 MemberLookup.addDecl(Field);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010627 MemberLookup.resolveKind();
Pavel Labath58934982013-08-30 08:52:28 +000010628 MemberBuilder From(MoveOther, OtherRefType,
10629 /*IsArrow=*/false, MemberLookup);
10630 MemberBuilder To(This, getCurrentThisType(),
10631 /*IsArrow=*/true, MemberLookup);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010632
Pavel Labath58934982013-08-30 08:52:28 +000010633 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
Sebastian Redl22653ba2011-08-30 19:58:05 +000010634 "Member reference with rvalue base must be rvalue except for reference "
10635 "members, which aren't allowed for move assignment.");
10636
Sebastian Redl22653ba2011-08-30 19:58:05 +000010637 // Build the move of this field.
Richard Smith41ae3282012-11-14 00:50:40 +000010638 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath58934982013-08-30 08:52:28 +000010639 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +000010640 /*CopyingBaseSubobject=*/false,
10641 /*Copying=*/false);
10642 if (Move.isInvalid()) {
10643 Diag(CurrentLocation, diag::note_member_synthesized_at)
10644 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10645 MoveAssignOperator->setInvalidDecl();
10646 return;
10647 }
Richard Smith11d19592012-11-12 23:33:00 +000010648
Sebastian Redl22653ba2011-08-30 19:58:05 +000010649 // Success! Record the copy.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010650 Statements.push_back(Move.getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010651 }
10652
10653 if (!Invalid) {
10654 // Add a "return *this;"
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010655 ExprResult ThisObj =
10656 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
10657
Nick Lewyckyd78f92f2014-05-03 00:41:18 +000010658 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010659 if (Return.isInvalid())
10660 Invalid = true;
10661 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010662 Statements.push_back(Return.getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010663
10664 if (Trap.hasErrorOccurred()) {
10665 Diag(CurrentLocation, diag::note_member_synthesized_at)
10666 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10667 Invalid = true;
10668 }
10669 }
10670 }
10671
Ben Langmuir2f8e6b82014-09-25 20:55:00 +000010672 // The exception specification is needed because we are defining the
10673 // function.
10674 ResolveExceptionSpec(CurrentLocation,
10675 MoveAssignOperator->getType()->castAs<FunctionProtoType>());
10676
Sebastian Redl22653ba2011-08-30 19:58:05 +000010677 if (Invalid) {
10678 MoveAssignOperator->setInvalidDecl();
10679 return;
10680 }
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010681
10682 StmtResult Body;
10683 {
10684 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010685 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010686 /*isStmtExpr=*/false);
10687 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
10688 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010689 MoveAssignOperator->setBody(Body.getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010690
10691 if (ASTMutationListener *L = getASTMutationListener()) {
10692 L->CompletedImplicitDefinition(MoveAssignOperator);
10693 }
10694}
10695
Richard Smithd3b5c9082012-07-27 04:22:15 +000010696Sema::ImplicitExceptionSpecification
10697Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
10698 CXXRecordDecl *ClassDecl = MD->getParent();
10699
10700 ImplicitExceptionSpecification ExceptSpec(*this);
10701 if (ClassDecl->isInvalidDecl())
10702 return ExceptSpec;
10703
10704 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +000010705 assert(T->getNumParams() >= 1 && "not a copy ctor");
10706 unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers();
Richard Smithd3b5c9082012-07-27 04:22:15 +000010707
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010708 // C++ [except.spec]p14:
10709 // An implicitly declared special member function (Clause 12) shall have an
10710 // exception-specification. [...]
Aaron Ballman574705e2014-03-13 15:41:46 +000010711 for (const auto &Base : ClassDecl->bases()) {
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010712 // Virtual bases are handled below.
Aaron Ballman574705e2014-03-13 15:41:46 +000010713 if (Base.isVirtual())
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010714 continue;
10715
Douglas Gregora6d69502010-07-02 23:41:54 +000010716 CXXRecordDecl *BaseClassDecl
Aaron Ballman574705e2014-03-13 15:41:46 +000010717 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +000010718 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +000010719 LookupCopyingConstructor(BaseClassDecl, Quals))
Aaron Ballman574705e2014-03-13 15:41:46 +000010720 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010721 }
Aaron Ballman445a9392014-03-13 16:15:17 +000010722 for (const auto &Base : ClassDecl->vbases()) {
Douglas Gregora6d69502010-07-02 23:41:54 +000010723 CXXRecordDecl *BaseClassDecl
Aaron Ballman445a9392014-03-13 16:15:17 +000010724 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +000010725 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +000010726 LookupCopyingConstructor(BaseClassDecl, Quals))
Aaron Ballman445a9392014-03-13 16:15:17 +000010727 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010728 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010729 for (const auto *Field : ClassDecl->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +000010730 QualType FieldType = Context.getBaseElementType(Field->getType());
Alexis Hunt899bd442011-06-10 04:44:37 +000010731 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10732 if (CXXConstructorDecl *CopyConstructor =
Richard Smith1c6461e2012-07-18 03:36:00 +000010733 LookupCopyingConstructor(FieldClassDecl,
10734 Quals | FieldType.getCVRQualifiers()))
Richard Smithf623c962012-04-17 00:58:00 +000010735 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010736 }
10737 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +000010738
Richard Smithd3b5c9082012-07-27 04:22:15 +000010739 return ExceptSpec;
Alexis Hunt913820d2011-05-13 06:10:58 +000010740}
10741
10742CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
10743 CXXRecordDecl *ClassDecl) {
10744 // C++ [class.copy]p4:
10745 // If the class definition does not explicitly declare a copy
10746 // constructor, one is declared implicitly.
Richard Smith2be35f52012-12-01 02:35:44 +000010747 assert(ClassDecl->needsImplicitCopyConstructor());
Alexis Hunt913820d2011-05-13 06:10:58 +000010748
Richard Smith8bf22e52012-11-29 01:34:07 +000010749 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
10750 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000010751 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000010752
Alexis Hunt913820d2011-05-13 06:10:58 +000010753 QualType ClassType = Context.getTypeDeclType(ClassDecl);
10754 QualType ArgType = ClassType;
Richard Smith1c33fe82012-11-28 06:23:12 +000010755 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
Alexis Hunt913820d2011-05-13 06:10:58 +000010756 if (Const)
10757 ArgType = ArgType.withConst();
10758 ArgType = Context.getLValueReferenceType(ArgType);
Alexis Hunt913820d2011-05-13 06:10:58 +000010759
Richard Smithb5800092012-06-10 05:43:50 +000010760 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10761 CXXCopyConstructor,
10762 Const);
10763
Douglas Gregor54be3392010-07-01 17:57:27 +000010764 DeclarationName Name
10765 = Context.DeclarationNames.getCXXConstructorName(
10766 Context.getCanonicalType(ClassType));
Abramo Bagnaradff19302011-03-08 08:55:46 +000010767 SourceLocation ClassLoc = ClassDecl->getLocation();
10768 DeclarationNameInfo NameInfo(Name, ClassLoc);
Alexis Hunt913820d2011-05-13 06:10:58 +000010769
10770 // An implicitly-declared copy constructor is an inline public
Richard Smithcc36f692011-12-22 02:22:31 +000010771 // member of its class.
10772 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +000010773 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
Richard Smithcc36f692011-12-22 02:22:31 +000010774 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smithb5800092012-06-10 05:43:50 +000010775 Constexpr);
Douglas Gregor54be3392010-07-01 17:57:27 +000010776 CopyConstructor->setAccess(AS_public);
Alexis Hunt913820d2011-05-13 06:10:58 +000010777 CopyConstructor->setDefaulted();
Richard Smithcc36f692011-12-22 02:22:31 +000010778
Eli Bendersky9a220fc2014-09-29 20:38:29 +000010779 if (getLangOpts().CUDA) {
10780 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
10781 CopyConstructor,
10782 /* ConstRHS */ Const,
10783 /* Diagnose */ false);
10784 }
10785
Richard Smithd3b5c9082012-07-27 04:22:15 +000010786 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000010787 FunctionProtoType::ExtProtoInfo EPI =
10788 getImplicitMethodEPI(*this, CopyConstructor);
Richard Smithd3b5c9082012-07-27 04:22:15 +000010789 CopyConstructor->setType(
Jordan Rose5c382722013-03-08 21:51:21 +000010790 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000010791
Douglas Gregor54be3392010-07-01 17:57:27 +000010792 // Add the parameter to the constructor.
10793 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaradff19302011-03-08 08:55:46 +000010794 ClassLoc, ClassLoc,
Craig Topperc3ec1492014-05-26 06:22:03 +000010795 /*IdentifierInfo=*/nullptr,
10796 ArgType, /*TInfo=*/nullptr,
10797 SC_None, nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +000010798 CopyConstructor->setParams(FromParam);
Alexis Hunt913820d2011-05-13 06:10:58 +000010799
Richard Smith6b02d462012-12-08 08:32:28 +000010800 CopyConstructor->setTrivial(
10801 ClassDecl->needsOverloadResolutionForCopyConstructor()
10802 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
10803 : ClassDecl->hasTrivialCopyConstructor());
Alexis Hunte77a28f2011-05-18 03:41:58 +000010804
Richard Smith852265f2012-03-30 20:53:28 +000010805 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Richard Smithb4d2a152013-04-02 19:38:47 +000010806 SetDeclDeleted(CopyConstructor, ClassLoc);
Richard Smith852265f2012-03-30 20:53:28 +000010807
Richard Smith6b02d462012-12-08 08:32:28 +000010808 // Note that we have declared this constructor.
10809 ++ASTContext::NumImplicitCopyConstructorsDeclared;
10810
10811 if (Scope *S = getScopeForContext(ClassDecl))
10812 PushOnScopeChains(CopyConstructor, S, false);
10813 ClassDecl->addDecl(CopyConstructor);
10814
Douglas Gregor54be3392010-07-01 17:57:27 +000010815 return CopyConstructor;
10816}
10817
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010818void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Alexis Hunt913820d2011-05-13 06:10:58 +000010819 CXXConstructorDecl *CopyConstructor) {
10820 assert((CopyConstructor->isDefaulted() &&
10821 CopyConstructor->isCopyConstructor() &&
Richard Smith273c4e92012-02-26 07:51:39 +000010822 !CopyConstructor->doesThisDeclarationHaveABody() &&
10823 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010824 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +000010825
Anders Carlsson7a0ffdb2010-04-23 16:24:12 +000010826 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010827 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010828
Richard Smithd577fbb2013-06-13 03:23:42 +000010829 // C++11 [class.copy]p7:
Benjamin Kramer60509af2013-09-09 14:48:42 +000010830 // The [definition of an implicitly declared copy constructor] is
Richard Smithd577fbb2013-06-13 03:23:42 +000010831 // deprecated if the class has a user-declared copy assignment operator
10832 // or a user-declared destructor.
10833 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
10834 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
10835
Eli Friedmaneaf34142012-10-18 20:14:08 +000010836 SynthesizedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +000010837 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010838
David Blaikie3fc2f912013-01-17 05:26:25 +000010839 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +000010840 Trap.hasErrorOccurred()) {
Anders Carlsson79111502010-05-01 16:39:01 +000010841 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregor94f9a482010-05-05 05:51:00 +000010842 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson79111502010-05-01 16:39:01 +000010843 CopyConstructor->setInvalidDecl();
Douglas Gregor94f9a482010-05-05 05:51:00 +000010844 } else {
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010845 SourceLocation Loc = CopyConstructor->getLocEnd().isValid()
10846 ? CopyConstructor->getLocEnd()
10847 : CopyConstructor->getLocation();
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010848 Sema::CompoundScopeRAII CompoundScope(*this);
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010849 CopyConstructor->setBody(
10850 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
Anders Carlsson53e1ba92010-04-25 00:52:09 +000010851 }
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +000010852
Ben Langmuir2f8e6b82014-09-25 20:55:00 +000010853 // The exception specification is needed because we are defining the
10854 // function.
10855 ResolveExceptionSpec(CurrentLocation,
10856 CopyConstructor->getType()->castAs<FunctionProtoType>());
10857
Eli Friedman276dd182013-09-05 00:02:25 +000010858 CopyConstructor->markUsed(Context);
Reid Kleckner3be586f2014-07-18 01:48:10 +000010859 MarkVTableUsed(CurrentLocation, ClassDecl);
10860
Sebastian Redlab238a72011-04-24 16:28:06 +000010861 if (ASTMutationListener *L = getASTMutationListener()) {
10862 L->CompletedImplicitDefinition(CopyConstructor);
10863 }
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010864}
10865
Sebastian Redl22653ba2011-08-30 19:58:05 +000010866Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +000010867Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
10868 CXXRecordDecl *ClassDecl = MD->getParent();
10869
Sebastian Redl22653ba2011-08-30 19:58:05 +000010870 // C++ [except.spec]p14:
10871 // An implicitly declared special member function (Clause 12) shall have an
10872 // exception-specification. [...]
Richard Smithf623c962012-04-17 00:58:00 +000010873 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010874 if (ClassDecl->isInvalidDecl())
10875 return ExceptSpec;
10876
10877 // Direct base-class constructors.
Aaron Ballman574705e2014-03-13 15:41:46 +000010878 for (const auto &B : ClassDecl->bases()) {
10879 if (B.isVirtual()) // Handled below.
Sebastian Redl22653ba2011-08-30 19:58:05 +000010880 continue;
10881
Aaron Ballman574705e2014-03-13 15:41:46 +000010882 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000010883 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith1c6461e2012-07-18 03:36:00 +000010884 CXXConstructorDecl *Constructor =
10885 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010886 // If this is a deleted function, add it anyway. This might be conformant
10887 // with the standard. This might not. I'm not sure. It might not matter.
10888 if (Constructor)
Aaron Ballman574705e2014-03-13 15:41:46 +000010889 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010890 }
10891 }
10892
10893 // Virtual base-class constructors.
Aaron Ballman445a9392014-03-13 16:15:17 +000010894 for (const auto &B : ClassDecl->vbases()) {
10895 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000010896 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith1c6461e2012-07-18 03:36:00 +000010897 CXXConstructorDecl *Constructor =
10898 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010899 // If this is a deleted function, add it anyway. This might be conformant
10900 // with the standard. This might not. I'm not sure. It might not matter.
10901 if (Constructor)
Aaron Ballman445a9392014-03-13 16:15:17 +000010902 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010903 }
10904 }
10905
10906 // Field constructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010907 for (const auto *F : ClassDecl->fields()) {
Richard Smith1c6461e2012-07-18 03:36:00 +000010908 QualType FieldType = Context.getBaseElementType(F->getType());
10909 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
10910 CXXConstructorDecl *Constructor =
10911 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010912 // If this is a deleted function, add it anyway. This might be conformant
10913 // with the standard. This might not. I'm not sure. It might not matter.
10914 // In particular, the problem is that this function never gets called. It
10915 // might just be ill-formed because this function attempts to refer to
10916 // a deleted function here.
10917 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +000010918 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010919 }
10920 }
10921
10922 return ExceptSpec;
10923}
10924
10925CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
10926 CXXRecordDecl *ClassDecl) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +000010927 assert(ClassDecl->needsImplicitMoveConstructor());
10928
Richard Smith8bf22e52012-11-29 01:34:07 +000010929 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
10930 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000010931 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000010932
Sebastian Redl22653ba2011-08-30 19:58:05 +000010933 QualType ClassType = Context.getTypeDeclType(ClassDecl);
10934 QualType ArgType = Context.getRValueReferenceType(ClassType);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010935
Richard Smithb5800092012-06-10 05:43:50 +000010936 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10937 CXXMoveConstructor,
10938 false);
10939
Sebastian Redl22653ba2011-08-30 19:58:05 +000010940 DeclarationName Name
10941 = Context.DeclarationNames.getCXXConstructorName(
10942 Context.getCanonicalType(ClassType));
10943 SourceLocation ClassLoc = ClassDecl->getLocation();
10944 DeclarationNameInfo NameInfo(Name, ClassLoc);
10945
Richard Smith99005e62013-05-07 03:19:20 +000010946 // C++11 [class.copy]p11:
Sebastian Redl22653ba2011-08-30 19:58:05 +000010947 // An implicitly-declared copy/move constructor is an inline public
Richard Smithcc36f692011-12-22 02:22:31 +000010948 // member of its class.
10949 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +000010950 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
Richard Smithcc36f692011-12-22 02:22:31 +000010951 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smithb5800092012-06-10 05:43:50 +000010952 Constexpr);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010953 MoveConstructor->setAccess(AS_public);
10954 MoveConstructor->setDefaulted();
Richard Smithcc36f692011-12-22 02:22:31 +000010955
Eli Bendersky9a220fc2014-09-29 20:38:29 +000010956 if (getLangOpts().CUDA) {
10957 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
10958 MoveConstructor,
10959 /* ConstRHS */ false,
10960 /* Diagnose */ false);
10961 }
10962
Richard Smithd3b5c9082012-07-27 04:22:15 +000010963 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000010964 FunctionProtoType::ExtProtoInfo EPI =
10965 getImplicitMethodEPI(*this, MoveConstructor);
Richard Smithd3b5c9082012-07-27 04:22:15 +000010966 MoveConstructor->setType(
Jordan Rose5c382722013-03-08 21:51:21 +000010967 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000010968
Sebastian Redl22653ba2011-08-30 19:58:05 +000010969 // Add the parameter to the constructor.
10970 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
10971 ClassLoc, ClassLoc,
Craig Topperc3ec1492014-05-26 06:22:03 +000010972 /*IdentifierInfo=*/nullptr,
10973 ArgType, /*TInfo=*/nullptr,
10974 SC_None, nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +000010975 MoveConstructor->setParams(FromParam);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010976
Richard Smith6b02d462012-12-08 08:32:28 +000010977 MoveConstructor->setTrivial(
10978 ClassDecl->needsOverloadResolutionForMoveConstructor()
10979 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
10980 : ClassDecl->hasTrivialMoveConstructor());
10981
Alexis Hunt77c1f9f2011-10-11 06:43:29 +000010982 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Richard Smith8b86f2d2013-11-04 01:48:18 +000010983 ClassDecl->setImplicitMoveConstructorIsDeleted();
10984 SetDeclDeleted(MoveConstructor, ClassLoc);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010985 }
10986
10987 // Note that we have declared this constructor.
10988 ++ASTContext::NumImplicitMoveConstructorsDeclared;
10989
10990 if (Scope *S = getScopeForContext(ClassDecl))
10991 PushOnScopeChains(MoveConstructor, S, false);
10992 ClassDecl->addDecl(MoveConstructor);
10993
10994 return MoveConstructor;
10995}
10996
10997void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
10998 CXXConstructorDecl *MoveConstructor) {
10999 assert((MoveConstructor->isDefaulted() &&
11000 MoveConstructor->isMoveConstructor() &&
Richard Smith273c4e92012-02-26 07:51:39 +000011001 !MoveConstructor->doesThisDeclarationHaveABody() &&
11002 !MoveConstructor->isDeleted()) &&
Sebastian Redl22653ba2011-08-30 19:58:05 +000011003 "DefineImplicitMoveConstructor - call it for implicit move ctor");
11004
11005 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
11006 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
11007
Eli Friedmaneaf34142012-10-18 20:14:08 +000011008 SynthesizedFunctionScope Scope(*this, MoveConstructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011009 DiagnosticErrorTrap Trap(Diags);
11010
David Blaikie3fc2f912013-01-17 05:26:25 +000011011 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
Sebastian Redl22653ba2011-08-30 19:58:05 +000011012 Trap.hasErrorOccurred()) {
11013 Diag(CurrentLocation, diag::note_member_synthesized_at)
11014 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
11015 MoveConstructor->setInvalidDecl();
11016 } else {
Daniel Jasperb3b0b802014-06-20 08:44:22 +000011017 SourceLocation Loc = MoveConstructor->getLocEnd().isValid()
11018 ? MoveConstructor->getLocEnd()
11019 : MoveConstructor->getLocation();
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011020 Sema::CompoundScopeRAII CompoundScope(*this);
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +000011021 MoveConstructor->setBody(ActOnCompoundStmt(
Daniel Jasperb3b0b802014-06-20 08:44:22 +000011022 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000011023 }
11024
Ben Langmuir2f8e6b82014-09-25 20:55:00 +000011025 // The exception specification is needed because we are defining the
11026 // function.
11027 ResolveExceptionSpec(CurrentLocation,
11028 MoveConstructor->getType()->castAs<FunctionProtoType>());
11029
Eli Friedman276dd182013-09-05 00:02:25 +000011030 MoveConstructor->markUsed(Context);
Reid Kleckner3be586f2014-07-18 01:48:10 +000011031 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011032
11033 if (ASTMutationListener *L = getASTMutationListener()) {
11034 L->CompletedImplicitDefinition(MoveConstructor);
11035 }
11036}
11037
Douglas Gregor74f7d502012-02-15 19:33:52 +000011038bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
Eli Friedmanebea0f22013-07-18 23:29:14 +000011039 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
Douglas Gregor74f7d502012-02-15 19:33:52 +000011040}
Douglas Gregord3b672c2012-02-16 01:06:16 +000011041
11042void Sema::DefineImplicitLambdaToFunctionPointerConversion(
Faisal Vali571df122013-09-29 08:45:24 +000011043 SourceLocation CurrentLocation,
11044 CXXConversionDecl *Conv) {
11045 CXXRecordDecl *Lambda = Conv->getParent();
11046 CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
11047 // If we are defining a specialization of a conversion to function-ptr
11048 // cache the deduced template arguments for this specialization
11049 // so that we can use them to retrieve the corresponding call-operator
11050 // and static-invoker.
Craig Topperc3ec1492014-05-26 06:22:03 +000011051 const TemplateArgumentList *DeducedTemplateArgs = nullptr;
11052
Faisal Vali571df122013-09-29 08:45:24 +000011053 // Retrieve the corresponding call-operator specialization.
11054 if (Lambda->isGenericLambda()) {
11055 assert(Conv->isFunctionTemplateSpecialization());
11056 FunctionTemplateDecl *CallOpTemplate =
11057 CallOp->getDescribedFunctionTemplate();
11058 DeducedTemplateArgs = Conv->getTemplateSpecializationArgs();
Craig Topperc3ec1492014-05-26 06:22:03 +000011059 void *InsertPos = nullptr;
Faisal Vali571df122013-09-29 08:45:24 +000011060 FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization(
Craig Topper7e0daca2014-06-26 04:58:53 +000011061 DeducedTemplateArgs->asArray(),
Faisal Vali571df122013-09-29 08:45:24 +000011062 InsertPos);
11063 assert(CallOpSpec &&
11064 "Conversion operator must have a corresponding call operator");
11065 CallOp = cast<CXXMethodDecl>(CallOpSpec);
11066 }
11067 // Mark the call operator referenced (and add to pending instantiations
11068 // if necessary).
11069 // For both the conversion and static-invoker template specializations
11070 // we construct their body's in this function, so no need to add them
11071 // to the PendingInstantiations.
11072 MarkFunctionReferenced(CurrentLocation, CallOp);
11073
Eli Friedmaneaf34142012-10-18 20:14:08 +000011074 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregord3b672c2012-02-16 01:06:16 +000011075 DiagnosticErrorTrap Trap(Diags);
Faisal Vali571df122013-09-29 08:45:24 +000011076
Alp Tokerf6a24ce2013-12-05 16:25:25 +000011077 // Retrieve the static invoker...
Faisal Vali571df122013-09-29 08:45:24 +000011078 CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker();
11079 // ... and get the corresponding specialization for a generic lambda.
11080 if (Lambda->isGenericLambda()) {
11081 assert(DeducedTemplateArgs &&
11082 "Must have deduced template arguments from Conversion Operator");
11083 FunctionTemplateDecl *InvokeTemplate =
11084 Invoker->getDescribedFunctionTemplate();
Craig Topperc3ec1492014-05-26 06:22:03 +000011085 void *InsertPos = nullptr;
Faisal Vali571df122013-09-29 08:45:24 +000011086 FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization(
Craig Topper7e0daca2014-06-26 04:58:53 +000011087 DeducedTemplateArgs->asArray(),
Faisal Vali571df122013-09-29 08:45:24 +000011088 InsertPos);
11089 assert(InvokeSpec &&
11090 "Must have a corresponding static invoker specialization");
11091 Invoker = cast<CXXMethodDecl>(InvokeSpec);
11092 }
11093 // Construct the body of the conversion function { return __invoke; }.
11094 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011095 VK_LValue, Conv->getLocation()).get();
Faisal Vali571df122013-09-29 08:45:24 +000011096 assert(FunctionRef && "Can't refer to __invoke function?");
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011097 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
Faisal Vali571df122013-09-29 08:45:24 +000011098 Conv->setBody(new (Context) CompoundStmt(Context, Return,
11099 Conv->getLocation(),
11100 Conv->getLocation()));
11101
11102 Conv->markUsed(Context);
11103 Conv->setReferenced();
Douglas Gregord3b672c2012-02-16 01:06:16 +000011104
Faisal Vali571df122013-09-29 08:45:24 +000011105 // Fill in the __invoke function with a dummy implementation. IR generation
11106 // will fill in the actual details.
11107 Invoker->markUsed(Context);
11108 Invoker->setReferenced();
11109 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
11110
Douglas Gregord3b672c2012-02-16 01:06:16 +000011111 if (ASTMutationListener *L = getASTMutationListener()) {
11112 L->CompletedImplicitDefinition(Conv);
Faisal Vali571df122013-09-29 08:45:24 +000011113 L->CompletedImplicitDefinition(Invoker);
11114 }
Douglas Gregord3b672c2012-02-16 01:06:16 +000011115}
11116
Faisal Vali571df122013-09-29 08:45:24 +000011117
11118
Douglas Gregord3b672c2012-02-16 01:06:16 +000011119void Sema::DefineImplicitLambdaToBlockPointerConversion(
11120 SourceLocation CurrentLocation,
11121 CXXConversionDecl *Conv)
11122{
Faisal Vali850da1a2013-09-29 17:08:32 +000011123 assert(!Conv->getParent()->isGenericLambda());
Faisal Vali571df122013-09-29 08:45:24 +000011124
Eli Friedman276dd182013-09-05 00:02:25 +000011125 Conv->markUsed(Context);
Douglas Gregord3b672c2012-02-16 01:06:16 +000011126
Eli Friedmaneaf34142012-10-18 20:14:08 +000011127 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregord3b672c2012-02-16 01:06:16 +000011128 DiagnosticErrorTrap Trap(Diags);
11129
Douglas Gregored90df32012-02-22 05:02:47 +000011130 // Copy-initialize the lambda object as needed to capture it.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011131 Expr *This = ActOnCXXThis(CurrentLocation).get();
11132 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
Douglas Gregord3b672c2012-02-16 01:06:16 +000011133
Eli Friedman98b01ed2012-03-01 04:01:32 +000011134 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
11135 Conv->getLocation(),
11136 Conv, DerefThis);
11137
11138 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
11139 // behavior. Note that only the general conversion function does this
11140 // (since it's unusable otherwise); in the case where we inline the
11141 // block literal, it has block literal lifetime semantics.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011142 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman98b01ed2012-03-01 04:01:32 +000011143 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
11144 CK_CopyAndAutoreleaseBlockObject,
Craig Topperc3ec1492014-05-26 06:22:03 +000011145 BuildBlock.get(), nullptr, VK_RValue);
Eli Friedman98b01ed2012-03-01 04:01:32 +000011146
11147 if (BuildBlock.isInvalid()) {
Douglas Gregord3b672c2012-02-16 01:06:16 +000011148 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregored90df32012-02-22 05:02:47 +000011149 Conv->setInvalidDecl();
11150 return;
Douglas Gregord3b672c2012-02-16 01:06:16 +000011151 }
Douglas Gregored90df32012-02-22 05:02:47 +000011152
Douglas Gregored90df32012-02-22 05:02:47 +000011153 // Create the return statement that returns the block from the conversion
11154 // function.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +000011155 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregored90df32012-02-22 05:02:47 +000011156 if (Return.isInvalid()) {
11157 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
11158 Conv->setInvalidDecl();
11159 return;
11160 }
11161
11162 // Set the body of the conversion function.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011163 Stmt *ReturnS = Return.get();
Nico Webera2a0eb92012-12-29 20:03:39 +000011164 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
Douglas Gregored90df32012-02-22 05:02:47 +000011165 Conv->getLocation(),
Douglas Gregord3b672c2012-02-16 01:06:16 +000011166 Conv->getLocation()));
11167
Douglas Gregored90df32012-02-22 05:02:47 +000011168 // We're done; notify the mutation listener, if any.
Douglas Gregord3b672c2012-02-16 01:06:16 +000011169 if (ASTMutationListener *L = getASTMutationListener()) {
11170 L->CompletedImplicitDefinition(Conv);
11171 }
11172}
11173
Douglas Gregord2f70072012-03-10 06:53:13 +000011174/// \brief Determine whether the given list arguments contains exactly one
11175/// "real" (non-default) argument.
11176static bool hasOneRealArgument(MultiExprArg Args) {
11177 switch (Args.size()) {
11178 case 0:
11179 return false;
11180
11181 default:
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011182 if (!Args[1]->isDefaultArgument())
Douglas Gregord2f70072012-03-10 06:53:13 +000011183 return false;
11184
11185 // fall through
11186 case 1:
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011187 return !Args[0]->isDefaultArgument();
Douglas Gregord2f70072012-03-10 06:53:13 +000011188 }
11189
11190 return false;
11191}
11192
John McCalldadc5752010-08-24 06:29:42 +000011193ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +000011194Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +000011195 CXXConstructorDecl *Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +000011196 MultiExprArg ExprArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011197 bool HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000011198 bool IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +000011199 bool IsStdInitListInitialization,
Douglas Gregor7ae2d772010-01-31 09:12:51 +000011200 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +000011201 unsigned ConstructKind,
11202 SourceRange ParenRange) {
Anders Carlsson250aada2009-08-16 05:13:48 +000011203 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +000011204
Douglas Gregor45cf7e32010-04-02 18:24:57 +000011205 // C++0x [class.copy]p34:
11206 // When certain criteria are met, an implementation is allowed to
11207 // omit the copy/move construction of a class object, even if the
11208 // copy/move constructor and/or destructor for the object have
11209 // side effects. [...]
11210 // - when a temporary class object that has not been bound to a
11211 // reference (12.2) would be copied/moved to a class object
11212 // with the same cv-unqualified type, the copy/move operation
11213 // can be omitted by constructing the temporary object
11214 // directly into the target of the omitted copy/move
John McCall7a626f62010-09-15 10:14:12 +000011215 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregord2f70072012-03-10 06:53:13 +000011216 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000011217 Expr *SubExpr = ExprArgs[0];
John McCall7a626f62010-09-15 10:14:12 +000011218 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson250aada2009-08-16 05:13:48 +000011219 }
Mike Stump11289f42009-09-09 15:08:12 +000011220
11221 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011222 Elidable, ExprArgs, HadMultipleCandidates,
Richard Smithf8adcdc2014-07-17 05:12:35 +000011223 IsListInitialization,
11224 IsStdInitListInitialization, RequiresZeroInit,
Richard Smithd59b8322012-12-19 01:39:02 +000011225 ConstructKind, ParenRange);
Anders Carlsson250aada2009-08-16 05:13:48 +000011226}
11227
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +000011228/// BuildCXXConstructExpr - Creates a complete call to a constructor,
11229/// including handling of its default argument expressions.
John McCalldadc5752010-08-24 06:29:42 +000011230ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +000011231Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
11232 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor4f4b1862009-12-16 18:50:27 +000011233 MultiExprArg ExprArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011234 bool HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000011235 bool IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +000011236 bool IsStdInitListInitialization,
Douglas Gregor7ae2d772010-01-31 09:12:51 +000011237 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +000011238 unsigned ConstructKind,
11239 SourceRange ParenRange) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000011240 MarkFunctionReferenced(ConstructLoc, Constructor);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011241 return CXXConstructExpr::Create(
11242 Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
Richard Smithf8adcdc2014-07-17 05:12:35 +000011243 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
11244 RequiresZeroInit,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011245 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
11246 ParenRange);
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +000011247}
11248
Reid Klecknerd60b82f2014-11-17 23:36:45 +000011249ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
11250 assert(Field->hasInClassInitializer());
11251
11252 // If we already have the in-class initializer nothing needs to be done.
11253 if (Field->getInClassInitializer())
11254 return CXXDefaultInitExpr::Create(Context, Loc, Field);
11255
11256 // Maybe we haven't instantiated the in-class initializer. Go check the
11257 // pattern FieldDecl to see if it has one.
11258 CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
11259
11260 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
11261 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
11262 DeclContext::lookup_result Lookup =
11263 ClassPattern->lookup(Field->getDeclName());
11264 assert(Lookup.size() == 1);
11265 FieldDecl *Pattern = cast<FieldDecl>(Lookup[0]);
11266 if (InstantiateInClassInitializer(Loc, Field, Pattern,
11267 getTemplateInstantiationArgs(Field)))
11268 return ExprError();
11269 return CXXDefaultInitExpr::Create(Context, Loc, Field);
11270 }
11271
11272 // DR1351:
11273 // If the brace-or-equal-initializer of a non-static data member
11274 // invokes a defaulted default constructor of its class or of an
11275 // enclosing class in a potentially evaluated subexpression, the
11276 // program is ill-formed.
11277 //
11278 // This resolution is unworkable: the exception specification of the
11279 // default constructor can be needed in an unevaluated context, in
11280 // particular, in the operand of a noexcept-expression, and we can be
11281 // unable to compute an exception specification for an enclosed class.
11282 //
11283 // Any attempt to resolve the exception specification of a defaulted default
11284 // constructor before the initializer is lexically complete will ultimately
11285 // come here at which point we can diagnose it.
11286 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
11287 if (OutermostClass == ParentRD) {
11288 Diag(Field->getLocEnd(), diag::err_in_class_initializer_not_yet_parsed)
11289 << ParentRD << Field;
11290 } else {
11291 Diag(Field->getLocEnd(),
11292 diag::err_in_class_initializer_not_yet_parsed_outer_class)
11293 << ParentRD << OutermostClass << Field;
11294 }
11295
11296 return ExprError();
11297}
11298
John McCall03c48482010-02-02 09:10:11 +000011299void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth86d17d32011-03-27 21:26:48 +000011300 if (VD->isInvalidDecl()) return;
11301
John McCall03c48482010-02-02 09:10:11 +000011302 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth86d17d32011-03-27 21:26:48 +000011303 if (ClassDecl->isInvalidDecl()) return;
Richard Smitheec915d62012-02-18 04:13:32 +000011304 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth86d17d32011-03-27 21:26:48 +000011305 if (ClassDecl->isDependentContext()) return;
John McCall47e40932010-08-01 20:20:59 +000011306
Chandler Carruth86d17d32011-03-27 21:26:48 +000011307 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedmanfa0df832012-02-02 03:46:19 +000011308 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth86d17d32011-03-27 21:26:48 +000011309 CheckDestructorAccess(VD->getLocation(), Destructor,
11310 PDiag(diag::err_access_dtor_var)
11311 << VD->getDeclName()
11312 << VD->getType());
Richard Smitheec915d62012-02-18 04:13:32 +000011313 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson98766db2011-03-24 01:01:41 +000011314
Stephan Tolksdorf5604a272014-03-27 20:23:36 +000011315 if (Destructor->isTrivial()) return;
Chandler Carruth86d17d32011-03-27 21:26:48 +000011316 if (!VD->hasGlobalStorage()) return;
11317
11318 // Emit warning for non-trivial dtor in global scope (a real global,
11319 // class-static, function-static).
11320 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
11321
11322 // TODO: this should be re-enabled for static locals by !CXAAtExit
Stephan Tolksdorf5604a272014-03-27 20:23:36 +000011323 if (!VD->isStaticLocal())
Chandler Carruth86d17d32011-03-27 21:26:48 +000011324 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +000011325}
11326
Douglas Gregor5d3507d2009-09-09 23:08:42 +000011327/// \brief Given a constructor and the set of arguments provided for the
11328/// constructor, convert the arguments and add any required default arguments
11329/// to form a proper call to this constructor.
11330///
11331/// \returns true if an error occurred, false otherwise.
11332bool
11333Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
11334 MultiExprArg ArgsPtr,
Richard Smith55ce3522012-06-25 20:30:08 +000011335 SourceLocation Loc,
Benjamin Kramerf0623432012-08-23 22:51:59 +000011336 SmallVectorImpl<Expr*> &ConvertedArgs,
Richard Smith6b216962013-02-05 05:52:24 +000011337 bool AllowExplicit,
11338 bool IsListInitialization) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +000011339 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
11340 unsigned NumArgs = ArgsPtr.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000011341 Expr **Args = ArgsPtr.data();
Douglas Gregor5d3507d2009-09-09 23:08:42 +000011342
11343 const FunctionProtoType *Proto
11344 = Constructor->getType()->getAs<FunctionProtoType>();
11345 assert(Proto && "Constructor without a prototype?");
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000011346 unsigned NumParams = Proto->getNumParams();
Alp Toker9cacbab2014-01-20 20:26:09 +000011347
Douglas Gregor5d3507d2009-09-09 23:08:42 +000011348 // If too few arguments are available, we'll fill in the rest with defaults.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000011349 if (NumArgs < NumParams)
11350 ConvertedArgs.reserve(NumParams);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000011351 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +000011352 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000011353
11354 VariadicCallType CallType =
11355 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000011356 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000011357 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011358 Proto, 0,
11359 llvm::makeArrayRef(Args, NumArgs),
11360 AllArgs,
Richard Smith6b216962013-02-05 05:52:24 +000011361 CallType, AllowExplicit,
11362 IsListInitialization);
Benjamin Kramer8001f742012-02-14 12:06:21 +000011363 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmanff4b4072012-02-18 04:48:30 +000011364
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011365 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
Eli Friedmanff4b4072012-02-18 04:48:30 +000011366
Dmitri Gribenko765396f2013-01-13 20:46:02 +000011367 CheckConstructorCall(Constructor,
Craig Topper8c2a2a02014-08-30 16:55:39 +000011368 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
Richard Smith55ce3522012-06-25 20:30:08 +000011369 Proto, Loc);
Eli Friedmanff4b4072012-02-18 04:48:30 +000011370
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000011371 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +000011372}
11373
Anders Carlssone363c8e2009-12-12 00:32:00 +000011374static inline bool
11375CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
11376 const FunctionDecl *FnDecl) {
Sebastian Redl50c68252010-08-31 00:36:30 +000011377 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlssone363c8e2009-12-12 00:32:00 +000011378 if (isa<NamespaceDecl>(DC)) {
11379 return SemaRef.Diag(FnDecl->getLocation(),
11380 diag::err_operator_new_delete_declared_in_namespace)
11381 << FnDecl->getDeclName();
11382 }
11383
11384 if (isa<TranslationUnitDecl>(DC) &&
John McCall8e7d6562010-08-26 03:08:43 +000011385 FnDecl->getStorageClass() == SC_Static) {
Anders Carlssone363c8e2009-12-12 00:32:00 +000011386 return SemaRef.Diag(FnDecl->getLocation(),
11387 diag::err_operator_new_delete_declared_static)
11388 << FnDecl->getDeclName();
11389 }
11390
Anders Carlsson60659a82009-12-12 02:43:16 +000011391 return false;
Anders Carlssone363c8e2009-12-12 00:32:00 +000011392}
11393
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011394static inline bool
11395CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
11396 CanQualType ExpectedResultType,
11397 CanQualType ExpectedFirstParamType,
11398 unsigned DependentParamTypeDiag,
11399 unsigned InvalidParamTypeDiag) {
Alp Toker314cc812014-01-25 16:55:45 +000011400 QualType ResultType =
11401 FnDecl->getType()->getAs<FunctionType>()->getReturnType();
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011402
11403 // Check that the result type is not dependent.
11404 if (ResultType->isDependentType())
11405 return SemaRef.Diag(FnDecl->getLocation(),
11406 diag::err_operator_new_delete_dependent_result_type)
11407 << FnDecl->getDeclName() << ExpectedResultType;
11408
11409 // Check that the result type is what we expect.
11410 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
11411 return SemaRef.Diag(FnDecl->getLocation(),
11412 diag::err_operator_new_delete_invalid_result_type)
11413 << FnDecl->getDeclName() << ExpectedResultType;
11414
11415 // A function template must have at least 2 parameters.
11416 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
11417 return SemaRef.Diag(FnDecl->getLocation(),
11418 diag::err_operator_new_delete_template_too_few_parameters)
11419 << FnDecl->getDeclName();
11420
11421 // The function decl must have at least 1 parameter.
11422 if (FnDecl->getNumParams() == 0)
11423 return SemaRef.Diag(FnDecl->getLocation(),
11424 diag::err_operator_new_delete_too_few_parameters)
11425 << FnDecl->getDeclName();
11426
Sylvestre Ledru830885c2012-07-23 08:59:39 +000011427 // Check the first parameter type is not dependent.
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011428 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
11429 if (FirstParamType->isDependentType())
11430 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
11431 << FnDecl->getDeclName() << ExpectedFirstParamType;
11432
11433 // Check that the first parameter type is what we expect.
Douglas Gregor684d7bd2009-12-22 23:42:49 +000011434 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011435 ExpectedFirstParamType)
11436 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
11437 << FnDecl->getDeclName() << ExpectedFirstParamType;
11438
11439 return false;
11440}
11441
Anders Carlsson12308f42009-12-11 23:23:22 +000011442static bool
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011443CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlssone363c8e2009-12-12 00:32:00 +000011444 // C++ [basic.stc.dynamic.allocation]p1:
11445 // A program is ill-formed if an allocation function is declared in a
11446 // namespace scope other than global scope or declared static in global
11447 // scope.
11448 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
11449 return true;
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011450
11451 CanQualType SizeTy =
11452 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
11453
11454 // C++ [basic.stc.dynamic.allocation]p1:
11455 // The return type shall be void*. The first parameter shall have type
11456 // std::size_t.
11457 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
11458 SizeTy,
11459 diag::err_operator_new_dependent_param_type,
11460 diag::err_operator_new_param_type))
11461 return true;
11462
11463 // C++ [basic.stc.dynamic.allocation]p1:
11464 // The first parameter shall not have an associated default argument.
11465 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlsson22f443f2009-12-12 00:26:23 +000011466 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011467 diag::err_operator_new_default_arg)
11468 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
11469
11470 return false;
Anders Carlsson22f443f2009-12-12 00:26:23 +000011471}
11472
11473static bool
Richard Smith66f3ac92012-10-20 08:26:51 +000011474CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
Anders Carlsson12308f42009-12-11 23:23:22 +000011475 // C++ [basic.stc.dynamic.deallocation]p1:
11476 // A program is ill-formed if deallocation functions are declared in a
11477 // namespace scope other than global scope or declared static in global
11478 // scope.
Anders Carlssone363c8e2009-12-12 00:32:00 +000011479 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
11480 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +000011481
11482 // C++ [basic.stc.dynamic.deallocation]p2:
11483 // Each deallocation function shall return void and its first parameter
11484 // shall be void*.
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011485 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
11486 SemaRef.Context.VoidPtrTy,
11487 diag::err_operator_delete_dependent_param_type,
11488 diag::err_operator_delete_param_type))
11489 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +000011490
Anders Carlsson12308f42009-12-11 23:23:22 +000011491 return false;
11492}
11493
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011494/// CheckOverloadedOperatorDeclaration - Check whether the declaration
11495/// of this overloaded operator is well-formed. If so, returns false;
11496/// otherwise, emits appropriate diagnostics and returns true.
11497bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +000011498 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011499 "Expected an overloaded operator declaration");
11500
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011501 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
11502
Mike Stump11289f42009-09-09 15:08:12 +000011503 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011504 // The allocation and deallocation functions, operator new,
11505 // operator new[], operator delete and operator delete[], are
11506 // described completely in 3.7.3. The attributes and restrictions
11507 // found in the rest of this subclause do not apply to them unless
11508 // explicitly stated in 3.7.3.
Anders Carlssonf1f46952009-12-11 23:31:21 +000011509 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson12308f42009-12-11 23:23:22 +000011510 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanian4e088942009-11-10 23:47:18 +000011511
Anders Carlsson22f443f2009-12-12 00:26:23 +000011512 if (Op == OO_New || Op == OO_Array_New)
11513 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011514
11515 // C++ [over.oper]p6:
11516 // An operator function shall either be a non-static member
11517 // function or be a non-member function and have at least one
11518 // parameter whose type is a class, a reference to a class, an
11519 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +000011520 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
11521 if (MethodDecl->isStatic())
11522 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000011523 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011524 } else {
11525 bool ClassOrEnumParam = false;
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000011526 for (auto Param : FnDecl->params()) {
11527 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +000011528 if (ParamType->isDependentType() || ParamType->isRecordType() ||
11529 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011530 ClassOrEnumParam = true;
11531 break;
11532 }
11533 }
11534
Douglas Gregord69246b2008-11-17 16:14:12 +000011535 if (!ClassOrEnumParam)
11536 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +000011537 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000011538 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011539 }
11540
11541 // C++ [over.oper]p8:
11542 // An operator function cannot have default arguments (8.3.6),
11543 // except where explicitly stated below.
11544 //
Mike Stump11289f42009-09-09 15:08:12 +000011545 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011546 // (C++ [over.call]p1).
11547 if (Op != OO_Call) {
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000011548 for (auto Param : FnDecl->params()) {
11549 if (Param->hasDefaultArg())
11550 return Diag(Param->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +000011551 diag::err_operator_overload_default_arg)
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000011552 << FnDecl->getDeclName() << Param->getDefaultArgRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011553 }
11554 }
11555
Douglas Gregor6cf08062008-11-10 13:38:07 +000011556 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
11557 { false, false, false }
11558#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
11559 , { Unary, Binary, MemberOnly }
11560#include "clang/Basic/OperatorKinds.def"
11561 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011562
Douglas Gregor6cf08062008-11-10 13:38:07 +000011563 bool CanBeUnaryOperator = OperatorUses[Op][0];
11564 bool CanBeBinaryOperator = OperatorUses[Op][1];
11565 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011566
11567 // C++ [over.oper]p8:
11568 // [...] Operator functions cannot have more or fewer parameters
11569 // than the number required for the corresponding operator, as
11570 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +000011571 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +000011572 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011573 if (Op != OO_Call &&
11574 ((NumParams == 1 && !CanBeUnaryOperator) ||
11575 (NumParams == 2 && !CanBeBinaryOperator) ||
11576 (NumParams < 1) || (NumParams > 2))) {
11577 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000011578 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +000011579 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000011580 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +000011581 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000011582 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +000011583 } else {
Chris Lattner2b786902008-11-21 07:50:02 +000011584 assert(CanBeBinaryOperator &&
11585 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000011586 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +000011587 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011588
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000011589 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000011590 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011591 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +000011592
Douglas Gregord69246b2008-11-17 16:14:12 +000011593 // Overloaded operators other than operator() cannot be variadic.
11594 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +000011595 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +000011596 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000011597 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011598 }
11599
11600 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +000011601 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
11602 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +000011603 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000011604 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011605 }
11606
11607 // C++ [over.inc]p1:
11608 // The user-defined function called operator++ implements the
11609 // prefix and postfix ++ operator. If this function is a member
11610 // function with no parameters, or a non-member function with one
11611 // parameter of class or enumeration type, it defines the prefix
11612 // increment operator ++ for objects of that type. If the function
11613 // is a member function with one parameter (which shall be of type
11614 // int) or a non-member function with two parameters (the second
11615 // of which shall be of type int), it defines the postfix
11616 // increment operator ++ for objects of that type.
11617 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
11618 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
Richard Smith538b52a2014-01-30 22:24:05 +000011619 QualType ParamType = LastParam->getType();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011620
Richard Smith538b52a2014-01-30 22:24:05 +000011621 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
11622 !ParamType->isDependentType())
Chris Lattner2b786902008-11-21 07:50:02 +000011623 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +000011624 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +000011625 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011626 }
11627
Douglas Gregord69246b2008-11-17 16:14:12 +000011628 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011629}
Chris Lattner3b024a32008-12-17 07:09:26 +000011630
Alexis Huntc88db062010-01-13 09:01:02 +000011631/// CheckLiteralOperatorDeclaration - Check whether the declaration
11632/// of this literal operator function is well-formed. If so, returns
11633/// false; otherwise, emits appropriate diagnostics and returns true.
11634bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smith5731c752012-03-10 22:18:57 +000011635 if (isa<CXXMethodDecl>(FnDecl)) {
Alexis Huntc88db062010-01-13 09:01:02 +000011636 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
11637 << FnDecl->getDeclName();
11638 return true;
11639 }
11640
Richard Smith72eebee2012-03-04 09:41:16 +000011641 if (FnDecl->isExternC()) {
11642 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
11643 return true;
11644 }
11645
Alexis Huntc88db062010-01-13 09:01:02 +000011646 bool Valid = false;
11647
Richard Smithbcc22fc2012-03-09 08:00:36 +000011648 // This might be the definition of a literal operator template.
11649 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
11650 // This might be a specialization of a literal operator template.
11651 if (!TpDecl)
11652 TpDecl = FnDecl->getPrimaryTemplate();
11653
Richard Smithb8b41d32013-10-07 19:57:58 +000011654 // template <char...> type operator "" name() and
11655 // template <class T, T...> type operator "" name() are the only valid
11656 // template signatures, and the only valid signatures with no parameters.
Richard Smithbcc22fc2012-03-09 08:00:36 +000011657 if (TpDecl) {
Richard Smith72eebee2012-03-04 09:41:16 +000011658 if (FnDecl->param_size() == 0) {
Richard Smithb8b41d32013-10-07 19:57:58 +000011659 // Must have one or two template parameters
Alexis Hunt7dd26172010-04-07 23:11:06 +000011660 TemplateParameterList *Params = TpDecl->getTemplateParameters();
11661 if (Params->size() == 1) {
11662 NonTypeTemplateParmDecl *PmDecl =
Richard Smithed943022012-08-03 21:14:57 +000011663 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Alexis Huntc88db062010-01-13 09:01:02 +000011664
Alexis Hunt7dd26172010-04-07 23:11:06 +000011665 // The template parameter must be a char parameter pack.
Alexis Hunt7dd26172010-04-07 23:11:06 +000011666 if (PmDecl && PmDecl->isTemplateParameterPack() &&
11667 Context.hasSameType(PmDecl->getType(), Context.CharTy))
11668 Valid = true;
Richard Smithb8b41d32013-10-07 19:57:58 +000011669 } else if (Params->size() == 2) {
11670 TemplateTypeParmDecl *PmType =
11671 dyn_cast<TemplateTypeParmDecl>(Params->getParam(0));
11672 NonTypeTemplateParmDecl *PmArgs =
11673 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
11674
11675 // The second template parameter must be a parameter pack with the
11676 // first template parameter as its type.
11677 if (PmType && PmArgs &&
11678 !PmType->isTemplateParameterPack() &&
11679 PmArgs->isTemplateParameterPack()) {
11680 const TemplateTypeParmType *TArgs =
11681 PmArgs->getType()->getAs<TemplateTypeParmType>();
11682 if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
11683 TArgs->getIndex() == PmType->getIndex()) {
11684 Valid = true;
11685 if (ActiveTemplateInstantiations.empty())
11686 Diag(FnDecl->getLocation(),
11687 diag::ext_string_literal_operator_template);
11688 }
11689 }
Alexis Hunt7dd26172010-04-07 23:11:06 +000011690 }
11691 }
Richard Smith72eebee2012-03-04 09:41:16 +000011692 } else if (FnDecl->param_size()) {
Alexis Huntc88db062010-01-13 09:01:02 +000011693 // Check the first parameter
Alexis Hunt7dd26172010-04-07 23:11:06 +000011694 FunctionDecl::param_iterator Param = FnDecl->param_begin();
11695
Richard Smith72eebee2012-03-04 09:41:16 +000011696 QualType T = (*Param)->getType().getUnqualifiedType();
Alexis Huntc88db062010-01-13 09:01:02 +000011697
Alexis Hunt079a6f72010-04-07 22:57:35 +000011698 // unsigned long long int, long double, and any character type are allowed
11699 // as the only parameters.
Alexis Huntc88db062010-01-13 09:01:02 +000011700 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
11701 Context.hasSameType(T, Context.LongDoubleTy) ||
11702 Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg0d81e012013-05-10 10:08:40 +000011703 Context.hasSameType(T, Context.WideCharTy) ||
Alexis Huntc88db062010-01-13 09:01:02 +000011704 Context.hasSameType(T, Context.Char16Ty) ||
11705 Context.hasSameType(T, Context.Char32Ty)) {
11706 if (++Param == FnDecl->param_end())
11707 Valid = true;
11708 goto FinishedParams;
11709 }
11710
Alexis Hunt079a6f72010-04-07 22:57:35 +000011711 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Alexis Huntc88db062010-01-13 09:01:02 +000011712 const PointerType *PT = T->getAs<PointerType>();
11713 if (!PT)
11714 goto FinishedParams;
11715 T = PT->getPointeeType();
Richard Smith72eebee2012-03-04 09:41:16 +000011716 if (!T.isConstQualified() || T.isVolatileQualified())
Alexis Huntc88db062010-01-13 09:01:02 +000011717 goto FinishedParams;
11718 T = T.getUnqualifiedType();
11719
11720 // Move on to the second parameter;
11721 ++Param;
11722
11723 // If there is no second parameter, the first must be a const char *
11724 if (Param == FnDecl->param_end()) {
11725 if (Context.hasSameType(T, Context.CharTy))
11726 Valid = true;
11727 goto FinishedParams;
11728 }
11729
11730 // const char *, const wchar_t*, const char16_t*, and const char32_t*
11731 // are allowed as the first parameter to a two-parameter function
11732 if (!(Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg0d81e012013-05-10 10:08:40 +000011733 Context.hasSameType(T, Context.WideCharTy) ||
Alexis Huntc88db062010-01-13 09:01:02 +000011734 Context.hasSameType(T, Context.Char16Ty) ||
11735 Context.hasSameType(T, Context.Char32Ty)))
11736 goto FinishedParams;
11737
11738 // The second and final parameter must be an std::size_t
11739 T = (*Param)->getType().getUnqualifiedType();
11740 if (Context.hasSameType(T, Context.getSizeType()) &&
11741 ++Param == FnDecl->param_end())
11742 Valid = true;
11743 }
11744
11745 // FIXME: This diagnostic is absolutely terrible.
11746FinishedParams:
11747 if (!Valid) {
11748 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
11749 << FnDecl->getDeclName();
11750 return true;
11751 }
11752
Richard Smith768cecc2012-03-09 08:16:22 +000011753 // A parameter-declaration-clause containing a default argument is not
11754 // equivalent to any of the permitted forms.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000011755 for (auto Param : FnDecl->params()) {
11756 if (Param->hasDefaultArg()) {
11757 Diag(Param->getDefaultArgRange().getBegin(),
Richard Smith768cecc2012-03-09 08:16:22 +000011758 diag::err_literal_operator_default_argument)
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000011759 << Param->getDefaultArgRange();
Richard Smith768cecc2012-03-09 08:16:22 +000011760 break;
11761 }
11762 }
11763
Richard Smith0df56f42012-03-08 02:39:21 +000011764 StringRef LiteralName
Douglas Gregor86325ad2011-08-30 22:40:35 +000011765 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
11766 if (LiteralName[0] != '_') {
Richard Smith0df56f42012-03-08 02:39:21 +000011767 // C++11 [usrlit.suffix]p1:
11768 // Literal suffix identifiers that do not start with an underscore
11769 // are reserved for future standardization.
Richard Smithf4198b72013-07-23 08:14:48 +000011770 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
11771 << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
Douglas Gregor86325ad2011-08-30 22:40:35 +000011772 }
Richard Smith0df56f42012-03-08 02:39:21 +000011773
Alexis Huntc88db062010-01-13 09:01:02 +000011774 return false;
11775}
11776
Douglas Gregor07665a62009-01-05 19:45:36 +000011777/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
11778/// linkage specification, including the language and (if present)
Richard Smith4ee696d2014-02-17 23:25:27 +000011779/// the '{'. ExternLoc is the location of the 'extern', Lang is the
11780/// language string literal. LBraceLoc, if valid, provides the location of
Douglas Gregor07665a62009-01-05 19:45:36 +000011781/// the '{' brace. Otherwise, this linkage specification does not
11782/// have any braces.
Chris Lattner8ea64422010-11-09 20:15:55 +000011783Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
Richard Smith4ee696d2014-02-17 23:25:27 +000011784 Expr *LangStr,
Chris Lattner8ea64422010-11-09 20:15:55 +000011785 SourceLocation LBraceLoc) {
Richard Smith4ee696d2014-02-17 23:25:27 +000011786 StringLiteral *Lit = cast<StringLiteral>(LangStr);
11787 if (!Lit->isAscii()) {
11788 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
11789 << LangStr->getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +000011790 return nullptr;
Richard Smith4ee696d2014-02-17 23:25:27 +000011791 }
11792
11793 StringRef Lang = Lit->getString();
Chris Lattner438e5012008-12-17 07:13:27 +000011794 LinkageSpecDecl::LanguageIDs Language;
Richard Smith4ee696d2014-02-17 23:25:27 +000011795 if (Lang == "C")
Chris Lattner438e5012008-12-17 07:13:27 +000011796 Language = LinkageSpecDecl::lang_c;
Richard Smith4ee696d2014-02-17 23:25:27 +000011797 else if (Lang == "C++")
Chris Lattner438e5012008-12-17 07:13:27 +000011798 Language = LinkageSpecDecl::lang_cxx;
11799 else {
Richard Smith4ee696d2014-02-17 23:25:27 +000011800 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
11801 << LangStr->getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +000011802 return nullptr;
Chris Lattner438e5012008-12-17 07:13:27 +000011803 }
Mike Stump11289f42009-09-09 15:08:12 +000011804
Chris Lattner438e5012008-12-17 07:13:27 +000011805 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +000011806
Richard Smith4ee696d2014-02-17 23:25:27 +000011807 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
11808 LangStr->getExprLoc(), Language,
Rafael Espindola327be3c2013-04-26 01:30:23 +000011809 LBraceLoc.isValid());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011810 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +000011811 PushDeclContext(S, D);
John McCall48871652010-08-21 09:40:31 +000011812 return D;
Chris Lattner438e5012008-12-17 07:13:27 +000011813}
11814
Abramo Bagnaraed5b6892010-07-30 16:47:02 +000011815/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor07665a62009-01-05 19:45:36 +000011816/// the C++ linkage specification LinkageSpec. If RBraceLoc is
11817/// valid, it's the position of the closing '}' brace in a linkage
11818/// specification that uses braces.
John McCall48871652010-08-21 09:40:31 +000011819Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara4a8cda82011-03-03 14:52:38 +000011820 Decl *LinkageSpec,
11821 SourceLocation RBraceLoc) {
Richard Smith4ee696d2014-02-17 23:25:27 +000011822 if (RBraceLoc.isValid()) {
11823 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
11824 LSDecl->setRBraceLoc(RBraceLoc);
Abramo Bagnara4a8cda82011-03-03 14:52:38 +000011825 }
Richard Smith4ee696d2014-02-17 23:25:27 +000011826 PopDeclContext();
Douglas Gregor07665a62009-01-05 19:45:36 +000011827 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +000011828}
11829
Michael Han84324352013-02-22 17:15:32 +000011830Decl *Sema::ActOnEmptyDeclaration(Scope *S,
11831 AttributeList *AttrList,
11832 SourceLocation SemiLoc) {
11833 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
11834 // Attribute declarations appertain to empty declaration so we handle
11835 // them here.
11836 if (AttrList)
11837 ProcessDeclAttributeList(S, ED, AttrList);
Richard Smith54ecd982013-02-20 19:22:51 +000011838
Michael Han84324352013-02-22 17:15:32 +000011839 CurContext->addDecl(ED);
11840 return ED;
Richard Smith54ecd982013-02-20 19:22:51 +000011841}
11842
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011843/// \brief Perform semantic analysis for the variable declaration that
11844/// occurs within a C++ catch clause, returning the newly-created
11845/// variable.
Abramo Bagnaradff19302011-03-08 08:55:46 +000011846VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCallbcd03502009-12-07 02:54:59 +000011847 TypeSourceInfo *TInfo,
Abramo Bagnaradff19302011-03-08 08:55:46 +000011848 SourceLocation StartLoc,
11849 SourceLocation Loc,
11850 IdentifierInfo *Name) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011851 bool Invalid = false;
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000011852 QualType ExDeclType = TInfo->getType();
11853
Sebastian Redl54c04d42008-12-22 19:15:10 +000011854 // Arrays and functions decay.
11855 if (ExDeclType->isArrayType())
11856 ExDeclType = Context.getArrayDecayedType(ExDeclType);
11857 else if (ExDeclType->isFunctionType())
11858 ExDeclType = Context.getPointerType(ExDeclType);
11859
11860 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
11861 // The exception-declaration shall not denote a pointer or reference to an
11862 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +000011863 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +000011864 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000011865 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlb28b4072009-03-22 23:49:27 +000011866 Invalid = true;
11867 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011868
Sebastian Redl54c04d42008-12-22 19:15:10 +000011869 QualType BaseType = ExDeclType;
11870 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +000011871 unsigned DK = diag::err_catch_incomplete;
Ted Kremenekc23c7e62009-07-29 21:53:49 +000011872 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000011873 BaseType = Ptr->getPointeeType();
11874 Mode = 1;
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000011875 DK = diag::err_catch_incomplete_ptr;
Mike Stump11289f42009-09-09 15:08:12 +000011876 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +000011877 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +000011878 BaseType = Ref->getPointeeType();
11879 Mode = 2;
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000011880 DK = diag::err_catch_incomplete_ref;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011881 }
Sebastian Redlb28b4072009-03-22 23:49:27 +000011882 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000011883 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl54c04d42008-12-22 19:15:10 +000011884 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011885
Mike Stump11289f42009-09-09 15:08:12 +000011886 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011887 RequireNonAbstractType(Loc, ExDeclType,
11888 diag::err_abstract_type_in_decl,
11889 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +000011890 Invalid = true;
11891
John McCall2ca705e2010-07-24 00:37:23 +000011892 // Only the non-fragile NeXT runtime currently supports C++ catches
11893 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011894 if (!Invalid && getLangOpts().ObjC1) {
John McCall2ca705e2010-07-24 00:37:23 +000011895 QualType T = ExDeclType;
11896 if (const ReferenceType *RT = T->getAs<ReferenceType>())
11897 T = RT->getPointeeType();
11898
11899 if (T->isObjCObjectType()) {
11900 Diag(Loc, diag::err_objc_object_catch);
11901 Invalid = true;
11902 } else if (T->isObjCObjectPointerType()) {
John McCall5fb5df92012-06-20 06:18:46 +000011903 // FIXME: should this be a test for macosx-fragile specifically?
11904 if (getLangOpts().ObjCRuntime.isFragile())
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +000011905 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall2ca705e2010-07-24 00:37:23 +000011906 }
11907 }
11908
Abramo Bagnaradff19302011-03-08 08:55:46 +000011909 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
Rafael Espindola6ae7e502013-04-03 19:27:57 +000011910 ExDeclType, TInfo, SC_None);
Douglas Gregor3f324d562010-05-03 18:51:14 +000011911 ExDecl->setExceptionVariable(true);
11912
Douglas Gregor8ca0c642011-12-10 01:22:52 +000011913 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011914 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor8ca0c642011-12-10 01:22:52 +000011915 Invalid = true;
11916
Douglas Gregor750734c2011-07-06 18:14:43 +000011917 if (!Invalid && !ExDeclType->isDependentType()) {
John McCall1bf58462011-02-16 08:02:54 +000011918 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
John McCalleaef89b2013-03-22 02:10:40 +000011919 // Insulate this from anything else we might currently be parsing.
11920 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
11921
Douglas Gregor6de584c2010-03-05 23:38:39 +000011922 // C++ [except.handle]p16:
Nick Lewycky0f292892013-09-22 10:06:57 +000011923 // The object declared in an exception-declaration or, if the
11924 // exception-declaration does not specify a name, a temporary (12.2) is
Douglas Gregor6de584c2010-03-05 23:38:39 +000011925 // copy-initialized (8.5) from the exception object. [...]
11926 // The object is destroyed when the handler exits, after the destruction
11927 // of any automatic objects initialized within the handler.
11928 //
Nick Lewycky0f292892013-09-22 10:06:57 +000011929 // We just pretend to initialize the object with itself, then make sure
Douglas Gregor6de584c2010-03-05 23:38:39 +000011930 // it can be destroyed later.
John McCall1bf58462011-02-16 08:02:54 +000011931 QualType initType = ExDeclType;
11932
11933 InitializedEntity entity =
11934 InitializedEntity::InitializeVariable(ExDecl);
11935 InitializationKind initKind =
11936 InitializationKind::CreateCopy(Loc, SourceLocation());
11937
11938 Expr *opaqueValue =
11939 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +000011940 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
11941 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
John McCall1bf58462011-02-16 08:02:54 +000011942 if (result.isInvalid())
Douglas Gregor6de584c2010-03-05 23:38:39 +000011943 Invalid = true;
John McCall1bf58462011-02-16 08:02:54 +000011944 else {
11945 // If the constructor used was non-trivial, set this as the
11946 // "initializer".
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011947 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
John McCall1bf58462011-02-16 08:02:54 +000011948 if (!construct->getConstructor()->isTrivial()) {
11949 Expr *init = MaybeCreateExprWithCleanups(construct);
11950 ExDecl->setInit(init);
11951 }
11952
11953 // And make sure it's destructable.
11954 FinalizeVarWithDestructor(ExDecl, recordType);
11955 }
Douglas Gregor6de584c2010-03-05 23:38:39 +000011956 }
11957 }
11958
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011959 if (Invalid)
11960 ExDecl->setInvalidDecl();
11961
11962 return ExDecl;
11963}
11964
11965/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
11966/// handler.
John McCall48871652010-08-21 09:40:31 +000011967Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCall8cb7bdf2010-06-04 23:28:52 +000011968 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregor72772f62010-12-16 17:48:04 +000011969 bool Invalid = D.isInvalidType();
11970
11971 // Check for unexpanded parameter packs.
Jordan Rosed03d99d2013-03-05 01:27:54 +000011972 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
11973 UPPC_ExceptionType)) {
Douglas Gregor72772f62010-12-16 17:48:04 +000011974 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
11975 D.getIdentifierLoc());
11976 Invalid = true;
11977 }
11978
Sebastian Redl54c04d42008-12-22 19:15:10 +000011979 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +000011980 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +000011981 LookupOrdinaryName,
11982 ForRedeclaration)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000011983 // The scope should be freshly made just for us. There is just no way
Aaron Ballman9ef622e2014-06-02 13:10:07 +000011984 // it contains any previous declaration, except for function parameters in
11985 // a function-try-block's catch statement.
John McCall48871652010-08-21 09:40:31 +000011986 assert(!S->isDeclScope(PrevDecl));
Aaron Ballman9ef622e2014-06-02 13:10:07 +000011987 if (isDeclInScope(PrevDecl, CurContext, S)) {
11988 Diag(D.getIdentifierLoc(), diag::err_redefinition)
11989 << D.getIdentifier();
11990 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
11991 Invalid = true;
11992 } else if (PrevDecl->isTemplateParameter())
Sebastian Redl54c04d42008-12-22 19:15:10 +000011993 // Maybe we will complain about the shadowed template parameter.
11994 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +000011995 }
11996
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011997 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000011998 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
11999 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000012000 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +000012001 }
12002
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000012003 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012004 D.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +000012005 D.getIdentifierLoc(),
12006 D.getIdentifier());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000012007 if (Invalid)
12008 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +000012009
Sebastian Redl54c04d42008-12-22 19:15:10 +000012010 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +000012011 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000012012 PushOnScopeChains(ExDecl, S);
12013 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000012014 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +000012015
Douglas Gregor758a8692009-06-17 21:51:59 +000012016 ProcessDeclAttributes(S, ExDecl, D);
John McCall48871652010-08-21 09:40:31 +000012017 return ExDecl;
Sebastian Redl54c04d42008-12-22 19:15:10 +000012018}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000012019
Abramo Bagnaraea947882011-03-08 16:41:52 +000012020Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCallb268a282010-08-23 23:25:46 +000012021 Expr *AssertExpr,
Richard Smithded9c2e2012-07-11 22:37:56 +000012022 Expr *AssertMessageExpr,
Abramo Bagnaraea947882011-03-08 16:41:52 +000012023 SourceLocation RParenLoc) {
Richard Smith085a64f2014-06-20 19:57:12 +000012024 StringLiteral *AssertMessage =
12025 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000012026
Richard Smithded9c2e2012-07-11 22:37:56 +000012027 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
Craig Topperc3ec1492014-05-26 06:22:03 +000012028 return nullptr;
Richard Smithded9c2e2012-07-11 22:37:56 +000012029
12030 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
12031 AssertMessage, RParenLoc, false);
12032}
12033
12034Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
12035 Expr *AssertExpr,
12036 StringLiteral *AssertMessage,
12037 SourceLocation RParenLoc,
12038 bool Failed) {
Richard Smith085a64f2014-06-20 19:57:12 +000012039 assert(AssertExpr != nullptr && "Expected non-null condition");
Richard Smithded9c2e2012-07-11 22:37:56 +000012040 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
12041 !Failed) {
Richard Smithf4c51d92012-02-04 09:53:13 +000012042 // In a static_assert-declaration, the constant-expression shall be a
12043 // constant expression that can be contextually converted to bool.
12044 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
12045 if (Converted.isInvalid())
Richard Smithded9c2e2012-07-11 22:37:56 +000012046 Failed = true;
Richard Smithf4c51d92012-02-04 09:53:13 +000012047
Richard Smith902ca212011-12-14 23:32:26 +000012048 llvm::APSInt Cond;
Richard Smithded9c2e2012-07-11 22:37:56 +000012049 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregore2b37442012-05-04 22:38:52 +000012050 diag::err_static_assert_expression_is_not_constant,
Richard Smithf4c51d92012-02-04 09:53:13 +000012051 /*AllowFold=*/false).isInvalid())
Richard Smithded9c2e2012-07-11 22:37:56 +000012052 Failed = true;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000012053
Richard Smithded9c2e2012-07-11 22:37:56 +000012054 if (!Failed && !Cond) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +000012055 SmallString<256> MsgBuffer;
Richard Smithf506eaf2012-03-05 23:20:05 +000012056 llvm::raw_svector_ostream Msg(MsgBuffer);
Richard Smith085a64f2014-06-20 19:57:12 +000012057 if (AssertMessage)
12058 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
Abramo Bagnaraea947882011-03-08 16:41:52 +000012059 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smith085a64f2014-06-20 19:57:12 +000012060 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
Richard Smithded9c2e2012-07-11 22:37:56 +000012061 Failed = true;
Richard Smithf506eaf2012-03-05 23:20:05 +000012062 }
Anders Carlsson54b26982009-03-14 00:33:21 +000012063 }
Mike Stump11289f42009-09-09 15:08:12 +000012064
Abramo Bagnaraea947882011-03-08 16:41:52 +000012065 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
Richard Smithded9c2e2012-07-11 22:37:56 +000012066 AssertExpr, AssertMessage, RParenLoc,
12067 Failed);
Mike Stump11289f42009-09-09 15:08:12 +000012068
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000012069 CurContext->addDecl(Decl);
John McCall48871652010-08-21 09:40:31 +000012070 return Decl;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000012071}
Sebastian Redlf769df52009-03-24 22:27:57 +000012072
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012073/// \brief Perform semantic analysis of the given friend type declaration.
12074///
12075/// \returns A friend declaration that.
Richard Smitha31a89a2012-09-20 01:31:00 +000012076FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
Abramo Bagnara254b6302011-10-29 20:52:52 +000012077 SourceLocation FriendLoc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012078 TypeSourceInfo *TSInfo) {
12079 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
12080
12081 QualType T = TSInfo->getType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +000012082 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012083
Richard Smithc8239732011-10-18 21:39:00 +000012084 // C++03 [class.friend]p2:
12085 // An elaborated-type-specifier shall be used in a friend declaration
12086 // for a class.*
12087 //
12088 // * The class-key of the elaborated-type-specifier is required.
12089 if (!ActiveTemplateInstantiations.empty()) {
12090 // Do not complain about the form of friend template types during
12091 // template instantiation; we will already have complained when the
12092 // template was declared.
Nick Lewycky36722d22013-02-06 05:59:33 +000012093 } else {
12094 if (!T->isElaboratedTypeSpecifier()) {
12095 // If we evaluated the type to a record type, suggest putting
12096 // a tag in front.
12097 if (const RecordType *RT = T->getAs<RecordType>()) {
12098 RecordDecl *RD = RT->getDecl();
Alp Tokera030cd02014-05-05 12:38:48 +000012099
12100 SmallString<16> InsertionText(" ");
12101 InsertionText += RD->getKindName();
12102
Nick Lewycky36722d22013-02-06 05:59:33 +000012103 Diag(TypeRange.getBegin(),
12104 getLangOpts().CPlusPlus11 ?
12105 diag::warn_cxx98_compat_unelaborated_friend_type :
12106 diag::ext_unelaborated_friend_type)
12107 << (unsigned) RD->getTagKind()
12108 << T
12109 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
12110 InsertionText);
12111 } else {
12112 Diag(FriendLoc,
12113 getLangOpts().CPlusPlus11 ?
12114 diag::warn_cxx98_compat_nonclass_type_friend :
12115 diag::ext_nonclass_type_friend)
12116 << T
12117 << TypeRange;
12118 }
12119 } else if (T->getAs<EnumType>()) {
Richard Smithc8239732011-10-18 21:39:00 +000012120 Diag(FriendLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +000012121 getLangOpts().CPlusPlus11 ?
Nick Lewycky36722d22013-02-06 05:59:33 +000012122 diag::warn_cxx98_compat_enum_friend :
12123 diag::ext_enum_friend)
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012124 << T
Richard Smitha31a89a2012-09-20 01:31:00 +000012125 << TypeRange;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012126 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012127
Nick Lewycky36722d22013-02-06 05:59:33 +000012128 // C++11 [class.friend]p3:
12129 // A friend declaration that does not declare a function shall have one
12130 // of the following forms:
12131 // friend elaborated-type-specifier ;
12132 // friend simple-type-specifier ;
12133 // friend typename-specifier ;
12134 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
12135 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
12136 }
Richard Smitha31a89a2012-09-20 01:31:00 +000012137
Douglas Gregor3b4abb62010-04-07 17:57:12 +000012138 // If the type specifier in a friend declaration designates a (possibly
Richard Smitha31a89a2012-09-20 01:31:00 +000012139 // cv-qualified) class type, that class is declared as a friend; otherwise,
Douglas Gregor3b4abb62010-04-07 17:57:12 +000012140 // the friend declaration is ignored.
Nikola Smiljanic3a01af02014-05-23 12:48:27 +000012141 return FriendDecl::Create(Context, CurContext,
12142 TSInfo->getTypeLoc().getLocStart(), TSInfo,
12143 FriendLoc);
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012144}
12145
John McCallace48cd2010-10-19 01:40:49 +000012146/// Handle a friend tag declaration where the scope specifier was
12147/// templated.
12148Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
12149 unsigned TagSpec, SourceLocation TagLoc,
12150 CXXScopeSpec &SS,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000012151 IdentifierInfo *Name,
12152 SourceLocation NameLoc,
John McCallace48cd2010-10-19 01:40:49 +000012153 AttributeList *Attr,
12154 MultiTemplateParamsArg TempParamLists) {
12155 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
12156
12157 bool isExplicitSpecialization = false;
John McCallace48cd2010-10-19 01:40:49 +000012158 bool Invalid = false;
12159
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +000012160 if (TemplateParameterList *TemplateParams =
12161 MatchTemplateParametersToScopeSpecifier(
Craig Topperc3ec1492014-05-26 06:22:03 +000012162 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +000012163 isExplicitSpecialization, Invalid)) {
John McCallace48cd2010-10-19 01:40:49 +000012164 if (TemplateParams->size() > 0) {
12165 // This is a declaration of a class template.
12166 if (Invalid)
Craig Topperc3ec1492014-05-26 06:22:03 +000012167 return nullptr;
Abramo Bagnara0adf29a2011-03-10 13:28:31 +000012168
Nikola Smiljanic4fc91532014-07-17 01:59:34 +000012169 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
12170 NameLoc, Attr, TemplateParams, AS_public,
Douglas Gregor2820e692011-09-09 19:05:14 +000012171 /*ModulePrivateLoc=*/SourceLocation(),
Nikola Smiljanic4fc91532014-07-17 01:59:34 +000012172 FriendLoc, TempParamLists.size() - 1,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012173 TempParamLists.data()).get();
John McCallace48cd2010-10-19 01:40:49 +000012174 } else {
12175 // The "template<>" header is extraneous.
12176 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
12177 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
12178 isExplicitSpecialization = true;
12179 }
12180 }
12181
Craig Topperc3ec1492014-05-26 06:22:03 +000012182 if (Invalid) return nullptr;
John McCallace48cd2010-10-19 01:40:49 +000012183
John McCallace48cd2010-10-19 01:40:49 +000012184 bool isAllExplicitSpecializations = true;
Abramo Bagnara60804e12011-03-18 15:16:37 +000012185 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +000012186 if (TempParamLists[I]->size()) {
John McCallace48cd2010-10-19 01:40:49 +000012187 isAllExplicitSpecializations = false;
12188 break;
12189 }
12190 }
12191
12192 // FIXME: don't ignore attributes.
12193
12194 // If it's explicit specializations all the way down, just forget
12195 // about the template header and build an appropriate non-templated
12196 // friend. TODO: for source fidelity, remember the headers.
12197 if (isAllExplicitSpecializations) {
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000012198 if (SS.isEmpty()) {
12199 bool Owned = false;
12200 bool IsDependent = false;
12201 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
Richard Smith649c7b062014-01-08 00:56:48 +000012202 Attr, AS_public,
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000012203 /*ModulePrivateLoc=*/SourceLocation(),
Richard Smith649c7b062014-01-08 00:56:48 +000012204 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smith0f8ee222012-01-10 01:33:14 +000012205 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000012206 /*ScopedEnumUsesClassTag=*/false,
Richard Smith649c7b062014-01-08 00:56:48 +000012207 /*UnderlyingType=*/TypeResult(),
12208 /*IsTypeSpecifier=*/false);
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000012209 }
Richard Smith649c7b062014-01-08 00:56:48 +000012210
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000012211 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallace48cd2010-10-19 01:40:49 +000012212 ElaboratedTypeKeyword Keyword
12213 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000012214 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +000012215 *Name, NameLoc);
John McCallace48cd2010-10-19 01:40:49 +000012216 if (T.isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +000012217 return nullptr;
John McCallace48cd2010-10-19 01:40:49 +000012218
12219 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
12220 if (isa<DependentNameType>(T)) {
David Blaikie6adc78e2013-02-18 22:06:02 +000012221 DependentNameTypeLoc TL =
12222 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000012223 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000012224 TL.setQualifierLoc(QualifierLoc);
John McCallace48cd2010-10-19 01:40:49 +000012225 TL.setNameLoc(NameLoc);
12226 } else {
David Blaikie6adc78e2013-02-18 22:06:02 +000012227 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000012228 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +000012229 TL.setQualifierLoc(QualifierLoc);
David Blaikie6adc78e2013-02-18 22:06:02 +000012230 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
John McCallace48cd2010-10-19 01:40:49 +000012231 }
12232
12233 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000012234 TSI, FriendLoc, TempParamLists);
John McCallace48cd2010-10-19 01:40:49 +000012235 Friend->setAccess(AS_public);
12236 CurContext->addDecl(Friend);
12237 return Friend;
12238 }
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000012239
12240 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
12241
12242
John McCallace48cd2010-10-19 01:40:49 +000012243
12244 // Handle the case of a templated-scope friend class. e.g.
12245 // template <class T> class A<T>::B;
12246 // FIXME: we don't support these right now.
Richard Smithcd556eb2013-11-08 18:59:56 +000012247 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
12248 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
John McCallace48cd2010-10-19 01:40:49 +000012249 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
12250 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
12251 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
David Blaikie6adc78e2013-02-18 22:06:02 +000012252 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000012253 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000012254 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCallace48cd2010-10-19 01:40:49 +000012255 TL.setNameLoc(NameLoc);
12256
12257 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000012258 TSI, FriendLoc, TempParamLists);
John McCallace48cd2010-10-19 01:40:49 +000012259 Friend->setAccess(AS_public);
12260 Friend->setUnsupportedFriend(true);
12261 CurContext->addDecl(Friend);
12262 return Friend;
12263}
12264
12265
John McCall11083da2009-09-16 22:47:08 +000012266/// Handle a friend type declaration. This works in tandem with
12267/// ActOnTag.
12268///
12269/// Notes on friend class templates:
12270///
12271/// We generally treat friend class declarations as if they were
12272/// declaring a class. So, for example, the elaborated type specifier
12273/// in a friend declaration is required to obey the restrictions of a
12274/// class-head (i.e. no typedefs in the scope chain), template
12275/// parameters are required to match up with simple template-ids, &c.
12276/// However, unlike when declaring a template specialization, it's
12277/// okay to refer to a template specialization without an empty
12278/// template parameter declaration, e.g.
12279/// friend class A<T>::B<unsigned>;
12280/// We permit this as a special case; if there are any template
12281/// parameters present at all, require proper matching, i.e.
James Dennettf14a6e52012-06-15 22:23:43 +000012282/// template <> template \<class T> friend class A<int>::B;
John McCall48871652010-08-21 09:40:31 +000012283Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallc9739e32010-10-16 07:23:36 +000012284 MultiTemplateParamsArg TempParams) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012285 SourceLocation Loc = DS.getLocStart();
John McCall07e91c02009-08-06 02:15:43 +000012286
12287 assert(DS.isFriendSpecified());
12288 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
12289
John McCall11083da2009-09-16 22:47:08 +000012290 // Try to convert the decl specifier to a type. This works for
12291 // friend templates because ActOnTag never produces a ClassTemplateDecl
12292 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +000012293 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +000012294 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
12295 QualType T = TSI->getType();
Chris Lattner1fb66f42009-10-25 17:47:27 +000012296 if (TheDeclarator.isInvalidType())
Craig Topperc3ec1492014-05-26 06:22:03 +000012297 return nullptr;
John McCall07e91c02009-08-06 02:15:43 +000012298
Douglas Gregor6c110f32010-12-16 01:14:37 +000012299 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
Craig Topperc3ec1492014-05-26 06:22:03 +000012300 return nullptr;
Douglas Gregor6c110f32010-12-16 01:14:37 +000012301
John McCall11083da2009-09-16 22:47:08 +000012302 // This is definitely an error in C++98. It's probably meant to
12303 // be forbidden in C++0x, too, but the specification is just
12304 // poorly written.
12305 //
12306 // The problem is with declarations like the following:
12307 // template <T> friend A<T>::foo;
12308 // where deciding whether a class C is a friend or not now hinges
12309 // on whether there exists an instantiation of A that causes
12310 // 'foo' to equal C. There are restrictions on class-heads
12311 // (which we declare (by fiat) elaborated friend declarations to
12312 // be) that makes this tractable.
12313 //
12314 // FIXME: handle "template <> friend class A<T>;", which
12315 // is possibly well-formed? Who even knows?
Douglas Gregore677daf2010-03-31 22:19:08 +000012316 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCall11083da2009-09-16 22:47:08 +000012317 Diag(Loc, diag::err_tagless_friend_type_template)
12318 << DS.getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +000012319 return nullptr;
John McCall11083da2009-09-16 22:47:08 +000012320 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012321
John McCallaa74a0c2009-08-28 07:59:38 +000012322 // C++98 [class.friend]p1: A friend of a class is a function
12323 // or class that is not a member of the class . . .
John McCall463e10c2009-12-22 00:59:39 +000012324 // This is fixed in DR77, which just barely didn't make the C++03
12325 // deadline. It's also a very silly restriction that seriously
12326 // affects inner classes and which nobody else seems to implement;
12327 // thus we never diagnose it, not even in -pedantic.
John McCall15ad0962010-03-25 18:04:51 +000012328 //
12329 // But note that we could warn about it: it's always useless to
12330 // friend one of your own members (it's not, however, worthless to
12331 // friend a member of an arbitrary specialization of your template).
John McCallaa74a0c2009-08-28 07:59:38 +000012332
John McCall11083da2009-09-16 22:47:08 +000012333 Decl *D;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012334 if (unsigned NumTempParamLists = TempParams.size())
John McCall11083da2009-09-16 22:47:08 +000012335 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012336 NumTempParamLists,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000012337 TempParams.data(),
John McCall15ad0962010-03-25 18:04:51 +000012338 TSI,
John McCall11083da2009-09-16 22:47:08 +000012339 DS.getFriendSpecLoc());
12340 else
Abramo Bagnara254b6302011-10-29 20:52:52 +000012341 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012342
12343 if (!D)
Craig Topperc3ec1492014-05-26 06:22:03 +000012344 return nullptr;
12345
John McCall11083da2009-09-16 22:47:08 +000012346 D->setAccess(AS_public);
12347 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +000012348
John McCall48871652010-08-21 09:40:31 +000012349 return D;
John McCallaa74a0c2009-08-28 07:59:38 +000012350}
12351
Rafael Espindola0a67e2f2013-01-08 20:44:06 +000012352NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
12353 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +000012354 const DeclSpec &DS = D.getDeclSpec();
12355
12356 assert(DS.isFriendSpecified());
12357 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
12358
12359 SourceLocation Loc = D.getIdentifierLoc();
John McCall8cb7bdf2010-06-04 23:28:52 +000012360 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall07e91c02009-08-06 02:15:43 +000012361
12362 // C++ [class.friend]p1
12363 // A friend of a class is a function or class....
12364 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +000012365 // It *doesn't* see through dependent types, which is correct
12366 // according to [temp.arg.type]p3:
12367 // If a declaration acquires a function type through a
12368 // type dependent on a template-parameter and this causes
12369 // a declaration that does not use the syntactic form of a
12370 // function declarator to have a function type, the program
12371 // is ill-formed.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000012372 if (!TInfo->getType()->isFunctionType()) {
John McCall07e91c02009-08-06 02:15:43 +000012373 Diag(Loc, diag::err_unexpected_friend);
12374
12375 // It might be worthwhile to try to recover by creating an
12376 // appropriate declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +000012377 return nullptr;
John McCall07e91c02009-08-06 02:15:43 +000012378 }
12379
12380 // C++ [namespace.memdef]p3
12381 // - If a friend declaration in a non-local class first declares a
12382 // class or function, the friend class or function is a member
12383 // of the innermost enclosing namespace.
12384 // - The name of the friend is not found by simple name lookup
12385 // until a matching declaration is provided in that namespace
12386 // scope (either before or after the class declaration granting
12387 // friendship).
12388 // - If a friend function is called, its name may be found by the
12389 // name lookup that considers functions from namespaces and
12390 // classes associated with the types of the function arguments.
12391 // - When looking for a prior declaration of a class or a function
12392 // declared as a friend, scopes outside the innermost enclosing
12393 // namespace scope are not considered.
12394
John McCallde3fd222010-10-12 23:13:28 +000012395 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000012396 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
12397 DeclarationName Name = NameInfo.getName();
John McCall07e91c02009-08-06 02:15:43 +000012398 assert(Name);
12399
Douglas Gregor6c110f32010-12-16 01:14:37 +000012400 // Check for unexpanded parameter packs.
12401 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
12402 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
12403 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
Craig Topperc3ec1492014-05-26 06:22:03 +000012404 return nullptr;
Douglas Gregor6c110f32010-12-16 01:14:37 +000012405
John McCall07e91c02009-08-06 02:15:43 +000012406 // The context we found the declaration in, or in which we should
12407 // create the declaration.
12408 DeclContext *DC;
John McCallccbc0322010-10-13 06:22:15 +000012409 Scope *DCScope = S;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000012410 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +000012411 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +000012412
Richard Smith114394f2013-08-09 04:35:01 +000012413 // There are five cases here.
12414 // - There's no scope specifier and we're in a local class. Only look
12415 // for functions declared in the immediately-enclosing block scope.
12416 // We recover from invalid scope qualifiers as if they just weren't there.
Craig Topperc3ec1492014-05-26 06:22:03 +000012417 FunctionDecl *FunctionContainingLocalClass = nullptr;
Richard Smith114394f2013-08-09 04:35:01 +000012418 if ((SS.isInvalid() || !SS.isSet()) &&
12419 (FunctionContainingLocalClass =
12420 cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
12421 // C++11 [class.friend]p11:
John McCallf7cfb222010-10-13 05:45:15 +000012422 // If a friend declaration appears in a local class and the name
12423 // specified is an unqualified name, a prior declaration is
12424 // looked up without considering scopes that are outside the
12425 // innermost enclosing non-class scope. For a friend function
12426 // declaration, if there is no prior declaration, the program is
12427 // ill-formed.
Richard Smith114394f2013-08-09 04:35:01 +000012428
12429 // Find the innermost enclosing non-class scope. This is the block
12430 // scope containing the local class definition (or for a nested class,
12431 // the outer local class).
12432 DCScope = S->getFnParent();
12433
12434 // Look up the function name in the scope.
12435 Previous.clear(LookupLocalFriendName);
12436 LookupName(Previous, S, /*AllowBuiltinCreation*/false);
12437
12438 if (!Previous.empty()) {
12439 // All possible previous declarations must have the same context:
12440 // either they were declared at block scope or they are members of
12441 // one of the enclosing local classes.
12442 DC = Previous.getRepresentativeDecl()->getDeclContext();
12443 } else {
12444 // This is ill-formed, but provide the context that we would have
12445 // declared the function in, if we were permitted to, for error recovery.
12446 DC = FunctionContainingLocalClass;
12447 }
Richard Smith541b38b2013-09-20 01:15:31 +000012448 adjustContextForLocalExternDecl(DC);
Richard Smith114394f2013-08-09 04:35:01 +000012449
12450 // C++ [class.friend]p6:
12451 // A function can be defined in a friend declaration of a class if and
12452 // only if the class is a non-local class (9.8), the function name is
12453 // unqualified, and the function has namespace scope.
12454 if (D.isFunctionDefinition()) {
12455 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
12456 }
12457
12458 // - There's no scope specifier, in which case we just go to the
12459 // appropriate scope and look for a function or function template
12460 // there as appropriate.
12461 } else if (SS.isInvalid() || !SS.isSet()) {
12462 // C++11 [namespace.memdef]p3:
12463 // If the name in a friend declaration is neither qualified nor
12464 // a template-id and the declaration is a function or an
12465 // elaborated-type-specifier, the lookup to determine whether
12466 // the entity has been previously declared shall not consider
12467 // any scopes outside the innermost enclosing namespace.
John McCallf4776592010-10-14 22:22:28 +000012468 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall07e91c02009-08-06 02:15:43 +000012469
John McCallf7cfb222010-10-13 05:45:15 +000012470 // Find the appropriate context according to the above.
John McCall07e91c02009-08-06 02:15:43 +000012471 DC = CurContext;
John McCall07e91c02009-08-06 02:15:43 +000012472
Rafael Espindola3626b7e2013-04-25 20:12:36 +000012473 // Skip class contexts. If someone can cite chapter and verse
12474 // for this behavior, that would be nice --- it's what GCC and
12475 // EDG do, and it seems like a reasonable intent, but the spec
12476 // really only says that checks for unqualified existing
12477 // declarations should stop at the nearest enclosing namespace,
12478 // not that they should only consider the nearest enclosing
12479 // namespace.
12480 while (DC->isRecord())
12481 DC = DC->getParent();
12482
12483 DeclContext *LookupDC = DC;
12484 while (LookupDC->isTransparentContext())
12485 LookupDC = LookupDC->getParent();
12486
12487 while (true) {
12488 LookupQualifiedName(Previous, LookupDC);
John McCall07e91c02009-08-06 02:15:43 +000012489
Rafael Espindola3626b7e2013-04-25 20:12:36 +000012490 if (!Previous.empty()) {
12491 DC = LookupDC;
12492 break;
John McCallf4776592010-10-14 22:22:28 +000012493 }
Rafael Espindola3626b7e2013-04-25 20:12:36 +000012494
12495 if (isTemplateId) {
12496 if (isa<TranslationUnitDecl>(LookupDC)) break;
12497 } else {
12498 if (LookupDC->isFileContext()) break;
12499 }
12500 LookupDC = LookupDC->getParent();
John McCall07e91c02009-08-06 02:15:43 +000012501 }
12502
John McCallccbc0322010-10-13 06:22:15 +000012503 DCScope = getScopeForDeclContext(S, DC);
Richard Smith114394f2013-08-09 04:35:01 +000012504
John McCallde3fd222010-10-12 23:13:28 +000012505 // - There's a non-dependent scope specifier, in which case we
12506 // compute it and do a previous lookup there for a function
12507 // or function template.
12508 } else if (!SS.getScopeRep()->isDependent()) {
12509 DC = computeDeclContext(SS);
Craig Topperc3ec1492014-05-26 06:22:03 +000012510 if (!DC) return nullptr;
John McCallde3fd222010-10-12 23:13:28 +000012511
Craig Topperc3ec1492014-05-26 06:22:03 +000012512 if (RequireCompleteDeclContext(SS, DC)) return nullptr;
John McCallde3fd222010-10-12 23:13:28 +000012513
12514 LookupQualifiedName(Previous, DC);
12515
12516 // Ignore things found implicitly in the wrong scope.
12517 // TODO: better diagnostics for this case. Suggesting the right
12518 // qualified scope would be nice...
12519 LookupResult::Filter F = Previous.makeFilter();
12520 while (F.hasNext()) {
12521 NamedDecl *D = F.next();
12522 if (!DC->InEnclosingNamespaceSetOf(
12523 D->getDeclContext()->getRedeclContext()))
12524 F.erase();
12525 }
12526 F.done();
12527
12528 if (Previous.empty()) {
12529 D.setInvalidType();
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000012530 Diag(Loc, diag::err_qualified_friend_not_found)
12531 << Name << TInfo->getType();
Craig Topperc3ec1492014-05-26 06:22:03 +000012532 return nullptr;
John McCallde3fd222010-10-12 23:13:28 +000012533 }
12534
12535 // C++ [class.friend]p1: A friend of a class is a function or
12536 // class that is not a member of the class . . .
Richard Smith0bf8a4922011-10-18 20:49:44 +000012537 if (DC->Equals(CurContext))
12538 Diag(DS.getFriendSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +000012539 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +000012540 diag::warn_cxx98_compat_friend_is_member :
12541 diag::err_friend_is_member);
Douglas Gregor16e65612011-10-10 01:11:59 +000012542
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000012543 if (D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000012544 // C++ [class.friend]p6:
12545 // A function can be defined in a friend declaration of a class if and
12546 // only if the class is a non-local class (9.8), the function name is
12547 // unqualified, and the function has namespace scope.
12548 SemaDiagnosticBuilder DB
12549 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
12550
12551 DB << SS.getScopeRep();
12552 if (DC->isFileContext())
12553 DB << FixItHint::CreateRemoval(SS.getRange());
12554 SS.clear();
12555 }
John McCallde3fd222010-10-12 23:13:28 +000012556
12557 // - There's a scope specifier that does not match any template
12558 // parameter lists, in which case we use some arbitrary context,
12559 // create a method or method template, and wait for instantiation.
12560 // - There's a scope specifier that does match some template
12561 // parameter lists, which we don't handle right now.
12562 } else {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000012563 if (D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000012564 // C++ [class.friend]p6:
12565 // A function can be defined in a friend declaration of a class if and
12566 // only if the class is a non-local class (9.8), the function name is
12567 // unqualified, and the function has namespace scope.
12568 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
12569 << SS.getScopeRep();
12570 }
12571
John McCallde3fd222010-10-12 23:13:28 +000012572 DC = CurContext;
12573 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall07e91c02009-08-06 02:15:43 +000012574 }
Douglas Gregor16e65612011-10-10 01:11:59 +000012575
John McCallf7cfb222010-10-13 05:45:15 +000012576 if (!DC->isRecord()) {
John McCall07e91c02009-08-06 02:15:43 +000012577 // This implies that it has to be an operator or function.
Douglas Gregor7861a802009-11-03 01:35:08 +000012578 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
12579 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
12580 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall07e91c02009-08-06 02:15:43 +000012581 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor7861a802009-11-03 01:35:08 +000012582 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
12583 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
Craig Topperc3ec1492014-05-26 06:22:03 +000012584 return nullptr;
John McCall07e91c02009-08-06 02:15:43 +000012585 }
John McCall07e91c02009-08-06 02:15:43 +000012586 }
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000012587
Douglas Gregordd847ba2011-11-03 16:37:14 +000012588 // FIXME: This is an egregious hack to cope with cases where the scope stack
12589 // does not contain the declaration context, i.e., in an out-of-line
12590 // definition of a class.
12591 Scope FakeDCScope(S, Scope::DeclScope, Diags);
12592 if (!DCScope) {
12593 FakeDCScope.setEntity(DC);
12594 DCScope = &FakeDCScope;
12595 }
Richard Smith114394f2013-08-09 04:35:01 +000012596
Francois Pichet00c7e6c2011-08-14 03:52:19 +000012597 bool AddToScope = true;
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000012598 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000012599 TemplateParams, AddToScope);
Craig Topperc3ec1492014-05-26 06:22:03 +000012600 if (!ND) return nullptr;
John McCall759e32b2009-08-31 22:39:49 +000012601
Douglas Gregora29a3ff2009-09-28 00:08:27 +000012602 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +000012603
Richard Smith114394f2013-08-09 04:35:01 +000012604 // If we performed typo correction, we might have added a scope specifier
12605 // and changed the decl context.
12606 DC = ND->getDeclContext();
12607
John McCall759e32b2009-08-31 22:39:49 +000012608 // Add the function declaration to the appropriate lookup tables,
12609 // adjusting the redeclarations list as necessary. We don't
12610 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +000012611 //
John McCall759e32b2009-08-31 22:39:49 +000012612 // Also update the scope-based lookup if the target context's
12613 // lookup context is in lexical scope.
12614 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +000012615 DC = DC->getRedeclContext();
Richard Smith05afe5e2012-03-13 03:12:56 +000012616 DC->makeDeclVisibleInContext(ND);
John McCall759e32b2009-08-31 22:39:49 +000012617 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +000012618 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +000012619 }
John McCallaa74a0c2009-08-28 07:59:38 +000012620
12621 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +000012622 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +000012623 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +000012624 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +000012625 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +000012626
John McCalla0a96892012-08-10 03:15:35 +000012627 if (ND->isInvalidDecl()) {
John McCallde3fd222010-10-12 23:13:28 +000012628 FrD->setInvalidDecl();
John McCalla0a96892012-08-10 03:15:35 +000012629 } else {
12630 if (DC->isRecord()) CheckFriendAccess(ND);
12631
John McCall2c2eb122010-10-16 06:59:13 +000012632 FunctionDecl *FD;
12633 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
12634 FD = FTD->getTemplatedDecl();
12635 else
12636 FD = cast<FunctionDecl>(ND);
12637
David Majnemer502b0ed2013-06-25 23:09:30 +000012638 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
12639 // default argument expression, that declaration shall be a definition
12640 // and shall be the only declaration of the function or function
12641 // template in the translation unit.
12642 if (functionDeclHasDefaultArgument(FD)) {
12643 if (FunctionDecl *OldFD = FD->getPreviousDecl()) {
12644 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
12645 Diag(OldFD->getLocation(), diag::note_previous_declaration);
12646 } else if (!D.isFunctionDefinition())
12647 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
12648 }
12649
John McCall2c2eb122010-10-16 06:59:13 +000012650 // Mark templated-scope function declarations as unsupported.
Richard Smith04b35e92014-09-29 05:57:29 +000012651 if (FD->getNumTemplateParameterLists() && SS.isValid()) {
12652 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
12653 << SS.getScopeRep() << SS.getRange()
12654 << cast<CXXRecordDecl>(CurContext);
John McCall2c2eb122010-10-16 06:59:13 +000012655 FrD->setUnsupportedFriend(true);
Richard Smith04b35e92014-09-29 05:57:29 +000012656 }
John McCall2c2eb122010-10-16 06:59:13 +000012657 }
John McCallde3fd222010-10-12 23:13:28 +000012658
John McCall48871652010-08-21 09:40:31 +000012659 return ND;
Anders Carlsson38811702009-05-11 22:55:49 +000012660}
12661
John McCall48871652010-08-21 09:40:31 +000012662void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
12663 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +000012664
Aaron Ballmanf96361e2013-01-16 23:39:10 +000012665 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
Sebastian Redlf769df52009-03-24 22:27:57 +000012666 if (!Fn) {
12667 Diag(DelLoc, diag::err_deleted_non_function);
12668 return;
12669 }
Richard Smithb4d2a152013-04-02 19:38:47 +000012670
Douglas Gregorec9fd132012-01-14 16:38:05 +000012671 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
David Blaikie36805522012-06-25 21:55:30 +000012672 // Don't consider the implicit declaration we generate for explicit
12673 // specializations. FIXME: Do not generate these implicit declarations.
Richard Smithbdd14642014-02-04 01:14:30 +000012674 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
12675 Prev->getPreviousDecl()) &&
12676 !Prev->isDefined()) {
David Blaikie36805522012-06-25 21:55:30 +000012677 Diag(DelLoc, diag::err_deleted_decl_not_first);
Richard Smithbdd14642014-02-04 01:14:30 +000012678 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
12679 Prev->isImplicit() ? diag::note_previous_implicit_declaration
12680 : diag::note_previous_declaration);
David Blaikie36805522012-06-25 21:55:30 +000012681 }
Sebastian Redlf769df52009-03-24 22:27:57 +000012682 // If the declaration wasn't the first, we delete the function anyway for
12683 // recovery.
Richard Smithb4d2a152013-04-02 19:38:47 +000012684 Fn = Fn->getCanonicalDecl();
Sebastian Redlf769df52009-03-24 22:27:57 +000012685 }
Richard Smithb4d2a152013-04-02 19:38:47 +000012686
Nico Rieck9de0a572014-05-29 16:51:19 +000012687 // dllimport/dllexport cannot be deleted.
12688 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
12689 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
12690 Fn->setInvalidDecl();
12691 }
12692
Richard Smithb4d2a152013-04-02 19:38:47 +000012693 if (Fn->isDeleted())
12694 return;
12695
12696 // See if we're deleting a function which is already known to override a
12697 // non-deleted virtual function.
12698 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
12699 bool IssuedDiagnostic = false;
12700 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
12701 E = MD->end_overridden_methods();
12702 I != E; ++I) {
12703 if (!(*MD->begin_overridden_methods())->isDeleted()) {
12704 if (!IssuedDiagnostic) {
12705 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
12706 IssuedDiagnostic = true;
12707 }
12708 Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
12709 }
12710 }
12711 }
12712
Richard Smithb63b6ee2014-01-22 01:43:19 +000012713 // C++11 [basic.start.main]p3:
12714 // A program that defines main as deleted [...] is ill-formed.
12715 if (Fn->isMain())
12716 Diag(DelLoc, diag::err_deleted_main);
12717
Alexis Hunt4a8ea102011-05-06 20:44:56 +000012718 Fn->setDeletedAsWritten();
Sebastian Redlf769df52009-03-24 22:27:57 +000012719}
Sebastian Redl4c018662009-04-27 21:33:24 +000012720
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012721void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
Aaron Ballmanf96361e2013-01-16 23:39:10 +000012722 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012723
12724 if (MD) {
Alexis Hunt1fb4e762011-05-23 21:07:59 +000012725 if (MD->getParent()->isDependentType()) {
12726 MD->setDefaulted();
12727 MD->setExplicitlyDefaulted();
12728 return;
12729 }
12730
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012731 CXXSpecialMember Member = getSpecialMember(MD);
12732 if (Member == CXXInvalid) {
Eli Friedman84c0143e2013-07-11 23:55:07 +000012733 if (!MD->isInvalidDecl())
12734 Diag(DefaultLoc, diag::err_default_special_members);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012735 return;
12736 }
12737
12738 MD->setDefaulted();
12739 MD->setExplicitlyDefaulted();
12740
Alexis Hunt61ae8d32011-05-23 23:14:04 +000012741 // If this definition appears within the record, do the checking when
12742 // the record is complete.
12743 const FunctionDecl *Primary = MD;
Richard Smith802c4b72012-08-23 06:16:52 +000012744 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
Alexis Hunt61ae8d32011-05-23 23:14:04 +000012745 // Find the uninstantiated declaration that actually had the '= default'
12746 // on it.
Richard Smith802c4b72012-08-23 06:16:52 +000012747 Pattern->isDefined(Primary);
Alexis Hunt61ae8d32011-05-23 23:14:04 +000012748
Richard Smith3901dfe2013-03-27 00:22:47 +000012749 // If the method was defaulted on its first declaration, we will have
12750 // already performed the checking in CheckCompletedCXXClass. Such a
12751 // declaration doesn't trigger an implicit definition.
Alexis Hunt61ae8d32011-05-23 23:14:04 +000012752 if (Primary == Primary->getCanonicalDecl())
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012753 return;
12754
Richard Smithd3b5c9082012-07-27 04:22:15 +000012755 CheckExplicitlyDefaultedSpecialMember(MD);
12756
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012757 if (MD->isInvalidDecl())
12758 return;
12759
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012760 switch (Member) {
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012761 case CXXDefaultConstructor:
12762 DefineImplicitDefaultConstructor(DefaultLoc,
12763 cast<CXXConstructorDecl>(MD));
Alexis Hunt913820d2011-05-13 06:10:58 +000012764 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012765 case CXXCopyConstructor:
12766 DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012767 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012768 case CXXCopyAssignment:
12769 DefineImplicitCopyAssignment(DefaultLoc, MD);
Alexis Huntc9a55732011-05-14 05:23:28 +000012770 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012771 case CXXDestructor:
12772 DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
Alexis Huntf91729462011-05-12 22:46:25 +000012773 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012774 case CXXMoveConstructor:
12775 DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
Alexis Hunt119c10e2011-05-25 23:16:36 +000012776 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012777 case CXXMoveAssignment:
12778 DefineImplicitMoveAssignment(DefaultLoc, MD);
Sebastian Redl22653ba2011-08-30 19:58:05 +000012779 break;
Sebastian Redl22653ba2011-08-30 19:58:05 +000012780 case CXXInvalid:
David Blaikie83d382b2011-09-23 05:06:16 +000012781 llvm_unreachable("Invalid special member.");
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012782 }
12783 } else {
12784 Diag(DefaultLoc, diag::err_default_special_members);
12785 }
12786}
12787
Sebastian Redl4c018662009-04-27 21:33:24 +000012788static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall8322c3a2011-02-13 04:07:26 +000012789 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl4c018662009-04-27 21:33:24 +000012790 Stmt *SubStmt = *CI;
12791 if (!SubStmt)
12792 continue;
12793 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012794 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl4c018662009-04-27 21:33:24 +000012795 diag::err_return_in_constructor_handler);
12796 if (!isa<Expr>(SubStmt))
12797 SearchForReturnInStmt(Self, SubStmt);
12798 }
12799}
12800
12801void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
12802 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
12803 CXXCatchStmt *Handler = TryBlock->getHandler(I);
12804 SearchForReturnInStmt(*this, Handler);
12805 }
12806}
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012807
David Blaikie68f71a32013-01-18 23:03:15 +000012808bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
Aaron Ballman02df2e02012-12-09 17:45:41 +000012809 const CXXMethodDecl *Old) {
12810 const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
12811 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
12812
12813 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
12814
12815 // If the calling conventions match, everything is fine
12816 if (NewCC == OldCC)
12817 return false;
12818
Hans Wennborg2545efe2013-12-11 17:42:11 +000012819 // If the calling conventions mismatch because the new function is static,
12820 // suppress the calling convention mismatch error; the error about static
12821 // function override (err_static_overrides_virtual from
12822 // Sema::CheckFunctionDeclaration) is more clear.
12823 if (New->getStorageClass() == SC_Static)
12824 return false;
12825
Reid Kleckner78af0702013-08-27 23:08:25 +000012826 Diag(New->getLocation(),
12827 diag::err_conflicting_overriding_cc_attributes)
12828 << New->getDeclName() << New->getType() << Old->getType();
12829 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12830 return true;
Aaron Ballman02df2e02012-12-09 17:45:41 +000012831}
12832
Mike Stump11289f42009-09-09 15:08:12 +000012833bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012834 const CXXMethodDecl *Old) {
Alp Toker314cc812014-01-25 16:55:45 +000012835 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
12836 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012837
Chandler Carruth284bb2e2010-02-15 11:53:20 +000012838 if (Context.hasSameType(NewTy, OldTy) ||
12839 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012840 return false;
Mike Stump11289f42009-09-09 15:08:12 +000012841
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012842 // Check if the return types are covariant
12843 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +000012844
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012845 /// Both types must be pointers or references to classes.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000012846 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
12847 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012848 NewClassTy = NewPT->getPointeeType();
12849 OldClassTy = OldPT->getPointeeType();
12850 }
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000012851 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
12852 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
12853 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
12854 NewClassTy = NewRT->getPointeeType();
12855 OldClassTy = OldRT->getPointeeType();
12856 }
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012857 }
12858 }
Mike Stump11289f42009-09-09 15:08:12 +000012859
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012860 // The return types aren't either both pointers or references to a class type.
12861 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +000012862 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012863 diag::err_different_return_type_for_overriding_virtual_function)
Alp Tokerd0787eb2014-07-02 01:47:15 +000012864 << New->getDeclName() << NewTy << OldTy
12865 << New->getReturnTypeSourceRange();
12866 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12867 << Old->getReturnTypeSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +000012868
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012869 return true;
12870 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012871
Anders Carlssone60365b2009-12-31 18:34:24 +000012872 // C++ [class.virtual]p6:
12873 // If the return type of D::f differs from the return type of B::f, the
12874 // class type in the return type of D::f shall be complete at the point of
12875 // declaration of D::f or shall be the class type D.
Anders Carlsson0c9dd842009-12-31 18:54:35 +000012876 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
12877 if (!RT->isBeingDefined() &&
12878 RequireCompleteType(New->getLocation(), NewClassTy,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000012879 diag::err_covariant_return_incomplete,
12880 New->getDeclName()))
Anders Carlssone60365b2009-12-31 18:34:24 +000012881 return true;
Anders Carlsson0c9dd842009-12-31 18:54:35 +000012882 }
Anders Carlssone60365b2009-12-31 18:34:24 +000012883
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +000012884 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012885 // Check if the new class derives from the old class.
12886 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
Alp Tokerd0787eb2014-07-02 01:47:15 +000012887 Diag(New->getLocation(), diag::err_covariant_return_not_derived)
12888 << New->getDeclName() << NewTy << OldTy
12889 << New->getReturnTypeSourceRange();
12890 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12891 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012892 return true;
12893 }
Mike Stump11289f42009-09-09 15:08:12 +000012894
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012895 // Check if we the conversion from derived to base is valid.
Alp Tokerd0787eb2014-07-02 01:47:15 +000012896 if (CheckDerivedToBaseConversion(
12897 NewClassTy, OldClassTy,
12898 diag::err_covariant_return_inaccessible_base,
12899 diag::err_covariant_return_ambiguous_derived_to_base_conv,
12900 New->getLocation(), New->getReturnTypeSourceRange(),
12901 New->getDeclName(), nullptr)) {
John McCallc1465822011-02-14 07:13:47 +000012902 // FIXME: this note won't trigger for delayed access control
12903 // diagnostics, and it's impossible to get an undelayed error
12904 // here from access control during the original parse because
12905 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Alp Tokerd0787eb2014-07-02 01:47:15 +000012906 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12907 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012908 return true;
12909 }
12910 }
Mike Stump11289f42009-09-09 15:08:12 +000012911
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012912 // The qualifiers of the return types must be the same.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000012913 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012914 Diag(New->getLocation(),
12915 diag::err_covariant_return_type_different_qualifications)
Alp Tokerd0787eb2014-07-02 01:47:15 +000012916 << New->getDeclName() << NewTy << OldTy
12917 << New->getReturnTypeSourceRange();
12918 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12919 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012920 return true;
12921 };
Mike Stump11289f42009-09-09 15:08:12 +000012922
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012923
12924 // The new class type must have the same or less qualifiers as the old type.
12925 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
12926 Diag(New->getLocation(),
12927 diag::err_covariant_return_type_class_type_more_qualified)
Alp Tokerd0787eb2014-07-02 01:47:15 +000012928 << New->getDeclName() << NewTy << OldTy
12929 << New->getReturnTypeSourceRange();
12930 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12931 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012932 return true;
12933 };
Mike Stump11289f42009-09-09 15:08:12 +000012934
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012935 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012936}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012937
Douglas Gregor21920e372009-12-01 17:24:26 +000012938/// \brief Mark the given method pure.
12939///
12940/// \param Method the method to be marked pure.
12941///
12942/// \param InitRange the source range that covers the "0" initializer.
12943bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000012944 SourceLocation EndLoc = InitRange.getEnd();
12945 if (EndLoc.isValid())
12946 Method->setRangeEnd(EndLoc);
12947
Douglas Gregor21920e372009-12-01 17:24:26 +000012948 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
12949 Method->setPure();
Douglas Gregor21920e372009-12-01 17:24:26 +000012950 return false;
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000012951 }
Douglas Gregor21920e372009-12-01 17:24:26 +000012952
12953 if (!Method->isInvalidDecl())
12954 Diag(Method->getLocation(), diag::err_non_virtual_pure)
12955 << Method->getDeclName() << InitRange;
12956 return true;
12957}
12958
Douglas Gregor926410d2012-02-21 02:22:07 +000012959/// \brief Determine whether the given declaration is a static data member.
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012960static bool isStaticDataMember(const Decl *D) {
12961 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
12962 return Var->isStaticDataMember();
12963
12964 return false;
Douglas Gregor926410d2012-02-21 02:22:07 +000012965}
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012966
John McCall1f4ee7b2009-12-19 09:28:58 +000012967/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
12968/// an initializer for the out-of-line declaration 'Dcl'. The scope
12969/// is a fresh scope pushed for just this purpose.
12970///
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012971/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
12972/// static data member of class X, names should be looked up in the scope of
12973/// class X.
John McCall48871652010-08-21 09:40:31 +000012974void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012975 // If there is no declaration, there was an error parsing it.
Craig Topperc3ec1492014-05-26 06:22:03 +000012976 if (!D || D->isInvalidDecl())
12977 return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012978
Richard Smitha2302242013-12-05 07:51:02 +000012979 // We will always have a nested name specifier here, but this declaration
12980 // might not be out of line if the specifier names the current namespace:
12981 // extern int n;
12982 // int ::n = 0;
12983 if (D->isOutOfLine())
12984 EnterDeclaratorContext(S, D->getDeclContext());
12985
Douglas Gregor926410d2012-02-21 02:22:07 +000012986 // If we are parsing the initializer for a static data member, push a
12987 // new expression evaluation context that is associated with this static
12988 // data member.
12989 if (isStaticDataMember(D))
12990 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012991}
12992
12993/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall48871652010-08-21 09:40:31 +000012994/// initializer for the out-of-line declaration 'D'.
12995void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012996 // If there is no declaration, there was an error parsing it.
Craig Topperc3ec1492014-05-26 06:22:03 +000012997 if (!D || D->isInvalidDecl())
12998 return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012999
Douglas Gregor926410d2012-02-21 02:22:07 +000013000 if (isStaticDataMember(D))
Richard Smitha2302242013-12-05 07:51:02 +000013001 PopExpressionEvaluationContext();
Douglas Gregor926410d2012-02-21 02:22:07 +000013002
Richard Smitha2302242013-12-05 07:51:02 +000013003 if (D->isOutOfLine())
13004 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000013005}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000013006
13007/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
13008/// C++ if/switch/while/for statement.
13009/// e.g: "if (int x = f()) {...}"
John McCall48871652010-08-21 09:40:31 +000013010DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000013011 // C++ 6.4p2:
13012 // The declarator shall not specify a function or an array.
13013 // The type-specifier-seq shall not contain typedef and shall not declare a
13014 // new class or enumeration.
13015 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
13016 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000013017
13018 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor1fe12c92011-07-05 16:13:20 +000013019 if (!Dcl)
13020 return true;
13021
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000013022 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
13023 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000013024 << D.getSourceRange();
Douglas Gregor1fe12c92011-07-05 16:13:20 +000013025 return true;
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000013026 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000013027
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000013028 return Dcl;
13029}
Anders Carlssonf98849e2009-12-02 17:15:43 +000013030
Douglas Gregor4daf6a32011-07-28 19:11:31 +000013031void Sema::LoadExternalVTableUses() {
13032 if (!ExternalSource)
13033 return;
13034
13035 SmallVector<ExternalVTableUse, 4> VTables;
13036 ExternalSource->ReadUsedVTables(VTables);
13037 SmallVector<VTableUse, 4> NewUses;
13038 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
13039 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
13040 = VTablesUsed.find(VTables[I].Record);
13041 // Even if a definition wasn't required before, it may be required now.
13042 if (Pos != VTablesUsed.end()) {
13043 if (!Pos->second && VTables[I].DefinitionRequired)
13044 Pos->second = true;
13045 continue;
13046 }
13047
13048 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
13049 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
13050 }
13051
13052 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
13053}
13054
Douglas Gregor88d292c2010-05-13 16:44:06 +000013055void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
13056 bool DefinitionRequired) {
13057 // Ignore any vtable uses in unevaluated operands or for classes that do
13058 // not have a vtable.
13059 if (!Class->isDynamicClass() || Class->isDependentContext() ||
John McCallf413f5e2013-05-03 00:10:13 +000013060 CurContext->isDependentContext() || isUnevaluatedContext())
Rafael Espindolae7113ca2010-03-10 02:19:29 +000013061 return;
13062
Douglas Gregor88d292c2010-05-13 16:44:06 +000013063 // Try to insert this class into the map.
Douglas Gregor4daf6a32011-07-28 19:11:31 +000013064 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000013065 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
13066 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
13067 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
13068 if (!Pos.second) {
Daniel Dunbar53217762010-05-25 00:33:13 +000013069 // If we already had an entry, check to see if we are promoting this vtable
Nico Weberf1cebf02015-01-06 23:54:59 +000013070 // to require a definition. If so, we need to reappend to the VTableUses
Daniel Dunbar53217762010-05-25 00:33:13 +000013071 // list, since we may have already processed the first entry.
13072 if (DefinitionRequired && !Pos.first->second) {
13073 Pos.first->second = true;
13074 } else {
13075 // Otherwise, we can early exit.
13076 return;
13077 }
Hans Wennborg3d791542014-02-24 15:58:24 +000013078 } else {
13079 // The Microsoft ABI requires that we perform the destructor body
13080 // checks (i.e. operator delete() lookup) when the vtable is marked used, as
13081 // the deleting destructor is emitted with the vtable, not with the
13082 // destructor definition as in the Itanium ABI.
13083 // If it has a definition, we do the check at that point instead.
13084 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13085 Class->hasUserDeclaredDestructor() &&
13086 !Class->getDestructor()->isDefined() &&
13087 !Class->getDestructor()->isDeleted()) {
Reid Kleckner67130862014-06-12 22:39:12 +000013088 CXXDestructorDecl *DD = Class->getDestructor();
13089 ContextRAII SavedContext(*this, DD);
13090 CheckDestructor(DD);
Hans Wennborg3d791542014-02-24 15:58:24 +000013091 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000013092 }
13093
13094 // Local classes need to have their virtual members marked
13095 // immediately. For all other classes, we mark their virtual members
13096 // at the end of the translation unit.
13097 if (Class->isLocalClass())
13098 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar0547ad32010-05-11 21:32:35 +000013099 else
Douglas Gregor88d292c2010-05-13 16:44:06 +000013100 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregor0c4aad12010-05-11 20:24:17 +000013101}
13102
Douglas Gregor88d292c2010-05-13 16:44:06 +000013103bool Sema::DefineUsedVTables() {
Douglas Gregor4daf6a32011-07-28 19:11:31 +000013104 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000013105 if (VTableUses.empty())
Anders Carlsson82fccd02009-12-07 08:24:59 +000013106 return false;
Chandler Carruth88bfa5e2010-12-12 21:36:11 +000013107
Douglas Gregor88d292c2010-05-13 16:44:06 +000013108 // Note: The VTableUses vector could grow as a result of marking
13109 // the members of a class as "used", so we check the size each
Richard Smithd3b5c9082012-07-27 04:22:15 +000013110 // time through the loop and prefer indices (which are stable) to
Douglas Gregor88d292c2010-05-13 16:44:06 +000013111 // iterators (which are not).
Douglas Gregor97509692011-04-22 22:25:37 +000013112 bool DefinedAnything = false;
Douglas Gregor88d292c2010-05-13 16:44:06 +000013113 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbar105ce6d2010-05-25 00:32:58 +000013114 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor88d292c2010-05-13 16:44:06 +000013115 if (!Class)
13116 continue;
13117
13118 SourceLocation Loc = VTableUses[I].second;
13119
Richard Smithd3b5c9082012-07-27 04:22:15 +000013120 bool DefineVTable = true;
13121
Douglas Gregor88d292c2010-05-13 16:44:06 +000013122 // If this class has a key function, but that key function is
13123 // defined in another translation unit, we don't need to emit the
13124 // vtable even though we're using it.
John McCall6bd2a892013-01-25 22:31:03 +000013125 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +000013126 if (KeyFunction && !KeyFunction->hasBody()) {
Rafael Espindolaef7fe1f2013-08-26 23:23:21 +000013127 // The key function is in another translation unit.
13128 DefineVTable = false;
13129 TemplateSpecializationKind TSK =
13130 KeyFunction->getTemplateSpecializationKind();
13131 assert(TSK != TSK_ExplicitInstantiationDefinition &&
13132 TSK != TSK_ImplicitInstantiation &&
13133 "Instantiations don't have key functions");
13134 (void)TSK;
Douglas Gregor88d292c2010-05-13 16:44:06 +000013135 } else if (!KeyFunction) {
13136 // If we have a class with no key function that is the subject
13137 // of an explicit instantiation declaration, suppress the
13138 // vtable; it will live with the explicit instantiation
13139 // definition.
13140 bool IsExplicitInstantiationDeclaration
13141 = Class->getTemplateSpecializationKind()
13142 == TSK_ExplicitInstantiationDeclaration;
Aaron Ballman86c93902014-03-06 23:45:36 +000013143 for (auto R : Class->redecls()) {
Douglas Gregor88d292c2010-05-13 16:44:06 +000013144 TemplateSpecializationKind TSK
Aaron Ballman86c93902014-03-06 23:45:36 +000013145 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
Douglas Gregor88d292c2010-05-13 16:44:06 +000013146 if (TSK == TSK_ExplicitInstantiationDeclaration)
13147 IsExplicitInstantiationDeclaration = true;
13148 else if (TSK == TSK_ExplicitInstantiationDefinition) {
13149 IsExplicitInstantiationDeclaration = false;
13150 break;
13151 }
13152 }
13153
13154 if (IsExplicitInstantiationDeclaration)
Richard Smithd3b5c9082012-07-27 04:22:15 +000013155 DefineVTable = false;
13156 }
13157
13158 // The exception specifications for all virtual members may be needed even
13159 // if we are not providing an authoritative form of the vtable in this TU.
13160 // We may choose to emit it available_externally anyway.
13161 if (!DefineVTable) {
13162 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
13163 continue;
Douglas Gregor88d292c2010-05-13 16:44:06 +000013164 }
13165
13166 // Mark all of the virtual members of this class as referenced, so
13167 // that we can build a vtable. Then, tell the AST consumer that a
13168 // vtable for this class is required.
Douglas Gregor97509692011-04-22 22:25:37 +000013169 DefinedAnything = true;
Douglas Gregor88d292c2010-05-13 16:44:06 +000013170 MarkVirtualMembersReferenced(Loc, Class);
13171 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
Nico Weberb6a5d052015-01-15 04:07:35 +000013172 if (VTablesUsed[Canonical])
13173 Consumer.HandleVTable(Class);
Douglas Gregor88d292c2010-05-13 16:44:06 +000013174
13175 // Optionally warn if we're emitting a weak vtable.
Rafael Espindola3ae00052013-05-13 00:12:11 +000013176 if (Class->isExternallyVisible() &&
Douglas Gregor88d292c2010-05-13 16:44:06 +000013177 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Craig Topperc3ec1492014-05-26 06:22:03 +000013178 const FunctionDecl *KeyFunctionDef = nullptr;
Douglas Gregor34bc6e52011-09-23 19:04:03 +000013179 if (!KeyFunction ||
13180 (KeyFunction->hasBody(KeyFunctionDef) &&
13181 KeyFunctionDef->isInlined()))
David Blaikie72b61202011-12-09 18:32:50 +000013182 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
13183 TSK_ExplicitInstantiationDefinition
13184 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
13185 << Class;
Douglas Gregor88d292c2010-05-13 16:44:06 +000013186 }
Anders Carlssonf98849e2009-12-02 17:15:43 +000013187 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000013188 VTableUses.clear();
13189
Douglas Gregor97509692011-04-22 22:25:37 +000013190 return DefinedAnything;
Anders Carlssonf98849e2009-12-02 17:15:43 +000013191}
Anders Carlsson82fccd02009-12-07 08:24:59 +000013192
Richard Smithd3b5c9082012-07-27 04:22:15 +000013193void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
13194 const CXXRecordDecl *RD) {
Aaron Ballman2b124d12014-03-13 16:36:16 +000013195 for (const auto *I : RD->methods())
13196 if (I->isVirtual() && !I->isPure())
13197 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
Richard Smithd3b5c9082012-07-27 04:22:15 +000013198}
13199
Rafael Espindola5b334082010-03-26 00:36:59 +000013200void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
13201 const CXXRecordDecl *RD) {
Richard Smith4ff9ff92012-07-07 06:59:51 +000013202 // Mark all functions which will appear in RD's vtable as used.
13203 CXXFinalOverriderMap FinalOverriders;
13204 RD->getFinalOverriders(FinalOverriders);
13205 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
13206 E = FinalOverriders.end();
13207 I != E; ++I) {
13208 for (OverridingMethods::const_iterator OI = I->second.begin(),
13209 OE = I->second.end();
13210 OI != OE; ++OI) {
13211 assert(OI->second.size() > 0 && "no final overrider");
13212 CXXMethodDecl *Overrider = OI->second.front().Method;
Anders Carlsson82fccd02009-12-07 08:24:59 +000013213
Richard Smith4ff9ff92012-07-07 06:59:51 +000013214 // C++ [basic.def.odr]p2:
13215 // [...] A virtual member function is used if it is not pure. [...]
13216 if (!Overrider->isPure())
13217 MarkFunctionReferenced(Loc, Overrider);
13218 }
Anders Carlsson82fccd02009-12-07 08:24:59 +000013219 }
Rafael Espindola5b334082010-03-26 00:36:59 +000013220
13221 // Only classes that have virtual bases need a VTT.
13222 if (RD->getNumVBases() == 0)
13223 return;
13224
Aaron Ballman574705e2014-03-13 15:41:46 +000013225 for (const auto &I : RD->bases()) {
Rafael Espindola5b334082010-03-26 00:36:59 +000013226 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +000013227 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Rafael Espindola5b334082010-03-26 00:36:59 +000013228 if (Base->getNumVBases() == 0)
13229 continue;
13230 MarkVirtualMembersReferenced(Loc, Base);
13231 }
Anders Carlsson82fccd02009-12-07 08:24:59 +000013232}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013233
13234/// SetIvarInitializers - This routine builds initialization ASTs for the
13235/// Objective-C implementation whose ivars need be initialized.
13236void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000013237 if (!getLangOpts().CPlusPlus)
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013238 return;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +000013239 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000013240 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013241 CollectIvarsToConstructOrDestruct(OID, ivars);
13242 if (ivars.empty())
13243 return;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000013244 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013245 for (unsigned i = 0; i < ivars.size(); i++) {
13246 FieldDecl *Field = ivars[i];
Douglas Gregor527786e2010-05-20 02:24:22 +000013247 if (Field->isInvalidDecl())
13248 continue;
13249
Alexis Hunt1d792652011-01-08 20:30:50 +000013250 CXXCtorInitializer *Member;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013251 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
13252 InitializationKind InitKind =
13253 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
Dmitri Gribenko78852e92013-05-05 20:40:26 +000013254
13255 InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
13256 ExprResult MemberInit =
13257 InitSeq.Perform(*this, InitEntity, InitKind, None);
Douglas Gregora40433a2010-12-07 00:41:46 +000013258 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013259 // Note, MemberInit could actually come back empty if no initialization
13260 // is required (e.g., because it would call a trivial default constructor)
13261 if (!MemberInit.get() || MemberInit.isInvalid())
13262 continue;
John McCallacf0ee52010-10-08 02:01:28 +000013263
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013264 Member =
Alexis Hunt1d792652011-01-08 20:30:50 +000013265 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
13266 SourceLocation(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013267 MemberInit.getAs<Expr>(),
Alexis Hunt1d792652011-01-08 20:30:50 +000013268 SourceLocation());
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013269 AllToInit.push_back(Member);
Douglas Gregor527786e2010-05-20 02:24:22 +000013270
13271 // Be sure that the destructor is accessible and is marked as referenced.
Nico Weberaa0117c2014-11-12 03:44:43 +000013272 if (const RecordType *RecordTy =
13273 Context.getBaseElementType(Field->getType())
13274 ->getAs<RecordType>()) {
13275 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregore71edda2010-07-01 22:47:18 +000013276 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000013277 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor527786e2010-05-20 02:24:22 +000013278 CheckDestructorAccess(Field->getLocation(), Destructor,
13279 PDiag(diag::err_access_dtor_ivar)
13280 << Context.getBaseElementType(Field->getType()));
13281 }
13282 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013283 }
13284 ObjCImplementation->setIvarInitializers(Context,
13285 AllToInit.data(), AllToInit.size());
13286 }
13287}
Alexis Hunt6118d662011-05-04 05:57:24 +000013288
Alexis Hunt27a761d2011-05-04 23:29:54 +000013289static
13290void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
13291 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
13292 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
13293 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
13294 Sema &S) {
Alexis Hunt27a761d2011-05-04 23:29:54 +000013295 if (Ctor->isInvalidDecl())
13296 return;
13297
Richard Smith802c4b72012-08-23 06:16:52 +000013298 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
13299
13300 // Target may not be determinable yet, for instance if this is a dependent
13301 // call in an uninstantiated template.
13302 if (Target) {
Craig Topperc3ec1492014-05-26 06:22:03 +000013303 const FunctionDecl *FNTarget = nullptr;
Richard Smith802c4b72012-08-23 06:16:52 +000013304 (void)Target->hasBody(FNTarget);
13305 Target = const_cast<CXXConstructorDecl*>(
13306 cast_or_null<CXXConstructorDecl>(FNTarget));
13307 }
Alexis Hunt27a761d2011-05-04 23:29:54 +000013308
13309 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
13310 // Avoid dereferencing a null pointer here.
Craig Topperc3ec1492014-05-26 06:22:03 +000013311 *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
Alexis Hunt27a761d2011-05-04 23:29:54 +000013312
David Blaikie82e95a32014-11-19 07:49:47 +000013313 if (!Current.insert(Canonical).second)
Alexis Hunt27a761d2011-05-04 23:29:54 +000013314 return;
13315
13316 // We know that beyond here, we aren't chaining into a cycle.
13317 if (!Target || !Target->isDelegatingConstructor() ||
13318 Target->isInvalidDecl() || Valid.count(TCanonical)) {
Benjamin Kramer8bf44352013-07-24 15:28:33 +000013319 Valid.insert(Current.begin(), Current.end());
Alexis Hunt27a761d2011-05-04 23:29:54 +000013320 Current.clear();
13321 // We've hit a cycle.
13322 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
13323 Current.count(TCanonical)) {
13324 // If we haven't diagnosed this cycle yet, do so now.
13325 if (!Invalid.count(TCanonical)) {
13326 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Alexis Hunte2622992011-05-05 00:05:47 +000013327 diag::warn_delegating_ctor_cycle)
Alexis Hunt27a761d2011-05-04 23:29:54 +000013328 << Ctor;
13329
Richard Smith802c4b72012-08-23 06:16:52 +000013330 // Don't add a note for a function delegating directly to itself.
Alexis Hunt27a761d2011-05-04 23:29:54 +000013331 if (TCanonical != Canonical)
13332 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
13333
13334 CXXConstructorDecl *C = Target;
13335 while (C->getCanonicalDecl() != Canonical) {
Craig Topperc3ec1492014-05-26 06:22:03 +000013336 const FunctionDecl *FNTarget = nullptr;
Alexis Hunt27a761d2011-05-04 23:29:54 +000013337 (void)C->getTargetConstructor()->hasBody(FNTarget);
13338 assert(FNTarget && "Ctor cycle through bodiless function");
13339
Richard Smith802c4b72012-08-23 06:16:52 +000013340 C = const_cast<CXXConstructorDecl*>(
13341 cast<CXXConstructorDecl>(FNTarget));
Alexis Hunt27a761d2011-05-04 23:29:54 +000013342 S.Diag(C->getLocation(), diag::note_which_delegates_to);
13343 }
13344 }
13345
Benjamin Kramer8bf44352013-07-24 15:28:33 +000013346 Invalid.insert(Current.begin(), Current.end());
Alexis Hunt27a761d2011-05-04 23:29:54 +000013347 Current.clear();
13348 } else {
13349 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
13350 }
13351}
13352
13353
Alexis Hunt6118d662011-05-04 05:57:24 +000013354void Sema::CheckDelegatingCtorCycles() {
13355 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
13356
Douglas Gregorbae31202011-07-27 21:57:17 +000013357 for (DelegatingCtorDeclsType::iterator
13358 I = DelegatingCtorDecls.begin(ExternalSource),
Alexis Hunt27a761d2011-05-04 23:29:54 +000013359 E = DelegatingCtorDecls.end();
Richard Smith802c4b72012-08-23 06:16:52 +000013360 I != E; ++I)
13361 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Alexis Hunt27a761d2011-05-04 23:29:54 +000013362
Benjamin Kramer8bf44352013-07-24 15:28:33 +000013363 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
13364 CE = Invalid.end();
13365 CI != CE; ++CI)
Alexis Hunt27a761d2011-05-04 23:29:54 +000013366 (*CI)->setInvalidDecl();
Alexis Hunt6118d662011-05-04 05:57:24 +000013367}
Peter Collingbourne7277fe82011-10-02 23:49:40 +000013368
Douglas Gregor3024f072012-04-16 07:05:22 +000013369namespace {
13370 /// \brief AST visitor that finds references to the 'this' expression.
13371 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
13372 Sema &S;
13373
13374 public:
13375 explicit FindCXXThisExpr(Sema &S) : S(S) { }
13376
13377 bool VisitCXXThisExpr(CXXThisExpr *E) {
13378 S.Diag(E->getLocation(), diag::err_this_static_member_func)
13379 << E->isImplicit();
13380 return false;
13381 }
13382 };
13383}
13384
13385bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
13386 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
13387 if (!TSInfo)
13388 return false;
13389
13390 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +000013391 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor3024f072012-04-16 07:05:22 +000013392 if (!ProtoTL)
13393 return false;
13394
13395 // C++11 [expr.prim.general]p3:
13396 // [The expression this] shall not appear before the optional
13397 // cv-qualifier-seq and it shall not appear within the declaration of a
13398 // static member function (although its type and value category are defined
13399 // within a static member function as they are within a non-static member
13400 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumi40edb2a2012-04-21 09:40:04 +000013401 // until the complete declarator is known. - end note ]
David Blaikie6adc78e2013-02-18 22:06:02 +000013402 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor3024f072012-04-16 07:05:22 +000013403 FindCXXThisExpr Finder(*this);
13404
13405 // If the return type came after the cv-qualifier-seq, check it now.
13406 if (Proto->hasTrailingReturn() &&
Alp Toker42a16a62014-01-25 23:51:36 +000013407 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
Douglas Gregor3024f072012-04-16 07:05:22 +000013408 return true;
13409
13410 // Check the exception specification.
Douglas Gregor433e0532012-04-16 18:27:27 +000013411 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
13412 return true;
13413
13414 return checkThisInStaticMemberFunctionAttributes(Method);
13415}
13416
13417bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
13418 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
13419 if (!TSInfo)
13420 return false;
13421
13422 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +000013423 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor433e0532012-04-16 18:27:27 +000013424 if (!ProtoTL)
13425 return false;
13426
David Blaikie6adc78e2013-02-18 22:06:02 +000013427 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor433e0532012-04-16 18:27:27 +000013428 FindCXXThisExpr Finder(*this);
13429
Douglas Gregor3024f072012-04-16 07:05:22 +000013430 switch (Proto->getExceptionSpecType()) {
Richard Smith0b3a4622014-11-13 20:01:57 +000013431 case EST_Unparsed:
Richard Smithf623c962012-04-17 00:58:00 +000013432 case EST_Uninstantiated:
Richard Smithd3b5c9082012-07-27 04:22:15 +000013433 case EST_Unevaluated:
Douglas Gregor3024f072012-04-16 07:05:22 +000013434 case EST_BasicNoexcept:
Douglas Gregor3024f072012-04-16 07:05:22 +000013435 case EST_DynamicNone:
13436 case EST_MSAny:
13437 case EST_None:
13438 break;
Douglas Gregor433e0532012-04-16 18:27:27 +000013439
Douglas Gregor3024f072012-04-16 07:05:22 +000013440 case EST_ComputedNoexcept:
13441 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
13442 return true;
Douglas Gregor433e0532012-04-16 18:27:27 +000013443
Douglas Gregor3024f072012-04-16 07:05:22 +000013444 case EST_Dynamic:
Aaron Ballmanb088fbe2014-03-17 15:38:09 +000013445 for (const auto &E : Proto->exceptions()) {
13446 if (!Finder.TraverseType(E))
Douglas Gregor3024f072012-04-16 07:05:22 +000013447 return true;
13448 }
13449 break;
13450 }
Douglas Gregor433e0532012-04-16 18:27:27 +000013451
13452 return false;
Douglas Gregor3024f072012-04-16 07:05:22 +000013453}
13454
13455bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
13456 FindCXXThisExpr Finder(*this);
13457
13458 // Check attributes.
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013459 for (const auto *A : Method->attrs()) {
Douglas Gregor3024f072012-04-16 07:05:22 +000013460 // FIXME: This should be emitted by tblgen.
Craig Topperc3ec1492014-05-26 06:22:03 +000013461 Expr *Arg = nullptr;
Douglas Gregor3024f072012-04-16 07:05:22 +000013462 ArrayRef<Expr *> Args;
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013463 if (const auto *G = dyn_cast<GuardedByAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000013464 Arg = G->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013465 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000013466 Arg = G->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013467 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000013468 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013469 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000013470 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013471 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
Douglas Gregor3024f072012-04-16 07:05:22 +000013472 Arg = ETLF->getSuccessValue();
Craig Topper5fc8fc22014-08-27 06:28:36 +000013473 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013474 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
Douglas Gregor3024f072012-04-16 07:05:22 +000013475 Arg = STLF->getSuccessValue();
Craig Topper5fc8fc22014-08-27 06:28:36 +000013476 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
Aaron Ballman18d85ae2014-03-20 16:02:49 +000013477 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000013478 Arg = LR->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013479 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000013480 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013481 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000013482 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013483 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000013484 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013485 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000013486 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013487 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000013488 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
Douglas Gregor3024f072012-04-16 07:05:22 +000013489
13490 if (Arg && !Finder.TraverseStmt(Arg))
13491 return true;
13492
13493 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
13494 if (!Finder.TraverseStmt(Args[I]))
13495 return true;
13496 }
13497 }
13498
13499 return false;
13500}
13501
Richard Smith2e321552014-11-12 02:00:47 +000013502void Sema::checkExceptionSpecification(
13503 bool IsTopLevel, ExceptionSpecificationType EST,
13504 ArrayRef<ParsedType> DynamicExceptions,
13505 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
13506 SmallVectorImpl<QualType> &Exceptions,
13507 FunctionProtoType::ExceptionSpecInfo &ESI) {
Douglas Gregor433e0532012-04-16 18:27:27 +000013508 Exceptions.clear();
Richard Smith8acb4282014-07-31 21:57:55 +000013509 ESI.Type = EST;
Douglas Gregor433e0532012-04-16 18:27:27 +000013510 if (EST == EST_Dynamic) {
13511 Exceptions.reserve(DynamicExceptions.size());
13512 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
13513 // FIXME: Preserve type source info.
13514 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
13515
Richard Smith2e321552014-11-12 02:00:47 +000013516 if (IsTopLevel) {
13517 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
13518 collectUnexpandedParameterPacks(ET, Unexpanded);
13519 if (!Unexpanded.empty()) {
13520 DiagnoseUnexpandedParameterPacks(
13521 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
13522 Unexpanded);
13523 continue;
13524 }
Douglas Gregor433e0532012-04-16 18:27:27 +000013525 }
13526
13527 // Check that the type is valid for an exception spec, and
13528 // drop it if not.
13529 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
13530 Exceptions.push_back(ET);
13531 }
Richard Smith8acb4282014-07-31 21:57:55 +000013532 ESI.Exceptions = Exceptions;
Douglas Gregor433e0532012-04-16 18:27:27 +000013533 return;
13534 }
Richard Smith8acb4282014-07-31 21:57:55 +000013535
Douglas Gregor433e0532012-04-16 18:27:27 +000013536 if (EST == EST_ComputedNoexcept) {
13537 // If an error occurred, there's no expression here.
13538 if (NoexceptExpr) {
13539 assert((NoexceptExpr->isTypeDependent() ||
13540 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
13541 Context.BoolTy) &&
13542 "Parser should have made sure that the expression is boolean");
Richard Smith2e321552014-11-12 02:00:47 +000013543 if (IsTopLevel && NoexceptExpr &&
13544 DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
Richard Smith8acb4282014-07-31 21:57:55 +000013545 ESI.Type = EST_BasicNoexcept;
Douglas Gregor433e0532012-04-16 18:27:27 +000013546 return;
13547 }
Richard Smith8acb4282014-07-31 21:57:55 +000013548
Douglas Gregor433e0532012-04-16 18:27:27 +000013549 if (!NoexceptExpr->isValueDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +000013550 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, nullptr,
Douglas Gregore2b37442012-05-04 22:38:52 +000013551 diag::err_noexcept_needs_constant_expression,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013552 /*AllowFold*/ false).get();
Richard Smith8acb4282014-07-31 21:57:55 +000013553 ESI.NoexceptExpr = NoexceptExpr;
Douglas Gregor433e0532012-04-16 18:27:27 +000013554 }
13555 return;
13556 }
13557}
13558
Richard Smith0b3a4622014-11-13 20:01:57 +000013559void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
13560 ExceptionSpecificationType EST,
13561 SourceRange SpecificationRange,
13562 ArrayRef<ParsedType> DynamicExceptions,
13563 ArrayRef<SourceRange> DynamicExceptionRanges,
13564 Expr *NoexceptExpr) {
13565 if (!MethodD)
13566 return;
13567
13568 // Dig out the method we're referring to.
13569 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
13570 MethodD = FunTmpl->getTemplatedDecl();
13571
13572 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
13573 if (!Method)
13574 return;
13575
13576 // Check the exception specification.
13577 llvm::SmallVector<QualType, 4> Exceptions;
13578 FunctionProtoType::ExceptionSpecInfo ESI;
13579 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
13580 DynamicExceptionRanges, NoexceptExpr, Exceptions,
13581 ESI);
13582
13583 // Update the exception specification on the function type.
13584 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
13585
13586 if (Method->isStatic())
13587 checkThisInStaticMemberFunctionExceptionSpec(Method);
13588
13589 if (Method->isVirtual()) {
13590 // Check overrides, which we previously had to delay.
13591 for (CXXMethodDecl::method_iterator O = Method->begin_overridden_methods(),
13592 OEnd = Method->end_overridden_methods();
13593 O != OEnd; ++O)
13594 CheckOverridingFunctionExceptionSpec(Method, *O);
13595 }
13596}
13597
John McCall5e77d762013-04-16 07:28:30 +000013598/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
13599///
13600MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
13601 SourceLocation DeclStart,
13602 Declarator &D, Expr *BitWidth,
13603 InClassInitStyle InitStyle,
13604 AccessSpecifier AS,
13605 AttributeList *MSPropertyAttr) {
13606 IdentifierInfo *II = D.getIdentifier();
13607 if (!II) {
13608 Diag(DeclStart, diag::err_anonymous_property);
Craig Topperc3ec1492014-05-26 06:22:03 +000013609 return nullptr;
John McCall5e77d762013-04-16 07:28:30 +000013610 }
13611 SourceLocation Loc = D.getIdentifierLoc();
13612
13613 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13614 QualType T = TInfo->getType();
13615 if (getLangOpts().CPlusPlus) {
13616 CheckExtraCXXDefaultArguments(D);
13617
13618 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13619 UPPC_DataMemberType)) {
13620 D.setInvalidType();
13621 T = Context.IntTy;
13622 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
13623 }
13624 }
13625
13626 DiagnoseFunctionSpecifiers(D.getDeclSpec());
13627
13628 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
13629 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
13630 diag::err_invalid_thread)
13631 << DeclSpec::getSpecifierName(TSCS);
13632
13633 // Check to see if this name was declared as a member previously
Craig Topperc3ec1492014-05-26 06:22:03 +000013634 NamedDecl *PrevDecl = nullptr;
John McCall5e77d762013-04-16 07:28:30 +000013635 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
13636 LookupName(Previous, S);
13637 switch (Previous.getResultKind()) {
13638 case LookupResult::Found:
13639 case LookupResult::FoundUnresolvedValue:
13640 PrevDecl = Previous.getAsSingle<NamedDecl>();
13641 break;
13642
13643 case LookupResult::FoundOverloaded:
13644 PrevDecl = Previous.getRepresentativeDecl();
13645 break;
13646
13647 case LookupResult::NotFound:
13648 case LookupResult::NotFoundInCurrentInstantiation:
13649 case LookupResult::Ambiguous:
13650 break;
13651 }
13652
13653 if (PrevDecl && PrevDecl->isTemplateParameter()) {
13654 // Maybe we will complain about the shadowed template parameter.
13655 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13656 // Just pretend that we didn't see the previous declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +000013657 PrevDecl = nullptr;
John McCall5e77d762013-04-16 07:28:30 +000013658 }
13659
13660 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
Craig Topperc3ec1492014-05-26 06:22:03 +000013661 PrevDecl = nullptr;
John McCall5e77d762013-04-16 07:28:30 +000013662
13663 SourceLocation TSSL = D.getLocStart();
John McCall5e77d762013-04-16 07:28:30 +000013664 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
Richard Smithf7981722013-11-22 09:01:48 +000013665 MSPropertyDecl *NewPD = MSPropertyDecl::Create(
13666 Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId);
John McCall5e77d762013-04-16 07:28:30 +000013667 ProcessDeclAttributes(TUScope, NewPD, D);
13668 NewPD->setAccess(AS);
13669
13670 if (NewPD->isInvalidDecl())
13671 Record->setInvalidDecl();
13672
13673 if (D.getDeclSpec().isModulePrivateSpecified())
13674 NewPD->setModulePrivate();
13675
13676 if (NewPD->isInvalidDecl() && PrevDecl) {
13677 // Don't introduce NewFD into scope; there's already something
13678 // with the same name in the same scope.
13679 } else if (II) {
13680 PushOnScopeChains(NewPD, S);
13681 } else
13682 Record->addDecl(NewPD);
13683
13684 return NewPD;
13685}